Allocate resources to vertices on cores arbitrarily using a simple greedy
    algorithm.
428826
def allocate(vertices_resources, nets, machine, constraints, placements):
    
    allocation = {}

    # Globally reserved resource ranges {resource, [slice, ...], ...}
    globally_reserved = defaultdict(list)
    # Locally reserved resource ranges {(x, y): {resource, [slice, ...], ...}}
    locally_reserved = defaultdict(lambda: defaultdict(list))

    # Alignment of each resource
    alignments = defaultdict(lambda: 1)

    # Collect constraints
    for constraint in constraints:
        if isinstance(constraint, ReserveResourceConstraint):
            if constraint.location is None:
                globally_reserved[constraint.resource].append(
                    constraint.reservation)
            else:
                locally_reserved[constraint.location][
                    constraint.resource].append(constraint.reservation)
        elif isinstance(constraint, AlignResourceConstraint):
            alignments[constraint.resource] = constraint.alignment

    # A dictionary {(x, y): [vertex, ...], ...}
    chip_contents = defaultdict(list)
    for vertex, xy in iteritems(placements):
        chip_contents[xy].append(vertex)

    for xy, chip_vertices in iteritems(chip_contents):
        # Index of the next free resource in the current chip
        resource_pointers = {resource: 0
                             for resource in machine.chip_resources}

        for vertex in chip_vertices:
            vertex_allocation = {}

            # Make allocations, advancing resource pointers
            for resource, requirement in iteritems(vertices_resources[vertex]):
                proposed_allocation = None
                proposal_overlaps = True
                while proposal_overlaps:
                    # Check that the proposed allocation doesn't overlap a
                    # reserved area.
                    start = align(resource_pointers[resource],
                                  alignments[resource])
                    proposed_allocation = slice(start, start + requirement)
                    proposal_overlaps = False
                    if proposed_allocation.stop > machine[xy][resource]:
                        raise InsufficientResourceError(
                            "{} over-allocated on chip {}".format(resource,
                                                                  xy))
                    for reservation in globally_reserved[resource]:
                        if slices_overlap(proposed_allocation, reservation):
                            resource_pointers[resource] = reservation.stop
                            proposal_overlaps = True
                    local_reservations \
                        = locally_reserved.get(xy, {}).get(resource, [])
                    for reservation in local_reservations:
                        if slices_overlap(proposed_allocation, reservation):
                            resource_pointers[resource] = reservation.stop
                            proposal_overlaps = True

                # Getting here means the proposed allocation is not blocked
                # by any reservations
                vertex_allocation[resource] = proposed_allocation
                resource_pointers[resource] = proposed_allocation.stop

            allocation[vertex] = vertex_allocation

    return allocation
90717
def optimize(self):
        """"""
        subpattern = None
        if (self.content is not None and
            len(self.content) == 1 and len(self.content[0]) == 1):
            subpattern = self.content[0][0]
        if self.min == 1 and self.max == 1:
            if self.content is None:
                return NodePattern(name=self.name)
            if subpattern is not None and  self.name == subpattern.name:
                return subpattern.optimize()
        if (self.min <= 1 and isinstance(subpattern, WildcardPattern) and
            subpattern.min <= 1 and self.name == subpattern.name):
            return WildcardPattern(subpattern.content,
                                   self.min*subpattern.min,
                                   self.max*subpattern.max,
                                   subpattern.name)
        return self
539311
def set_for_computations(self, value):
        
        if self.mesh._compute_at_vertices:
            self._vertices = value
        else:
            self._centers = value
1048079
def make_batch(size, graph):
        
        i = iter(graph)
        chunk = list(islice(i, size))
        while chunk:
            yield chunk
            chunk = list(islice(i, size))
598340
def allocate(self, handles, initial=False, params={}):
        """"""
        assert all(re.search('^\d+$', h) for h in handles), "All handles must be numbers: {}".format(handles)
        self.requests.put(('allocate', (handles, initial, params)))
1253252
static private Vector3f[] copyVertices(Vector3f[] vertices) {
        if (vertices == null) {
            return null;
        }
        Vector3f[] copy = new Vector3f[vertices.length];
        for (int i = 0; i < vertices.length; ++i) {
            copy[i] = new Vector3f(vertices[i]);
        }
        return copy;
    }
697017
def _augment(graph, capacity, flow, source, target):
    
    n = len(graph)
    A = [0] * n               # A[v] = min residual cap. on path source->v
    augm_path = [None] * n    # None = node was not visited yet
    Q = deque()               # BFS
    Q.append(source)
    augm_path[source] = source
    A[source] = float('inf')
    while Q:
        u = Q.popleft()
        for v in graph[u]:
            cuv = capacity[u][v]
            residual = cuv - flow[u][v]
            if residual > 0 and augm_path[v] is None:
                augm_path[v] = u    # store predecessor
                A[v] = min(A[u], residual)
                if v == target:
                    break
                else:
                    Q.append(v)
    return (augm_path, A[target])
