Create a random hyper graph.
    
    @type  num_nodes: number
    @param num_nodes: Number of nodes.
    
    @type  num_edges: number
    @param num_edges: Number of edges.
    
    @type  r: number
    @param r: Uniform edges of size r.
323480
def generate_hypergraph(num_nodes, num_edges, r = 0):
    
    # Graph creation
    random_graph = hypergraph()
    
    # Nodes
    nodes = list(map(str, list(range(num_nodes))))
    random_graph.add_nodes(nodes)
    
    # Base edges
    edges = list(map(str, list(range(num_nodes, num_nodes+num_edges))))
    random_graph.add_hyperedges(edges)
    
    # Connect the edges
    if 0 == r:
        # Add each edge with 50/50 probability
        for e in edges:
            for n in nodes:
                if choice([True, False]):
                    random_graph.link(n, e)
    
    else:
        # Add only uniform edges
        for e in edges:
            # First shuffle the nodes
            shuffle(nodes)
            
            # Then take the first r nodes
            for i in range(r):
                random_graph.link(nodes[i], e)
    
    return random_graph
951998
def _choose_random_edge(self, edges: Set[EDGE]) -> Optional[EDGE]:
        
        if edges:
            index = self._rand.randint(len(edges))
            for e in edges:
                if not index:
                    return e
                index -= 1
        return None
128985
def _create_graph(self, return_target_sources=None):
        
        if return_target_sources is None:
            # We set it to a defaultdict in order to be consistent with the
            # actual parameter.
            return_target_sources = defaultdict(list)

        cfg = networkx.DiGraph()
        # The corner case: add a node to the graph if there is only one block
        if len(self._nodes) == 1:
            cfg.add_node(self._nodes[next(iter(self._nodes.keys()))])

        # Adding edges
        for tpl, targets in self._exit_targets.items():
            basic_block = self._nodes[tpl] # Cannot fail :)
            for ex, jumpkind in targets:
                if ex in self._nodes:
                    target_bbl = self._nodes[ex]
                    cfg.add_edge(basic_block, target_bbl, jumpkind=jumpkind)

                    # Add edges for possibly missing returns
                    if basic_block.addr in return_target_sources:
                        for src_irsb_key in \
                                return_target_sources[basic_block.addr]:
                            cfg.add_edge(self._nodes[src_irsb_key],
                                               basic_block, jumpkind="Ijk_Ret")
                else:
                    # Debugging output
                    def addr_formalize(addr):
                        if addr is None:
                            return "None"
                        else:
                            return "%#08x" % addr

                    s = "(["
                    for addr in ex[:-1]:
                        s += addr_formalize(addr) + ", "
                    s += "] %s)" % addr_formalize(ex[-1])
                    l.warning("Key %s does not exist.", s)

        return cfg
1330786
def create_edges(cells_nodes):
    
    # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of
    # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge
    # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3, n)`, where `n` is
    # the number of cells. Make sure that the k-th edge is opposite of the k-th
    # point in the triangle.
    local_idx = numpy.array([[1, 2], [2, 0], [0, 1]]).T
    # Map idx back to the nodes. This is useful if quantities which are in
    # idx shape need to be added up into nodes (e.g., equation system rhs).
    nds = cells_nodes.T
    idx_hierarchy = nds[local_idx]

    s = idx_hierarchy.shape
    a = numpy.sort(idx_hierarchy.reshape(s[0], s[1] * s[2]).T)

    b = numpy.ascontiguousarray(a).view(
        numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1]))
    )
    _, idx, inv, cts = numpy.unique(
        b, return_index=True, return_inverse=True, return_counts=True
    )

    # No edge has more than 2 cells. This assertion fails, for example, if
    # cells are listed twice.
    assert all(cts < 3)

    edge_nodes = a[idx]
    cells_edges = inv.reshape(3, -1).T

    return edge_nodes, cells_edges
509281
def make_original_face(num_edges)
      num_edges_check(num_edges)
      # Make the vertices
      vert_ref = Array.new(num_edges) {Vertex.new}
      edge_ref = []

      # Connect each vertex to the one before it (including the first one :)
      (num_edges).times do |vert_id|
        edge_ref << make_connection(vert_ref[vert_id - 1], vert_ref[vert_id])
      end

      # Make the face and store it
      face = add_face(edge_ref)
      # Store the new vertices
      @vertices += vert_ref
      # Store the new edges
      @edges += edge_ref

      face
    end
1166417
def new_edge(self, node_a, node_b, cost=1):
        """"""

        # Verify that both nodes exist in the graph
        try:
            self.nodes[node_a]
        except KeyError:
            raise NonexistentNodeError(node_a)
        try:
            self.nodes[node_b]
        except KeyError:
            raise NonexistentNodeError(node_b)

        # Create the new edge
        edge_id = self.generate_edge_id()

        edge = {'id': edge_id,
                'vertices': (node_a, node_b),
                'cost': cost,
                'data': {}
        }

        self.edges[edge_id] = edge
        self.nodes[node_a]['edges'].append(edge_id)

        self._num_edges += 1

        return edge_id
