Coalesces adjacent free entries to create larger free entries (so that the probability of finding a free entry during allocation increases)
357751
private void mergeFreeEntries(List<FileEntry> entries) {
      long startTime = 0;
      if (trace) startTime = timeService.wallClockTime();
      FileEntry lastEntry = null;
      FileEntry newEntry = null;
      int mergeCounter = 0;
      for (FileEntry fe : entries) {
         if (fe.isLocked())
            continue;

         // Merge any holes created (consecutive free entries) in the file
         if ((lastEntry != null) && (lastEntry.offset == (fe.offset + fe.size))) {
            if (newEntry == null) {
               newEntry = new FileEntry(fe.offset, fe.size + lastEntry.size);
               freeList.remove(lastEntry);
               mergeCounter++;
            } else {
               newEntry = new FileEntry(fe.offset, fe.size + newEntry.size);
            }
            freeList.remove(fe);
            mergeCounter++;
         } else {
            if (newEntry != null) {
               mergeAndLogEntry(newEntry, mergeCounter);
               newEntry = null;
               mergeCounter = 0;
            }
         }
         lastEntry = fe;
      }

      if (newEntry != null)
         mergeAndLogEntry(newEntry, mergeCounter);

      if (trace) log.tracef("Total time taken for mergeFreeEntries: " + (timeService.wallClockTime() - startTime) + " (ms)");
   }
202994
private void appendInitialEntries() {
    final long term = context.getTerm();

    // Append a no-op entry to reset session timeouts and commit entries from prior terms.
    try (InitializeEntry entry = context.getLog().create(InitializeEntry.class)) {
      entry.setTerm(term)
        .setTimestamp(appender.time());
      Assert.state(context.getLog().append(entry) == appender.index(), "Initialize entry not appended at the start of the leader's term");
      LOGGER.trace("{} - Appended {}", context.getCluster().member().address(), entry);
    }

    // Append a configuration entry to propagate the leader's cluster configuration.
    configure(context.getCluster().members());
  }
230258
def increase(self, infile):
        '''
        '''
        gf = infile[31:]
        index = gf.index(random.choice(gf))
        index_len = len(gf[index])
        large_size_index = random.choice([gf.index(g) for g in gf if len(g) > index_len])
        gf[index], gf[large_size_index] = gf[large_size_index], gf[index]
        return infile[:31] + gf
430582
@Override
  protected final void increaseNewListSize() throws IOException {
    // register old situation
    int tmpOldSize = newKeyList.length;
    int tmpNewPosition = newPosition;
    // increase
    super.increaseNewListSize();
    // reconstruct
    T1[] tmpNewBasicValueList = newBasicValueSumList;
    long[] tmpNewBasicValueNList = newBasicValueNList;
    newBasicValueSumList = operations.createVector1(newSize);
    newBasicValueNList = new long[newSize];
    newPosition = tmpNewPosition;
    System.arraycopy(tmpNewBasicValueList, 0, newBasicValueSumList, 0,
        tmpOldSize);
    System.arraycopy(tmpNewBasicValueNList, 0, newBasicValueNList, 0,
        tmpOldSize);
  }
624330
def expand(self, local_search=False):
        ''''''
        new_nodes = []
        for action in self.problem.actions(self.state):
            new_state = self.problem.result(self.state, action)
            cost = self.problem.cost(self.state,
                                     action,
                                     new_state)
            nodefactory = self.__class__
            new_nodes.append(nodefactory(state=new_state,
                                         parent=None if local_search else self,
                                         problem=self.problem,
                                         action=action,
                                         cost=self.cost + cost,
                                         depth=self.depth + 1))
        return new_nodes
487134
def alloc(self):
        
        if not self._free:
            self._expand()
        id = self._free.pop()
        self._used.add(id)
        return id
493078
private static long addUnsignedReturnOverflow(Slice left, Slice right, Slice result, boolean resultNegative)
    {
        // TODO: consider two 7 bytes operations
        int l0 = getInt(left, 0);
        int l1 = getInt(left, 1);
        int l2 = getInt(left, 2);
        int l3 = getInt(left, 3);

        int r0 = getInt(right, 0);
        int r1 = getInt(right, 1);
        int r2 = getInt(right, 2);
        int r3 = getInt(right, 3);

        long intermediateResult;
        intermediateResult = (l0 & LONG_MASK) + (r0 & LONG_MASK);

        int z0 = (int) intermediateResult;

        intermediateResult = (l1 & LONG_MASK) + (r1 & LONG_MASK) + (intermediateResult >>> 32);

        int z1 = (int) intermediateResult;

        intermediateResult = (l2 & LONG_MASK) + (r2 & LONG_MASK) + (intermediateResult >>> 32);

        int z2 = (int) intermediateResult;

        intermediateResult = (l3 & LONG_MASK) + (r3 & LONG_MASK) + (intermediateResult >>> 32);

        int z3 = (int) intermediateResult & (~SIGN_INT_MASK);

        pack(result, z0, z1, z2, z3, resultNegative);

        return intermediateResult >> 31;
    }
790820
PairTable rebuild(final int newLgSizeInts) {
    checkLgSizeInts(newLgSizeInts);
    final int newSize = 1 << newLgSizeInts;
    final int oldSize = 1 << lgSizeInts;
    rtAssert(newSize > numPairs);
    final int[] oldSlotsArr = slotsArr;
    slotsArr = new int[newSize];
    Arrays.fill(slotsArr, -1);
    lgSizeInts = newLgSizeInts;
    for (int i = 0; i < oldSize; i++) {
      final int item = oldSlotsArr[i];
      if (item != -1) { mustInsert(this, item); }
    }
    return this;
  }
