Generate a random tree-structured dependency graph based on a
        specified edge probability.

        Also create helper data struct mapping child -> parent.
770849
def _generate_edges(self, edge_prob):
        
        self.E, self.parent = [], {}
        for i in range(self.m):
            if random() < edge_prob and i > 0:
                p_i = choice(i)
                self.E.append((p_i, i))
                self.parent[i] = p_i
779480
def create_build_graph(self, target_roots, build_root=None):
    
    logger.debug('target_roots are: %r', target_roots)
    graph = LegacyBuildGraph.create(self.scheduler_session, self.build_file_aliases)
    logger.debug('build_graph is: %s', graph)
    # Ensure the entire generator is unrolled.
    for _ in graph.inject_roots_closure(target_roots):
      pass

    address_mapper = LegacyAddressMapper(self.scheduler_session, build_root or get_buildroot())
    logger.debug('address_mapper is: %s', address_mapper)
    return graph, address_mapper
1207894
def generate_dummy_graph(network):
    """"""
    
    graph = pypsa.descriptors.OrderedGraph()
    
    graph.add_nodes_from([bus for bus in network.buses.index if bus not in buses_to_split])
    
    #add positions to graph for voronoi cell computation
    for node in graph.nodes():
        graph.node[node]["pos"] = np.array(network.buses.loc[node,["x","y"]],dtype=float)
    
    return graph
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);
		}
	});
}
1365330
def x_build_targets_target( self, node ):
        '''
        
        '''
        target_node = node
        name = self.get_child_data(target_node,tag='name',strip=True)
        path = self.get_child_data(target_node,tag='path',strip=True)
        jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
        #~ Map for jam targets to virtual targets.
        self.target[jam_target] = {
            'name' : name,
            'path' : path
            }
        #~ Create the ancestry.
        dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
        while dep_node:
            child = self.get_data(dep_node,strip=True)
            child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
            self.parent[child_jam_target] = jam_target
            dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
        return None
1138053
def mygenerator(n=5, n_edges=5):
    '''
    
    '''
    G = nx.Graph()

    for i in range(n):
        G.add_node(i)
    
    for i in range(n_edges):
        nodes = list(G.nodes)
        n_in = choice(nodes)
        nodes.remove(n_in)  # Avoid loops
        n_out = choice(nodes)
        G.add_edge(n_in, n_out)
    return G
570980
function (graph, opts, params) {
    if (graph.children.length == 0) return '';

    function getRels(node) {
      var rels = [];
      node.children.forEach(function(childNode) {
        rels.push('(' + node.name + ')-[__rel_' + childNode.name + ':' + childNode.comp.rel + ']->(' + childNode.name + ')');
        rels.push.apply(rels, getRels(childNode));
      });
      return rels;
    }
    
    return 'CREATE UNIQUE ' + getRels(graph).join(',');
  }
1163773
def generate_random_graph(node_num, edge_num, self_loops=False, multi_edges=False):
    '''
    
    '''
    g = Graph.Graph()

    if not multi_edges:
        if self_loops:
            max_edges = node_num * node_num
        else:
            max_edges = node_num * (node_num-1)

        if edge_num > max_edges:
            raise GraphError("inconsistent arguments to 'generate_random_graph'")

    nodes = range(node_num)

    for node in nodes:
        g.add_node(node)

    while 1:
        head = random.choice(nodes)
        tail = random.choice(nodes)

        # loop defense
        if head == tail and not self_loops:
            continue

        # multiple edge defense
        if g.edge_by_node(head,tail) is not None and not multi_edges:
            continue

        # add the edge
        g.add_edge(head, tail)
        if g.number_of_edges() >= edge_num:
            break

    return g