775648
def add_edge(self, fr, to):
        
        if fr not in set(self.graph.vs):  # ToDo: find out why item can be in set but not dict
            raise ValueError('can not connect unknown vertices in n-partite graphs, {!r} missing'.format(fr))
        elif to not in set(self.graph.vs):
            raise ValueError('can not connect unknown vertices in n-partite graphs, {!r} missing'.format(to))
        self.graph.add_edge(fr, to)
145444
def build_cycle_graph(num_nodes):
    """"""
    graph = UndirectedGraph()

    if num_nodes > 0:
        first_node = graph.new_node()
        if num_nodes > 1:
            previous_node = first_node
            for _ in range(num_nodes - 1):
                new_node = graph.new_node()
                graph.new_edge(previous_node, new_node)
                previous_node = new_node
            graph.new_edge(previous_node, first_node)

    return graph
236266
public void randomize() {
		numKnots = 4 + (int)(6*Math.random());
		xKnots = new int[numKnots];
		yKnots = new int[numKnots];
		knotTypes = new byte[numKnots];
		for (int i = 0; i < numKnots; i++) {
			xKnots[i] = (int)(255 * Math.random());
			yKnots[i] = 0xff000000 | ((int)(255 * Math.random()) << 16) | ((int)(255 * Math.random()) << 8) | (int)(255 * Math.random());
			knotTypes[i] = RGB|SPLINE;
		}
		xKnots[0] = -1;
		xKnots[1] = 0;
		xKnots[numKnots-2] = 255;
		xKnots[numKnots-1] = 256;
		sortKnots();
		rebuildGradient();
	}
1023215
public List<String> nextParagraphs(int num) {
        List<String> paragraphs = new ArrayList<String>(num);
        for(int i = 0; i < num; i++) {
            paragraphs.add(nextParagraph());
        }
        return paragraphs;
    }
214894
def _create_ring(self, nodes):
        
        for node_name, node_conf in nodes:
            for w in range(0, node_conf['vnodes'] * node_conf['weight']):
                self._distribution[node_name] += 1
                self._ring[self.hashi('%s-%s' % (node_name, w))] = node_name
        self._keys = sorted(self._ring.keys())
549315
def _helper(result,
            graph,
            number_edges_remaining: int,
            node_blacklist: Set[BaseEntity],
            invert_degrees: Optional[bool] = None,
            ):
    
    original_node_count = graph.number_of_nodes()

    log.debug('adding remaining %d edges', number_edges_remaining)
    for _ in range(number_edges_remaining):

        source, possible_step_nodes, c = None, set(), 0
        while not source or not possible_step_nodes:
            source = get_random_node(result, node_blacklist, invert_degrees=invert_degrees)

            c += 1
            if c >= original_node_count:
                log.warning('infinite loop happening')
                log.warning('source: %s', source)
                log.warning('no grow: %s', node_blacklist)
                return  # Happens when after exhausting the connected components. Try increasing the number seed edges

            if source is None:
                continue  # maybe do something else?

            # Only keep targets in the original graph that aren't in the result graph
            possible_step_nodes = set(graph[source]) - set(result[source])

            if not possible_step_nodes:
                node_blacklist.add(
                    source)  # there aren't any possible nodes to step to, so try growing from somewhere else

        step_node = random.choice(list(possible_step_nodes))

        # it's not really a big deal which, but it might be possible to weight this by the utility of edges later
        key, attr_dict = random.choice(list(graph[source][step_node].items()))

        result.add_edge(source, step_node, key=key, **attr_dict)
58669
def connect_edges(graph):
    
    paths = []
    for start, end in graph.array(graph.kdims):
        start_ds = graph.nodes[:, :, start]
        end_ds = graph.nodes[:, :, end]
        if not len(start_ds) or not len(end_ds):
            raise ValueError('Could not find node positions for all edges')
        start = start_ds.array(start_ds.kdims[:2])
        end = end_ds.array(end_ds.kdims[:2])
        paths.append(np.array([start[0], end[0]]))
    return paths
156363
private LinkedHashMap<HypergraphNode<Variable>, Integer> createInitialOrdering(final Formula formula, final Map<Variable, HypergraphNode<Variable>> nodes) {
    final LinkedHashMap<HypergraphNode<Variable>, Integer> initialOrdering = new LinkedHashMap<>();
    final List<Variable> dfsOrder = this.dfsOrdering.getOrder(formula);
    for (int i = 0; i < dfsOrder.size(); i++)
      initialOrdering.put(nodes.get(dfsOrder.get(i)), i);
    return initialOrdering;
  }
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
49347
def subgraph(graph, nodes: Iterable[BaseEntity]):
    
    sg = graph.subgraph(nodes)

    # see implementation for .copy()
    result = graph.fresh_copy()
    result.graph.update(sg.graph)

    for node, data in sg.nodes(data=True):
        result.add_node(node, **data)

    result.add_edges_from(
        (u, v, key, datadict.copy())
        for u, v, key, datadict in sg.edges(keys=True, data=True)
    )

    return result
942048
def _rand_init(x_bounds, x_types, selection_num_starting_points):
    '''
    
    '''
    return [lib_data.rand(x_bounds, x_types) for i \
                    in range(0, selection_num_starting_points)]