126292
private Map<Integer, List<InstanceId>> getRoundRobinAllocation(
      int numContainer, Map<String, Integer> parallelismMap) {
    Map<Integer, List<InstanceId>> allocation = new HashMap<>();
    int totalInstance = TopologyUtils.getTotalInstance(parallelismMap);
    if (numContainer < 1) {
      throw new RuntimeException(String.format("Invlaid number of container: %d", numContainer));
    } else if (numContainer > totalInstance) {
      throw new RuntimeException(
          String.format("More containers (%d) allocated than instances (%d).",
              numContainer, totalInstance));
    }

    for (int i = 1; i <= numContainer; ++i) {
      allocation.put(i, new ArrayList<>());
    }

    int index = 1;
    int globalTaskIndex = 1;

    // To ensure we spread out the big instances first
    // Only sorting by RAM here because only RAM can be explicitly capped by JVM processes
    List<String> sortedInstances = getSortedRAMComponents(parallelismMap.keySet()).stream()
        .map(ResourceRequirement::getComponentName).collect(Collectors.toList());
    for (String component : sortedInstances) {
      int numInstance = parallelismMap.get(component);
      for (int i = 0; i < numInstance; ++i) {
        allocation.get(index).add(new InstanceId(component, globalTaskIndex, i));
        index = (index == numContainer) ? 1 : index + 1;
        globalTaskIndex++;
      }
    }
    return allocation;
  }
914195
private static void vectorSwap(PagesIndex pagesIndex, int from, int l, int s)
    {
        for (int i = 0; i < s; i++, from++, l++) {
            pagesIndex.swap(from, l);
        }
    }
561315
@Override
    public Set<VM> getMisPlacedVMs(Instance i) {
        for (SatConstraint c : i.getSatConstraints()) {
            if (!(c instanceof ResourceRelated && ((ResourceRelated) c).getResource().equals(rc.getResourceIdentifier()))) {
                continue;
            }
            if (c instanceof Preserve) {
                VM v = c.getInvolvedVMs().iterator().next();
                wantedAmount.put(v, consumption(v, ((Preserve) c).getAmount()));
            } else if (c instanceof Overbook) {
                Node n = c.getInvolvedNodes().iterator().next();
                wantedRatios.put(n, ratio(n, ((Overbook) c).getRatio()));
            } else if (c instanceof ResourceCapacity && c.getInvolvedNodes().size() == 1) {
                Node n = c.getInvolvedNodes().iterator().next();
                wantedCapacity.put(n, capacity(n, ((ResourceCapacity) c).getAmount()));
            }
        }
        Mapping m = i.getModel().getMapping();
        Set<VM> candidates = new HashSet<>();
        for (Node n : m.getOnlineNodes()) {
            if (overloaded(m, n)) {
                candidates.addAll(m.getRunningVMs(n));
            }
        }
        return candidates;
    }
630871
private int[] loadNodes(int size, int relType, Direction direction) {
        final CursorFactory cursors = ktx.cursors();
        try (NodeCursor node = cursors.allocateNodeCursor()) {
            // todo reuse array
            int[] offsets = new int[size];
            Arrays.fill(offsets,-1);
            int offset = 0;
            int maxIdx = 0;

            ktx.dataRead().allNodesScan(node);

            while (node.next()) {
                int degree = DegreeUtil.degree(node, cursors, relType, direction);
                int idx = mapId(node.nodeReference());
//                offsets[idx] = degree;
                offsets[idx] = offset;
                offset += degree;
                if (idx > maxIdx) maxIdx = idx;
            }

            return maxIdx < offsets.length -1 ? Arrays.copyOf(offsets,maxIdx+1) : offsets;
        }
    }
95719
function allocate(height, length) {
	var node = new Array(length);
	node.height = height;
	if (height > 0) {
		node.sizes = new Array(length);
	}
	return node;
}
220943
private long allocate_from_tail(int block_size)
    throws IOException
    {
        long block_to_alloc;

        block_to_alloc = tail_ptr;
        tail_ptr = tail_ptr + block_size;

        allocated_blocks++;
        allocated_words += block_size;

        seek_and_count(block_to_alloc);
        writeInt(- block_size);
        seek_and_count(TAIL_DPTR);
        writeLong(tail_ptr);

        return(block_to_alloc + HDR_SIZE);
    }
