Make unique nodes for sequence graph.
175037
def make_sequence(seq, name="S"):
    
    return ["{}_{}_{}".format(name, i, x) for i, x in enumerate(seq)]
279638
def unique_authors(self, limit):
        """"""
        seen = set()
        if limit == 0:
            limit = None
        seen_add = seen.add  # Assign to variable, so not resolved each time
        return [x.author for x in self.sorted_commits[:limit]
                if not (x.author in seen or seen_add(x.author))]
11393
function createParagraph(nodes) {
    const firstNode = nodes[0];
    const lastNode = nodes[nodes.length - 1];
    return {
        type: Syntax.Paragraph,
        raw: nodes
            .map(function(node) {
                return node.raw;
            })
            .join(""),
        range: [firstNode.range[0], lastNode.range[1]],
        loc: {
            start: {
                line: firstNode.loc.start.line,
                column: firstNode.loc.start.column
            },
            end: {
                line: lastNode.loc.end.line,
                column: lastNode.loc.end.column
            }
        },
        children: nodes
    };
}
867867
def build_unique_fragments(self):
        
        self.set_node_attributes()

        graph = self.graph.to_undirected()

        nm = iso.categorical_node_match("specie", "ERROR")

        # find all possible fragments, aka connected induced subgraphs
        all_fragments = []
        for ii in range(1, len(self.molecule)):
            for combination in combinations(graph.nodes, ii):
                subgraph = nx.subgraph(graph, combination)
                if nx.is_connected(subgraph):
                    all_fragments.append(subgraph)

        # narrow to all unique fragments using graph isomorphism
        unique_fragments = []
        for fragment in all_fragments:
            if not [nx.is_isomorphic(fragment, f, node_match=nm)
                    for f in unique_fragments].count(True) >= 1:
                unique_fragments.append(fragment)

        # convert back to molecule graphs
        unique_mol_graphs = []
        for fragment in unique_fragments:
            mapping = {e: i for i, e in enumerate(sorted(fragment.nodes))}
            remapped = nx.relabel_nodes(fragment, mapping)

            species = nx.get_node_attributes(remapped, "specie")
            coords = nx.get_node_attributes(remapped, "coords")

            edges = {}

            for from_index, to_index, key in remapped.edges:
                edge_props = fragment.get_edge_data(from_index, to_index, key=key)

                edges[(from_index, to_index)] = edge_props

            unique_mol_graphs.append(self.with_edges(Molecule(species=species,
                                                              coords=coords,
                                                              charge=self.molecule.charge),
                                                     edges))
        return unique_mol_graphs
912203
def match_seq(self, nodes, results=None):
        """"""
        for c, r in self.generate_matches(nodes):
            if c == len(nodes):
                if results is not None:
                    results.update(r)
                    if self.name:
                        results[self.name] = list(nodes)
                return True
        return False
991378
def _make_tasks_unique(tasks):
        """"""
        unique_tasks = []
        prev_tasks = set()

        for task in tasks:
            if task in prev_tasks:
                task = copy.deepcopy(task)
            unique_tasks.append(task)

        return unique_tasks
368583
def unique(iterable):
    """"""
    seen = set()
    for item in iterable:
        if item not in seen:
            seen.add(item)
            yield item
908970
private void createMissingSpanningRelations(SDocumentGraph graph,
    FastInverseMap<Long, SNode> nodeByRankID,
    TreeMap<Long, SToken> tokenByIndex,
    Map<String, ComponentEntry> componentForSpan,
    AtomicInteger numberOfRelations)
  {

    // add the missing spanning relations for each continuous span of the graph
    for (SSpan span : graph.getSpans())
    {
      long pre=1;
      RelannisNodeFeature featSpan = RelannisNodeFeature.extract(span);      
      ComponentEntry spanComponent = componentForSpan.get(span.getId());
      if (spanComponent != null && featSpan != null 
        && featSpan.getLeftToken() >= 0 && featSpan.getRightToken() >= 0)
      {
        for (long i = featSpan.getLeftToken(); i <= featSpan.getRightToken();
          i++)
        {
          SToken tok = tokenByIndex.get(i);
          if (tok != null)
          {
            boolean missing = true;
            List<SRelation<SNode, SNode>> existingRelations = graph.getRelations(span.getId(),
              tok.getId());
            if (existingRelations != null)
            {
              for (Relation e : existingRelations)
              {
                if (e instanceof SSpanningRelation)
                {
                  missing = false;
                  break;
                }
              }
            } // end if relations exist

            if (missing)
            {
              String type = "c";

              SLayer layer
                = findOrAddSLayer(spanComponent.getNamespace(), graph);

              createNewRelation(graph, span, tok, null, type,
                spanComponent.getId(), layer,
                pre++, nodeByRankID, numberOfRelations);
            }
          } // end if token exists
        } // end for each covered token index
      }
    } // end for each span
  }
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
1019817
def create_copy_without_data(G):
    """"""
    H = nx.Graph()
    for i in H.nodes_iter():
        H.node[i] = {}
    return H