1307044
private void consolidateIfNeeded() {
        // Consolidate if the number of components will exceed the allowed maximum by the current
        // operation.
        int size = componentCount;
        if (size > maxNumComponents) {
            final int capacity = components[size - 1].endOffset;

            ByteBuf consolidated = allocBuffer(capacity);
            lastAccessed = null;

            // We're not using foreach to avoid creating an iterator.
            for (int i = 0; i < size; i ++) {
                components[i].transferTo(consolidated);
            }

            components[0] = new Component(consolidated, 0, 0, capacity, consolidated);
            removeCompRange(1, size);
        }
    }
465098
public Allocation allocate(Mutation mutation, int size)
    {
        CommitLogSegment segment = allocatingFrom();

        Allocation alloc;
        while ( null == (alloc = segment.allocate(mutation, size)) )
        {
            // failed to allocate, so move to a new segment with enough room
            advanceAllocatingFrom(segment);
            segment = allocatingFrom;
        }

        return alloc;
    }
1047308
def createEvenlySpreadSDRs(numSDRs, n, w):
  
  assert w <= n

  available = np.arange(n)
  np.random.shuffle(available)

  SDRs = []

  for _ in xrange(numSDRs):
    selected = available[:w]
    available = available[w:]

    if available.size == 0:
      remainderSelected = np.random.choice(
        np.setdiff1d(np.arange(n), selected),
        size=(w - selected.size),
        replace= False)
      selected = np.append(selected, remainderSelected)

      available = np.setdiff1d(np.arange(n), remainderSelected)
      np.random.shuffle(available)

    selected.sort()
    SDRs.append(selected)

  return SDRs
844312
public void calculateOccupied() {
    int total = 0;
    for (int hypercube : hypercubes) {
      if (hypercube > 0) {
        total++;
      }
    }

    occupied = new int[total];
    int base = 0;
    for (int i = 0; i < hypercubes.length; i++) {
      if (hypercubes[i] > 0) {
        occupied[base] = i;
        base++;
      }
    }
  }
579649
private void doGenerateIncrements() {
		if(increments != null) {
			return;	// Nothing to do
		}

		// Create random number sequence generator
		MersenneTwister			mersenneTwister		= new MersenneTwister(seed);

		// Allocate memory
		double[][][] incrementsArray = new double[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors][numberOfPaths];

		// Pre-fetch icdfs
		DoubleUnaryOperator[][] inverseCumulativeDistributionFunctions = new DoubleUnaryOperator[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors];
		for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
			for(int factor=0; factor<numberOfFactors; factor++) {
				inverseCumulativeDistributionFunctions[timeIndex][factor] = this.inverseCumulativeDistributionFunctions.apply(timeIndex).apply(factor);
			}
		}

		/*
		 * Generate normal distributed independent increments.
		 *
		 * The inner loop goes over time and factors.
		 * MersenneTwister is known to generate "independent" increments in 623 dimensions.
		 * Since we want to generate independent streams (paths), the loop over path is the outer loop.
		 */
		for(int path=0; path<numberOfPaths; path++) {
			for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
				// Generate uncorrelated Brownian increment
				for(int factor=0; factor<numberOfFactors; factor++) {
					double uniformIncrement = mersenneTwister.nextDouble();
					incrementsArray[timeIndex][factor][path] = inverseCumulativeDistributionFunctions[timeIndex][factor].applyAsDouble(uniformIncrement);
				}
			}
		}

		// Allocate memory for RandomVariable wrapper objects.
		increments = new RandomVariableInterface[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors];

		// Wrap the values in RandomVariable objects
		for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
			double time = timeDiscretization.getTime(timeIndex+1);
			for(int factor=0; factor<numberOfFactors; factor++) {
				increments[timeIndex][factor] =
						randomVariableFactory.createRandomVariable(time, incrementsArray[timeIndex][factor]);
			}
		}
	}
629083
private void expandAndRehash() {
    final int[] newHashSet = new int[hashSet.length * 2];
    final int bucketMask = (newHashSet.length - 1);

    for (int j = 0; j < hashSet.length; j++) {
      final int state = hashSet[j];
      if (state > 0) {
        int slot = hash(state, stateLength(state)) & bucketMask;
        for (int i = 0; newHashSet[slot] > 0;) {
          slot = (slot + (++i)) & bucketMask;
        }
        newHashSet[slot] = state;
      }
    }
    this.hashSet = newHashSet;
  }
159055
private final void expand_array()
  {
//    if (tc.isEntryEnabled())
//      SibTr.entry(tc, "expand_array");

    int length = m_array.length;
    Object[] m_new = new Object[length*2];
    System.arraycopy(m_array, m_head, m_new, m_head, length-m_head);
    System.arraycopy(m_array, 0, m_new, length, m_tail);
    m_tail += length;
    m_array = m_new;

//    if (tc.isEntryEnabled())
//      SibTr.exit(tc, "expand_array");
  }
72357
private int allocate(int size)
    {
        while (true)
        {
            int prev = allocatePosition.get();
            int next = prev + size;
            if (next >= buffer.capacity())
                return -1;
            if (allocatePosition.compareAndSet(prev, next))
                return prev;
        }
    }
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