Get all the leafs of the graph. Time complexity: O(|V|).
343090
function() {

        var sinks = [];
        joint.util.forIn(this._nodes, function(exists, node) {
            if (!this._out[node] || joint.util.isEmpty(this._out[node])) {
                sinks.push(this.getCell(node));
            }
        }.bind(this));
        return sinks;
    }
520315
def leaf_to_root(self):
        """"""
        node = self
        subp = []
        while node:
            if node.type == TYPE_ALTERNATIVES:
                node.alternatives.append(subp)
                if len(node.alternatives) == len(node.children):
                    #last alternative
                    subp = [tuple(node.alternatives)]
                    node.alternatives = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == TYPE_GROUP:
                node.group.append(subp)
                #probably should check the number of leaves
                if len(node.group) == len(node.children):
                    subp = get_characteristic_subpattern(node.group)
                    node.group = []
                    node = node.parent
                    continue
                else:
                    node = node.parent
                    subp = None
                    break

            if node.type == token_labels.NAME and node.name:
                #in case of type=name, use the name instead
                subp.append(node.name)
            else:
                subp.append(node.type)

            node = node.parent
        return subp
255762
def graphs(self):
        """"""
        result = Dummy()
        for graph in graphs.__all__:
            cls = getattr(graphs, graph)
            setattr(result, cls.short_name, cls(self))
        return result
299671
private void compute() {

        int n = graph.length;

        // the set 'S' contains the pairs of vertices adjacent to 'y'
        int[] s = new int[n];
        int sizeOfS;

        // order the vertices by degree
        int[] vertices = new int[n];
        for (int v = 0; v < n; v++) {
            vertices[ordering[v]] = v;
        }

        // if the graph is known to be a biconnected component (prepossessing)
        // and there is at least one vertex with a degree > 2 we can skip all
        // vertices of degree 2.
        //
        // otherwise the smallest possible cycle is {0,1,2} (no parallel edges
        // or loops) we can therefore don't need to do the first two shortest
        // paths calculations
        int first = biconnected && nDeg2Vertices < n ? nDeg2Vertices : 2;

        for (int i = first; i < n; i++) {
            final int r = vertices[i];

            ShortestPaths pathsFromR = new ShortestPaths(graph, null, r, limit / 2, ordering);

            // we only check the vertices which belong to the set Vr. this
            // set is vertices reachable from 'r' by only travelling though
            // vertices smaller then r. In the ShortestPaths API this is
            // name 'isPrecedingPathTo'.
            //
            // using Vr allows us to prune the number of vertices to check and
            // discover each cycle exactly once. This is possible as for each
            // simple cycle there is only one vertex with a maximum ordering.
            for (int j = 0; j < i; j++) {
                final int y = vertices[j];
                if (!pathsFromR.isPrecedingPathTo(y)) continue;

                // start refilling set 's' by resetting it's size
                sizeOfS = 0;

                // z is adjacent to y and belong to Vr
                for (final int z : graph[y]) {
                    if (!pathsFromR.isPrecedingPathTo(z)) continue;

                    final int distToZ = pathsFromR.distanceTo(z);
                    final int distToY = pathsFromR.distanceTo(y);

                    // the distance of the path to z is one less then the
                    // path to y. the vertices are adjacent, therefore z must
                    // also belong to the shortest path from r to y.
                    //
                    // we queue up (in 's') all the vertices adjacent to y for
                    // which this holds and then check these once we've processed
                    // all adjacent vertices
                    //
                    //  / ¯ ¯ z1 \          z1 and z2 are added to 's' and
                    // r          y - z3    checked later as p and q (see below)
                    //  \ _ _ z2 /
                    //
                    if (distToZ + 1 == distToY) {
                        s[sizeOfS++] = z;
                    }

                    // if the distances are equal we could have an odd cycle
                    // but we need to check the paths only intersect at 'r'.
                    //
                    // we check the intersect for cases like this, shortest
                    // cycle here is {p .. y, z .. p} not {r .. y, z .. r}
                    //
                    //           / ¯ ¯ y         / ¯ ¯ \ / ¯ ¯ y
                    //  r - - - p      |    or  r       p      |
                    //           \ _ _ z         \ _ _ / \ _ _ z
                    //
                    // if it's the shortest cycle then the intersect is just {r}
                    //
                    //  / ¯ ¯ y
                    // r      |
                    //  \ _ _ z
                    //
                    else if (distToZ == distToY && ordering[z] < ordering[y]) {
                        final int[] pathToY = pathsFromR.pathTo(y);
                        final int[] pathToZ = pathsFromR.pathTo(z);
                        if (singletonIntersect(pathToZ, pathToY)) {
                            Cycle cycle = new OddCycle(pathsFromR, pathToY, pathToZ);
                            add(cycle);
                        }
                    }
                }

                // check each pair vertices adjacent to 'y' for an
                // even cycle, as with the odd cycle we ensure the intersect
                // of the paths {r .. p} and {r .. q} is {r}.
                //
                //  / ¯ ¯ p \
                // r         y
                //  \ _ _ q /
                //
                for (int k = 0; k < sizeOfS; k++) {
                    for (int l = k + 1; l < sizeOfS; l++) {
                        int[] pathToP = pathsFromR.pathTo(s[k]);
                        int[] pathToQ = pathsFromR.pathTo(s[l]);
                        if (singletonIntersect(pathToP, pathToQ)) {
                            Cycle cycle = new EvenCycle(pathsFromR, pathToP, y, pathToQ);
                            add(cycle);
                        }
                    }
                }
            }
        }
    }
