Fallback for cases in which the graph has cycles.
979852
def sort_cyclic_graph_best_effort(graph, pick_first='head'):
    """"""
    ordered = []
    visited = set()
    # Go first on the pick_first chain then go back again on the others
    # that were not visited. Given the way the graph is built both chains
    # will always contain all the elements.
    if pick_first == 'head':
        fst_attr, snd_attr = ('head_node', 'update_node')
    else:
        fst_attr, snd_attr = ('update_node', 'head_node')

    current = FIRST
    while current is not None:
        visited.add(current)
        current = getattr(graph[current], fst_attr)
        if current not in visited and current is not None:
            ordered.append(current)
    current = FIRST
    while current is not None:
        visited.add(current)
        current = getattr(graph[current], snd_attr)
        if current not in visited and current is not None:
            ordered.append(current)
    return ordered
378993
def digraph_walker_backwards(graph, element, call_back):
    """"""
    call_back(graph, element)
    for predecessor in graph.predecessors(element):
        call_back(graph, predecessor)
    for predecessor in graph.predecessors(element):
        digraph_walker_backwards(graph, predecessor, call_back)
332301
def key_cycles():
    
    graph = garbage()
    sccs = graph.strongly_connected_components()
    return [scc for scc in sccs if _is_orphan(scc, graph)]
745473
public static boolean hasNegativeCycle(Object sourceOrDest,
			DirectedGraph g, Mode mode) {
		return calcShortestDistances(sourceOrDest, g, mode) == null;
	}
734041
function debugOrdering(g) {
  var layerMatrix = util.buildLayerMatrix(g);

  var h = new Graph({ compound: true, multigraph: true }).setGraph({});

  _.forEach(g.nodes(), function(v) {
    h.setNode(v, { label: v });
    h.setParent(v, "layer" + g.node(v).rank);
  });

  _.forEach(g.edges(), function(e) {
    h.setEdge(e.v, e.w, {}, e.name);
  });

  _.forEach(layerMatrix, function(layer, i) {
    var layerV = "layer" + i;
    h.setNode(layerV, { rank: "same" });
    _.reduce(layer, function(u, v) {
      h.setEdge(u, v, { style: "invis" });
      return v;
    });
  });

  return h;
}
1247705
function findMinSlackEdge(t, g) {
  return _.minBy(g.edges(), function(e) {
    if (t.hasNode(e.v) !== t.hasNode(e.w)) {
      return slack(g, e);
    }
  });
}
561948
function spfa(graph, s) {
  const distance = {};
  const previous = {};
  const queue = {};
  const isInQue = {};
  const cnt = {};
  let head = 0;
  let tail = 1;
  // initialize
  distance[s] = 0;
  queue[0] = s;
  isInQue[s] = true;
  cnt[s] = 1;
  graph.vertices.forEach(v => {
    if (v !== s) {
      distance[v] = Infinity;
      isInQue[v] = false;
      cnt[v] = 0;
    }
  });

  let currNode;
  while (head !== tail) {
    currNode = queue[head++];
    isInQue[currNode] = false;
    const neighbors = graph.neighbors(currNode);
    for (let i = 0; i < neighbors.length; i++) {
      const v = neighbors[i];
      // relaxation
      const newDistance = distance[currNode] + graph.edge(currNode, v);
      if (newDistance < distance[v]) {
        distance[v] = newDistance;
        previous[v] = currNode;
        if (!isInQue[v]) {
          queue[tail++] = v;
          isInQue[v] = true;
          cnt[v]++;
          if (cnt[v] > graph.vertices.size) {
            // indicates negative-weighted cycle
            return {
              distance: {}
            };
          }
        }
      }
    }
  }

  return {
    distance,
    previous
  };
}
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)
124769
def total_cycles(self) -> int:
        """"""
        return sum((int(re.sub(r'\D', '', op)) for op in self.tokens))
746468
def euler_tour_dfs(G, source=None):
    
    if source is None:
        # produce edges for all components
        nodes = G
    else:
        # produce edges for components with source
        nodes = [source]
    yielder = []
    visited = set()
    for start in nodes:
        if start in visited:
            continue
        visited.add(start)
        stack = [(start, iter(G[start]))]
        while stack:
            parent, children = stack[-1]
            try:
                child = next(children)
                if child not in visited:
                    # yielder += [[parent, child]]
                    yielder += [parent]
                    visited.add(child)
                    stack.append((child, iter(G[child])))
            except StopIteration:
                if stack:
                    last = stack[-1]
                    yielder += [last[0]]
                stack.pop()
    return yielder
112310
function forEachEdge(graph, type, callback) {
  if (graph.size === 0)
    return;

  if (type === 'mixed' || type === graph.type) {
    graph._edges.forEach((data, key) => {

      const {attributes, source, target} = data;

      callback(
        key,
        attributes,
        source.key,
        target.key,
        source.attributes,
        target.attributes
      );
    });
  }
  else {
    const mask = type === 'undirected';

    graph._edges.forEach((data, key) => {
      if ((data instanceof UndirectedEdgeData) === mask) {

        const {attributes, source, target} = data;

        callback(
          key,
          attributes,
          source.key,
          target.key,
          source.attributes,
          target.attributes
        );
      }
    });
  }
}
697764
def cyclic(self):
        ""
        return any(isinstance(val, Cycle) for val in self.kwargs.values())
505632
public function hasCycle()
    {
        $components = new ConnectedComponents($this->graph);
        if ($components->isSingle()) {
            $alg = new Degree($this->graph);

            foreach ($this->graph->getVertices() as $vertex) {
                // uneven degree => fail
                if ($alg->getDegreeVertex($vertex) & 1) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
806752
def cyclic_deps(options, **kwargs):
    
    call_graph = options['call_graph']

    call_result = _CallResult(cyclic_test(call_graph))
    
    return call_result
7420
function buildDependencyGraph(module, dependencies, graph) {
	if (module && !graph[module]) {
		graph[module] = [];
	}

	var dependencyNames = Object.keys(dependencies);
	dependencyNames.forEach(function(dependencyName) {
		var dependency = dependencies[dependencyName];

		if (module && graph[module].indexOf(dependencyName) === -1) {
			graph[module].push(dependencyName);
		}

		// Traverse down to this dependency dependencies:
		// Dependency-ception.
		if (dependency.dependencies) {
			buildDependencyGraph(dependencyName, dependency.dependencies, graph);
		}
	});
}
1315246
def reroot_graph(G: nx.DiGraph, node: str) -> nx.DiGraph:
    """"""
    G = G.copy()
    for n, successors in list(nx.bfs_successors(G, source=node)):
        for s in successors:
            G.add_edge(s, n, **G.edges[n, s])
            G.remove_edge(n, s)
    return G
188155
def is_cyclic(graph):
    
    path = set()

    def visit(vertex):
        path.add(vertex)
        for neighbour in graph.get(vertex, ()):
            if neighbour in path or visit(neighbour):
                return True
        path.remove(vertex)
        return False

    return any(visit(v) for v in graph)