Do a topological sort on the dependency graph dict.
482434
def find_order(graph):
    '''
    
    '''
    while graph:
        # Find all items without a parent
        leftmost = [l for l, s in graph.items() if not s]
        if not leftmost:
            raise ValueError('Dependency cycle detected! %s' % graph)
        # If there is more than one, sort them for predictable order
        leftmost.sort()
        for result in leftmost:
            # Yield and remove them from the graph
            yield result
            graph.pop(result)
            for bset in graph.values():
                bset.discard(result)
143974
def have_cycle(graph:dict) -> frozenset:
    
    # topological sort
    walked = set()  # walked nodes
    nodes = frozenset(it.chain(it.chain.from_iterable(graph.values()), graph.keys()))  # all nodes of the graph
    preds = reversed_graph(graph)  # succ: preds
    last_walked_len = -1
    while last_walked_len != len(walked):
        last_walked_len = len(walked)
        for node in nodes - walked:
            if len(preds.get(node, set()) - walked) == 0:
                walked.add(node)
    return frozenset(nodes - walked)
940644
def resolve
      list = dependency_list.sort { |a, b| a.last.size <=> b.last.size }
      resolve_list(list)
    end
774436
def depends_on(options, **kwargs):
    
    include_graph = options['include_graph']

    include_graph.render('full_graph')

    result = None

    if 'graph' in kwargs:
        name = kwargs['graph']
        del kwargs['graph']

        result = _Result(kwargs)

        dep_graph = build_dependency_graph(include_graph, **kwargs)

        dep_graph.render(name)

        result.add_result("Rendered dep graph at {}".format(name))

    else:
        result = _Result(kwargs)

        dep_graph = build_dependency_graph(include_graph, **kwargs)

        for node, edges in dep_graph:
            if node not in kwargs:
                result.add_result(node)

    return result
109973
def _topological_sort(self):
        
        sorted_graph = []
        node_map = self._graph.get_nodes()

        nodes = [NodeVisitor(node_map[node]) for node in node_map]

        def get_pointers_for_edge_nodes(visitor_decorated_node):
            edges = []
            edge_ids = visitor_decorated_node.get_node().get_edges()
            for node in nodes:
                if node.get_id() in edge_ids:
                    edges.append(node)

            return edges

        # node is initially weighted with the number of immediate dependencies
        for node in nodes:
            for edge in get_pointers_for_edge_nodes(node):
                edge.increment()

        # Start with a list of nodes who have no dependents
        resolved = [node for node in nodes if node.get_weight() == 0]

        while resolved:
            node = resolved.pop()
            sorted_graph.append(node)

            for edge in get_pointers_for_edge_nodes(node):
                edge.decrement()
                if edge.get_weight() == 0:
                    resolved.append(edge)

        self._circular_dependencies = [
            node.get_node() for node in nodes if node.get_weight() > 0]

        self._sorted_nodes = list(reversed(
            [node.get_node() for node in sorted_graph]))
1116991
def dependencies_graph(nodes=nil)
      nodes = @resolver.getDependenciesGraph() unless nodes

      graph = {}
      if Naether.platform == 'java'
        nodes.each do |k,v|
          deps = dependencies_graph(v)
          graph[k] = Naether::Java.convert_to_ruby_hash( deps )
        end
      else
        iterator = nodes.entrySet().iterator();
        while iterator.hasNext()
          entry = iterator.next()
          deps = dependencies_graph(entry.getValue())
          graph[entry.getKey().toString()] = Naether::Java.convert_to_ruby_hash( deps )
        end
      end

      graph
    end
477559
def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]
619931
def topological_order_dfs(graph):
    
    n = len(graph)
    order = []
    times_seen = [-1] * n
    for start in range(n):
        if times_seen[start] == -1:
            times_seen[start] = 0
            to_visit = [start]
            while to_visit:
                node = to_visit[-1]
                children = graph[node]
                if times_seen[node] == len(children):
                    to_visit.pop()
                    order.append(node)
                else:
                    child = children[times_seen[node]]
                    times_seen[node] += 1
                    if times_seen[child] == -1:
                        times_seen[child] = 0
                        to_visit.append(child)
    return order[::-1]