317806
def components(self):
    
    skel, forest = self._compute_components()

    if len(forest) == 0:
      return []
    elif len(forest) == 1:
      return [ skel ]

    orig_verts = { tuple(coord): i for i, coord in enumerate(skel.vertices) }      

    skeletons = []
    for edge_list in forest:
      edge_list = np.array(edge_list, dtype=np.uint32)
      edge_list = np.unique(edge_list, axis=0)
      vert_idx = np.unique(edge_list.flatten())
      vert_list = skel.vertices[vert_idx]
      radii = skel.radii[vert_idx]
      vtypes = skel.vertex_types[vert_idx]

      new_verts = { orig_verts[tuple(coord)]: i for i, coord in enumerate(vert_list) }

      edge_vector_map = np.vectorize(lambda x: new_verts[x])
      edge_list = edge_vector_map(edge_list)

      skeletons.append(
        PrecomputedSkeleton(vert_list, edge_list, radii, vtypes, skel.id)
      )

    return skeletons
363700
def map_leafs(func, mapping):
    """"""

    def _inner(mapping, path=None):
        if path is None:
            path = []

        for key, val in mapping.items():
            if isinstance(val, collections.Mapping):
                _inner(val, path + [key])
            else:
                mapping[key] = func(val, path=path+[key])

        return mapping

    return _inner(copy.deepcopy(mapping))
836673
def _build_kth_tree(self):
        """"""
        neg_tau = -1.0 * abs(self.tau_matrix)
        edges = self.previous_tree.edges
        visited = set([0])
        unvisited = set(range(self.n_nodes))

        while len(visited) != self.n_nodes:
            adj_set = set()
            for x in visited:
                for k in range(self.n_nodes):
                    # check if (x,k) is a valid edge in the vine
                    if k not in visited and k != x and self._check_contraint(edges[x], edges[k]):
                        adj_set.add((x, k))

            # find edge with maximum tau
            if len(adj_set) == 0:
                visited.add(list(unvisited)[0])
                continue

            pairs = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]
            left_parent, right_parent = Edge.sort_edge([edges[pairs[0]], edges[pairs[1]]])

            new_edge = Edge.get_child_edge(len(visited) - 1, left_parent, right_parent)
            new_edge.tau = self.tau_matrix[pairs[0], pairs[1]]
            self.edges.append(new_edge)

            visited.add(pairs[1])
            unvisited.remove(pairs[1])