788085
def _make_nodes(self, dsk_graph, array, iteration_order, masked,
                    top=False):
        
        cache_key = _array_id(array, iteration_order, masked)
        # By the end of this function Nodes will be a dictionary with one item
        # per chunk to be processed for this array.
        nodes = self._node_cache.get(cache_key, None)

        if nodes is None:
            if hasattr(array, 'streams_handler'):
                nodes = self._make_stream_handler_nodes(dsk_graph, array,
                                                        iteration_order,
                                                        masked)
            else:
                nodes = {}
                chunks = []

                name = '{}\n{}'.format(array.__class__.__name__, array.shape)
                biggus_chunk_func = self.lazy_chunk_creator(name)

                chunk_index_gen = biggus._init.ProducerNode.chunk_index_gen
                for chunk_key in chunk_index_gen(array.shape,
                                                 iteration_order[::-1]):
                    biggus_array = array[chunk_key]
                    pretty_key = ', '.join(map(slice_repr, chunk_key))
                    chunk_id = ('chunk shape: {}\nsource key: [{}]\n\n{}'
                                ''.format(biggus_array.shape, pretty_key,
                                          uuid.uuid4()))
                    task = (biggus_chunk_func, chunk_key, biggus_array, masked)
                    chunks.append(task)
                    assert chunk_id not in dsk_graph
                    dsk_graph[chunk_id] = task
                    nodes[chunk_id] = task
            self._node_cache[cache_key] = nodes
        return nodes
518277
def build(self):
        """"""

        assert not self.final, 'Trying to mutate a final graph.'

        # Replace each strongly connected component with a single node `NodeSet`
        for scc in sorted(nx.kosaraju_strongly_connected_components(self.graph),
                          key=len, reverse=True):
            if len(scc) == 1:
                break

            self.shrink_to_node(NodeSet(scc))

        self.final = True
464364
def unique(seq):
    
    seen = set()
    return (x for x in seq if x not in seen and not seen.add(x))
1213316
def add_nodes(self, nodes, nesting=1):
        
        hopNodes = set()  # nodes in this hop
        hopEdges = []     # edges in this hop
        # get nodes and edges for this hop
        for i, n in zip(range(len(nodes)), nodes):
            r, g, b = rainbowcolour(i, len(nodes))
            colour = '#%02X%02X%02X' % (r, g, b)
            for nu in n.uses:
                if nu not in self.added:
                    hopNodes.add(nu)
                hopEdges.append((n, nu, 'dashed', colour))
            if hasattr(n, 'ancestor'):
                if n.ancestor not in self.added:
                    hopNodes.add(n.ancestor)
                hopEdges.append((n, n.ancestor, 'solid', colour))
        # add nodes, edges and attributes to the graph if maximum number of
        # nodes is not exceeded
        if self.add_to_graph(hopNodes, hopEdges, nesting):
            self.dot.attr('graph', size='11.875,1000.0')
144195
def _read_sequences(self, graph):
        
        for e in self._get_elements(graph, SBOL.Sequence):
            identity = e[0]
            c = self._get_rdf_identified(graph, identity)
            c['elements'] = self._get_triplet_value(graph, identity, SBOL.elements)
            c['encoding'] = self._get_triplet_value(graph, identity, SBOL.encoding)
            seq = Sequence(**c)
            self._sequences[identity.toPython()] = seq
            self._collection_store[identity.toPython()] = seq
253270
function matchGeneralSibling(nodes, predicate, root) {
  return uniqueReduce((matches, node) => {
    const parent = findParentNode(root, node);
    if (!parent) {
      return matches;
    }
    const parentChildren = childrenOfNode(parent);
    const nodeIndex = parentChildren.indexOf(node);
    const youngerSiblings = parentChildren.slice(nodeIndex + 1);
    return matches.concat(youngerSiblings.filter(predicate));
  }, nodes);
}
128651
def unique_labels(line_labels):
    """"""
    from collections import defaultdict
    d = defaultdict(int)
    for i in line_labels:
        d[i] += 1
    d = dict((i, k) for i, k in d.items() if k != 1)
    line_labels_u = []
    for lab in reversed(line_labels):
        c = d.get(lab, 0)
        if c >= 1:
            v = lab + "_num_" + str(c)
            d[lab] -= 1
        else:
            v = lab
        line_labels_u.insert(0, v)

    return line_labels_u