105267
def topological_order(self):
        """"""
        q = Queue()
        in_degree = {}
        for i in range(self.n_nodes):
            in_degree[i] = 0
        for u in range(self.n_nodes):
            for v, _ in self.adj_list[u]:
                in_degree[v] += 1
        for i in range(self.n_nodes):
            if in_degree[i] == 0:
                q.put(i)

        order_list = []
        while not q.empty():
            u = q.get()
            order_list.append(u)
            for v, _ in self.adj_list[u]:
                in_degree[v] -= 1
                if in_degree[v] == 0:
                    q.put(v)
        return order_list
530645
def get_dependent_dists(dists, dist):
    
    if dist not in dists:
        raise DistlibException('given distribution %r is not a member '
                               'of the list' % dist.name)
    graph = make_graph(dists)

    dep = [dist]  # dependent distributions
    todo = graph.reverse_list[dist]  # list of nodes we should inspect

    while todo:
        d = todo.pop()
        dep.append(d)
        for succ in graph.reverse_list[d]:
            if succ not in dep:
                todo.append(succ)

    dep.pop(0)  # remove dist from dep, was there to prevent infinite loops
    return dep
419531
def order(self, piecewise=False):
        
        if piecewise:
            return {k: v.order() for k, v in self.items()}
        return self.master_graph.order()
494235
function flagCircularDependencies(graph) {
	var includes = require("lodash/includes");
	var nodes = Array.isArray(graph) ? graph : require("lodash/values")(graph);

	for (var i = 0; i < nodes.length; i += 1) {
		var curr = nodes[i];

		for (var j = i + 1; j < nodes.length; j += 1) {
			var next = nodes[j];

			if (
				includes(curr.dependencies, next.load.name) &&
				includes(next.dependencies, curr.load.name)
			) {
				curr.load.circular = true;
				next.load.circular = true;
			}
		}
	}

	return graph;
}
737858
def topological_order(graph):
    
    V = range(len(graph))
    indeg = [0 for _ in V]
    for node in V:            # compute indegree
        for neighbor in graph[node]:
            indeg[neighbor] += 1
    Q = [node for node in V if indeg[node] == 0]
    order = []
    while Q:
        node = Q.pop()        # node without incoming arrows
        order.append(node)
        for neighbor in graph[node]:
            indeg[neighbor] -= 1
            if indeg[neighbor] == 0:
                Q.append(neighbor)
    return order
780246
public Map<String,Map> getDependenciesGraph() {
        Map<String,Map> graph = new HashMap<String,Map>();
        
        if ( preorderedNodeList != null ) {

            List<DependencyNode> nodes = preorderedNodeList.getNodes();
            Set<String> notations = new HashSet<String>();
            
            for (Dependency dependency : getDependencies() ) {
                notations.add(Notation.generate(dependency));
            }
            
            for( DependencyNode node: nodes) {
                String notation = Notation.generate( node.getDependency().getArtifact() );
            
                // Show Graph with dependenices as root and transitive as children
                if ( notations.contains( notation ) ) {
                    graph.put( notation, mapDependenciesFromNode( node ) );
                }
            }
        }
        
        return graph;
    }
1029256
def sort(self):
        
        while self.nodes:
            iterated = False
            for node in self.leaf_nodes():
                iterated = True
                self.prune_node(node)
                yield node
            if not iterated:
                raise CyclicGraphError("Sorting has found a cyclic graph.")
575669
def resolve_dependency_graph(self, target):
        
        targets = self.deep_dependendants(target)
        # print "deep dependants:", targets
        return sorted(targets,
                      cmp=lambda a, b:
                          1 if b in self.deep_dependendants(a) else
                          -1 if a in self.deep_dependendants(b) else
                          0)
200154
def __sort_adjacency_lists(dfs_data):
    """"""
    new_adjacency_lists = {}

    adjacency_lists = dfs_data['adj']
    edge_weights = dfs_data['edge_weights']
    edge_lookup = dfs_data['edge_lookup']

    for node_id, adj_list in list(adjacency_lists.items()):
        node_weight_lookup = {}
        frond_lookup = {}
        for node_b in adj_list:
            edge_id = dfs_data['graph'].get_first_edge_id_by_node_ids(node_id, node_b)
            node_weight_lookup[node_b] = edge_weights[edge_id]
            frond_lookup[node_b] = 1 if edge_lookup[edge_id] == 'backedge' else 2

        # Fronds should be before branches if the weights are equal
        new_list = sorted(adj_list, key=lambda n: frond_lookup[n])

        # Sort by weights
        new_list.sort(key=lambda n: node_weight_lookup[n])

        # Add the new sorted list to the new adjacency list lookup table
        new_adjacency_lists[node_id] = new_list

    return new_adjacency_lists