658503
def generate(self, tree):
        '''
        
        '''
        for middleware in DEFAULT_MIDDLEWARES + self.middlewares:
            tree = middleware.process(tree) # changed in place!!
        original = self._generate_node(tree)
        # first n lines n dependencies
        # after that additional code

        if self.a and tree.type == 'module':
            p = original.split('\n')
            r = '\n'.join(p[:len(tree.dependencies)] + (['\n'] if tree.dependencies else []) + self.a + ['\n'] + p[len(tree.dependencies):]) + '\n'
        else:
            r = original
        r = re.sub(CLOSING_CURLY_ENDLINES, r'}\n\2}', r)
        r = re.sub(JS_BRACKET, r'}\1', r)
        return re.sub(TOO_MANY_ENDLINES, r'\n\n', r)
712865
def _precompute_probabilities(self):
        

        d_graph = self.d_graph
        first_travel_done = set()

        nodes_generator = self.graph.nodes() if self.quiet \
            else tqdm(self.graph.nodes(), desc='Computing transition probabilities')

        for source in nodes_generator:

            # Init probabilities dict for first travel
            if self.PROBABILITIES_KEY not in d_graph[source]:
                d_graph[source][self.PROBABILITIES_KEY] = dict()

            for current_node in self.graph.neighbors(source):

                # Init probabilities dict
                if self.PROBABILITIES_KEY not in d_graph[current_node]:
                    d_graph[current_node][self.PROBABILITIES_KEY] = dict()

                unnormalized_weights = list()
                first_travel_weights = list()
                d_neighbors = list()

                # Calculate unnormalized weights
                for destination in self.graph.neighbors(current_node):

                    p = self.sampling_strategy[current_node].get(self.P_KEY,
                                                                 self.p) if current_node in self.sampling_strategy else self.p
                    q = self.sampling_strategy[current_node].get(self.Q_KEY,
                                                                 self.q) if current_node in self.sampling_strategy else self.q

                    if destination == source:  # Backwards probability
                        ss_weight = self.graph[current_node][destination].get(self.weight_key, 1) * 1 / p
                    elif destination in self.graph[source]:  # If the neighbor is connected to the source
                        ss_weight = self.graph[current_node][destination].get(self.weight_key, 1)
                    else:
                        ss_weight = self.graph[current_node][destination].get(self.weight_key, 1) * 1 / q

                    # Assign the unnormalized sampling strategy weight, normalize during random walk
                    unnormalized_weights.append(ss_weight)
                    if current_node not in first_travel_done:
                        first_travel_weights.append(self.graph[current_node][destination].get(self.weight_key, 1))
                    d_neighbors.append(destination)

                # Normalize
                unnormalized_weights = np.array(unnormalized_weights)
                d_graph[current_node][self.PROBABILITIES_KEY][
                    source] = unnormalized_weights / unnormalized_weights.sum()

                if current_node not in first_travel_done:
                    unnormalized_weights = np.array(first_travel_weights)
                    d_graph[current_node][self.FIRST_TRAVEL_KEY] = unnormalized_weights / unnormalized_weights.sum()
                    first_travel_done.add(current_node)

                # Save neighbors
                d_graph[current_node][self.NEIGHBORS_KEY] = d_neighbors
742114
function createDependencyGraph(tasks) {
    var graph = {
      tasks: {},
      roots: [],
      leaves: [],
      resources: [],
      depth: 0,
      end : 0
    };

    for(var i = 0, len = tasks.length; i < len; i++) {
      var t = tasks[i];
      graph.tasks[t.id] = {
        id: t.id,
        duration: t.duration,
        priority: t.priority,
        schedule: t.schedule,
        minSchedule: t.minSchedule,
        dependsOn: t.dependsOn,
        resources: t.resources
      };
    }

    setResources(graph);
    setRequiredBy(graph.tasks);
    setRootsAndLeaves(graph);

    setDepth(graph, graph.leaves, 0);
    graph.depth += 1; // increment depth so it is 1 based

    forwardPass(graph, {}, graph.roots, 0);
    setEnd(graph, graph.leaves);
    backwardPass(graph, {}, graph.leaves, graph.end);

    return graph;
  }