119635
def all_edges(self, node):
        
        return set(self.inc_edges(node) + self.out_edges(node))
83233
def get_obs_leaves(self):
        
        obs_leaves = []
        for n in self:
            if n.is_leaf:
                if isinstance(n, ModelNode):
                    l = n.parent
                else:
                    l = n
            if l not in obs_leaves:
                obs_leaves.append(l)
        return obs_leaves
214070
def get_roots(self):
        
        return [node for node, in_degree in dict(self.in_degree()).items() if in_degree == 0]
527815
def list(cls, name, parent=None, interleave=None):
        """"""
        node = cls.leaf_list(name, parent, interleave=interleave)
        node.keys = []
        node.keymap = {}
        return node
666342
def get_leaf_children(gos_user, go2obj_arg):
    """"""
    childgoid2obj = {}
    for goid_usr in gos_user:
        goobj_usr = go2obj_arg[goid_usr]
        fill_childgoid2obj(childgoid2obj, goobj_usr)
    return set(go for go, o in childgoid2obj.items() if not o.children)
605932
def get_gene_leaves(graph) -> Iterable[BaseEntity]:
    
    for node in get_nodes_by_function(graph, GENE):
        if graph.in_degree(node) != 0:
            continue

        if graph.out_degree(node) != 1:
            continue

        _, _, d = list(graph.out_edges(node, data=True))[0]

        if d[RELATION] == TRANSCRIBED_TO:
            yield node
91072
def num_trees(n):
    
    dp = [0] * (n+1)
    dp[0] = 1
    dp[1] = 1
    for i in range(2, n+1):
        for j in range(i+1):
            dp[i] += dp[i-j] * dp[j-1]
    return dp[-1]
87000
def get_leaf(self, index):
        
        leaf_level_index = len(self.tree['levels']) - 1
        if index < 0 or index > len(self.tree['levels'][leaf_level_index]) - 1:
            # index is out of bounds
            return None
        return self.tree['levels'][leaf_level_index][index]
362295
def get_input_nodes(G: nx.DiGraph) -> List[str]:
    
    return [n for n, d in G.in_degree() if d == 0]
1171451
def cut_nodes_edges(graph):
    
    n = len(graph)
    time = 0
    num = [None] * n
    low = [n] * n
    father = [None] * n        # father[v] = None if root else father of v
    critical_childs = [0] * n  # c_c[u] = #childs v s.t. low[v] >= num[u]
    times_seen = [-1] * n
    for start in range(n):
        if times_seen[start] == -1:               # init DFS path
            times_seen[start] = 0
            to_visit = [start]
            while to_visit:
                node = to_visit[-1]
                if times_seen[node] == 0:         # start processing
                    num[node] = time
                    time += 1
                    low[node] = float('inf')
                children = graph[node]
                if times_seen[node] == len(children):  # end processing
                    to_visit.pop()
                    up = father[node]            # propagate low to father
                    if up is not None:
                        low[up] = min(low[up], low[node])
                        if low[node] >= num[up]:
                            critical_childs[up] += 1
                else:
                    child = children[times_seen[node]]   # next arrow
                    times_seen[node] += 1
                    if times_seen[child] == -1:   # not visited yet
                        father[child] = node      # link arrow
                        times_seen[child] = 0
                        to_visit.append(child)    # (below) back arrow
                    elif num[child] < num[node] and father[node] != child:
                        low[node] = min(low[node], num[child])
    cut_edges = []
    cut_nodes = []                                # extract solution
    for node in range(n):
        if father[node] is None:                  # characteristics
            if critical_childs[node] >= 2:
                cut_nodes.append(node)
        else:                                     # internal nodes
            if critical_childs[node] >= 1:
                cut_nodes.append(node)
            if low[node] >= num[node]:
                cut_edges.append((father[node], node))
    return cut_nodes, cut_edges