596693
protected void recycleData() {
		for (int i = 0; i < nodes.size(); i++) {
			SquareNode n = nodes.get(i);
			for (int j = 0; j < n.edges.length; j++) {
				if( n.edges[j] != null ) {
					graph.detachEdge(n.edges[j]);
				}
			}
		}
		for (int i = 0; i < nodes.size(); i++) {
			SquareNode n = nodes.get(i);
			for (int j = 0; j < n.edges.length; j++) {
				if( n.edges[j] != null )
					throw new RuntimeException("BUG!");
			}
		}

		nodes.reset();

		for (int i = 0; i < clusters.size; i++) {
			clusters.get(i).clear();
		}
		clusters.reset();
	}
218716
private <E> Collection<Block<S, L>> initialize(UniversalGraph<S, E, ?, L> graph,
                                                   Collection<? extends S> initialNodes) {
        Iterable<? extends S> origStates;
        if (initialNodes == null || initialNodes.isEmpty()) {
            origStates = graph.getNodes();
        } else {
            origStates = GraphTraversal.depthFirstOrder(graph, initialNodes);
        }

        Map<L, TransitionLabel<S, L>> transitionMap = new HashMap<>();

        stateStorage = graph.createStaticNodeMapping();

        int numStates = 0;
        for (S origState : origStates) {
            State<S, L> state = new State<>(numStates++, origState);
            stateStorage.put(origState, state);
            stateList.add(state);
        }

        InitialPartitioning<S, L> initPartitioning = new HashMapInitialPartitioning<>(graph);

        for (State<S, L> state : stateList) {
            S origState = state.getOriginalState();

            Block<S, L> block = initPartitioning.getBlock(origState);
            block.addState(state);

            for (E edge : graph.getOutgoingEdges(origState)) {
                S origTarget = graph.getTarget(edge);
                State<S, L> target = stateStorage.get(origTarget);
                L label = graph.getEdgeProperty(edge);
                TransitionLabel<S, L> transition = transitionMap.computeIfAbsent(label, TransitionLabel::new);
                Edge<S, L> edgeObj = new Edge<>(state, target, transition);
                state.addOutgoingEdge(edgeObj);
                target.addIncomingEdge(edgeObj);
            }
        }
        stateList.quickClear();

        return initPartitioning.getInitialBlocks();
    }
745059
def full_subgraph(self, vertices):
        
        subgraph_vertices = {v for v in vertices}
        subgraph_edges = {edge
                          for v in subgraph_vertices
                          for edge in self._out_edges[v]
                          if self._heads[edge] in subgraph_vertices}
        subgraph_heads = {edge: self._heads[edge]
                          for edge in subgraph_edges}
        subgraph_tails = {edge: self._tails[edge]
                          for edge in subgraph_edges}
        return DirectedGraph._raw(
            vertices=subgraph_vertices,
            edges=subgraph_edges,
            heads=subgraph_heads,
            tails=subgraph_tails,
        )
312703
static function optimize( $useComments, &$php, $tpl, &$tree, &$resourceData )
    {
        /* If for some reason we don't have elements, simply return */
        if (! is_array( $tree[1] ) )
            return;

        $addNodeInit = false;

        /* Loop through the children of the root */
        foreach ( $tree[1] as $key => $kiddie )
        {
            /* Analyse per node type */
            switch ( $kiddie[0] )
            {
                case eZTemplate::NODE_INTERNAL_OUTPUT_SPACING_INCREASE:
                case eZTemplate::NODE_INTERNAL_SPACING_DECREASE:
                    /* Removing unnecessary whitespace changes */
                    unset( $tree[1][$key] );
                    break;
                case 3: /* Variable */
                    if ( isset( $tree[1][$key + 1] ) and
                         ( $tree[1][$key + 1][0] == eZTemplate::NODE_INTERNAL_RESOURCE_ACQUISITION ) and
                         isset( $resourceData['class-info'] ) )
                    {
                        $ret = eZTemplateOptimizer::optimizeResourceAcquisition(
                            $useComments, $php, $tpl,
                            $tree[1][$key], $tree[1][$key + 1], $resourceData );
                        /* We only unset the tree node when the optimization
                         * function returns false, as that means that the
                         * optimization could not be made. */
                        if ($ret)
                        {
                            unset( $tree[1][$key] );
                        }
                    }
                    else
                    {
                        $ret = eZTemplateOptimizer::optimizeVariable( $useComments, $php, $tpl, $tree[1][$key][2], $resourceData );
                        if ( $ret & 1 )
                            $addNodeInit = true;
                    }
                    break;
            }
        }
        if ( $addNodeInit )
        {
            $initializer = array( eZTemplate::NODE_OPTIMIZED_INIT, null, false );
            array_unshift( $tree[1], $initializer );
        }
    }