529901
def generate_or_fail(self):
        

        t1 = self.generate_random_table()
        t2 = self.generate_random_table()
        f1 = self.generate_func(t1)
        f2 = self.generate_func(t2)
        edges = [(f1(word), f2(word)) for word in self.words]

        # Try to generate that graph, mack!
        # Note that failure to generate the graph here should be caught
        # by the caller.
        graph = forest.ForestGraph(edges=edges)

        # Associate each edge with its corresponding word.
        associations = {}
        for num in range(len(self.words)):
            edge = edges[num]
            word = self.words[num]
            associations[graph.canonical_order(edge)] = (num, word)

        # Assign all of these to the object.
        for name in ('t1', 't2', 'f1', 'f2', 'graph', 'associations'):
            self.__dict__[name] = locals()[name]
1148687
def get_random_path(graph) -> List[BaseEntity]:
    
    wg = graph.to_undirected()

    nodes = wg.nodes()

    def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]:
        """Get a pair of random nodes."""
        return random.sample(nodes, k=2)

    source, target = pick_random_pair()

    tries = 0
    sentinel_tries = 5

    while not nx.has_path(wg, source, target) and tries < sentinel_tries:
        tries += 1
        source, target = pick_random_pair()

    if tries == sentinel_tries:
        return [source]

    return nx.shortest_path(wg, source=source, target=target)
1293134
def _init_edges(p2cs, c2ps):
        """"""
        edge_from_to = []
        for parent, children in p2cs.items():
            for child in children:
                # if child in goids_present and parent in goids_present:
                edge_from_to.append((child, parent))
        for parent, children in c2ps.items():
            for child in children:
                # if child in goids_present and parent in goids_present:
                edge_from_to.append((child, parent))
        return edge_from_to
878854
private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {
        // In that case of Axway artifact we will add a module to the graph
        if (filters.getCorporateFilter().filter(dependency)) {
            final DbModule dbTarget = repoHandler.getModuleOf(dependency.getTarget());

            // if there is no module, add the artifact to the graph
            if(dbTarget == null){
                LOG.error("Got missing reference: " + dependency.getTarget());
                final DbArtifact dbArtifact = DataUtils.createDbArtifact(dependency.getTarget());
                final String targetElementId = graph.getId(dbArtifact);
                graph.addElement(targetElementId, dbArtifact.getVersion(), false);
                graph.addDependency(parentId, targetElementId, dependency.getScope());
                return;
            }

            // Add the element to the graph
            addModuleToGraph(dbTarget, graph, depth + 1);

            //Add the dependency to the graph
            final String moduleElementId = graph.getId(dbTarget);
            graph.addDependency(parentId, moduleElementId, dependency.getScope());
        }
        // In case a third-party we will add an artifact
        else {
            final DbArtifact dbTarget = repoHandler.getArtifact(dependency.getTarget());
            if(dbTarget == null){
                LOG.error("Got missing artifact: " + dependency.getTarget());
                return;
            }

            if(!graph.isTreated(graph.getId(dbTarget))){
                final ModelMapper modelMapper = new ModelMapper(repoHandler);
                final Artifact target = modelMapper.getArtifact(dbTarget);
                final String targetElementId = graph.getId(target);
                graph.addElement(targetElementId, target.getVersion(), false);
                graph.addDependency(parentId, targetElementId, dependency.getScope());
            }
        }
    }
435820
function tightTree(t, g) {
  function dfs(v) {
    _.forEach(g.nodeEdges(v), function(e) {
      var edgeV = e.v,
        w = (v === edgeV) ? e.w : edgeV;
      if (!t.hasNode(w) && !slack(g, e)) {
        t.setNode(w, {});
        t.setEdge(v, w, {});
        dfs(w);
      }
    });
  }

  _.forEach(t.nodes(), dfs);
  return t.nodeCount();
}
465910
def dependent(self):
        
        if self._dependent is None:
            dependents = self._element.xpath('dependent')
            if len(dependents) > 0:
                self._dependent = DependencyNode.load(self._graph, dependents[0])
        return self._dependent