This is to implement memory allocation in the array. Like malloc().
19358
public int alloc(int size) {
        int index = n;
        int len = array.length;
        if (n + size >= len) {
            byte[] aux = new byte[len + blockSize];
            System.arraycopy(array, 0, aux, 0, len);
            array = aux;
        }
        n += size;
        return index;
    }
848158
private Set<Integer> arrayToSet(int[] arr) {
        Set<Integer> s = new HashSet<Integer>();
        for (int value : arr)
            s.add(value);
        return s;
    }
196183
@Override
    public PointersPair malloc(AllocationShape shape, AllocationPoint point, AllocationStatus location) {

        //log.info("shape onCreate: {}, target: {}", shape, location);

        switch (location) {
            case HOST: {
                long reqMem = AllocationUtils.getRequiredMemory(shape);

                // FIXME: this is WRONG, and directly leads to memleak
                if (reqMem < 1)
                    reqMem = 1;

                val pointer = nativeOps.mallocHost(reqMem, 0);
                if (pointer == null)
                    throw new RuntimeException("Can't allocate [HOST] memory: " + reqMem + "; threadId: "
                                    + Thread.currentThread().getId());

                //                log.info("Host allocation, Thread id: {}, ReqMem: {}, Pointer: {}", Thread.currentThread().getId(), reqMem, pointer != null ? pointer.address() : null);

                val hostPointer = new CudaPointer(pointer);

                val devicePointerInfo = new PointersPair();
                devicePointerInfo.setDevicePointer(new CudaPointer(hostPointer, reqMem));
                devicePointerInfo.setHostPointer(new CudaPointer(hostPointer, reqMem));

                point.setPointers(devicePointerInfo);

                point.setAllocationStatus(AllocationStatus.HOST);

                MemoryTracker.getInstance().incrementAllocatedHostAmount(reqMem);

                return devicePointerInfo;
            }
            case DEVICE: {
                // cudaMalloc call
                val deviceId = AtomicAllocator.getInstance().getDeviceId();
                long reqMem = AllocationUtils.getRequiredMemory(shape);

                // FIXME: this is WRONG, and directly leads to memleak
                if (reqMem < 1)
                    reqMem = 1;

                AllocationsTracker.getInstance().markAllocated(AllocationKind.GENERAL, deviceId, reqMem);
                var pointer = nativeOps.mallocDevice(reqMem, deviceId, 0);
                if (pointer == null) {
                    // try to purge stuff if we're low on memory
                    purgeCache(deviceId);

                    // call for gc
                    Nd4j.getMemoryManager().invokeGc();

                    pointer = nativeOps.mallocDevice(reqMem, deviceId, 0);
                    if (pointer == null)
                        return null;
                }

                val devicePointer = new CudaPointer(pointer);

                var devicePointerInfo = point.getPointers();
                if (devicePointerInfo == null)
                    devicePointerInfo = new PointersPair();
                devicePointerInfo.setDevicePointer(new CudaPointer(devicePointer, reqMem));

                point.setAllocationStatus(AllocationStatus.DEVICE);
                point.setDeviceId(deviceId);
                MemoryTracker.getInstance().incrementAllocatedAmount(deviceId, reqMem);
                return devicePointerInfo;
            }
            default:
                throw new IllegalStateException("Unsupported location for malloc: [" + location + "]");
        }
    }
1124039
public void setTo( int[] array , int offset , int length ) {
		resize(length);
		System.arraycopy(array,offset,data,0,length);
	}
992938
public T alloc() {
    if (numFree == 0) {
      Preconditions.checkState(numAlloc < maxSize);
      numAlloc++;
      return allocator.get();
    } else {
      T item = free[numFree - 1];
      numFree--;
      return item;
    }
  }
429318
@Override
    @SuppressWarnings("unchecked")
    protected void ensureCapacity(int capacity) {
        checkCapacity(capacity);
        K[] newArray = (K[]) new Object[capacity];
        System.arraycopy(array, 0, newArray, 0, size);
        array = newArray;
        BitSet newBitSet = new BitSet(capacity);
        newBitSet.or(reverse);
        reverse = newBitSet;
    }
448940
@Override
    public AllocationPoint allocateMemory(DataBuffer buffer, AllocationShape requiredMemory, AllocationStatus location,
                    boolean initialize) {
        AllocationPoint point = new AllocationPoint();

        useTracker.set(System.currentTimeMillis());

        // we use these longs as tracking codes for memory tracking
        Long allocId = objectsTracker.getAndIncrement();
        //point.attachBuffer(buffer);
        point.setObjectId(allocId);
        point.setShape(requiredMemory);
        /*
        if (buffer instanceof CudaIntDataBuffer) {
            buffer.setConstant(true);
            point.setConstant(true);
        }
        */
        /*int numBuckets = configuration.getNumberOfGcThreads();
        int bucketId = RandomUtils.nextInt(0, numBuckets);

        GarbageBufferReference reference =
                        new GarbageBufferReference((BaseDataBuffer) buffer, queueMap.get(bucketId), point);*/
        //point.attachReference(reference);
        point.setDeviceId(-1);

        if (buffer.isAttached()) {
            long reqMem = AllocationUtils.getRequiredMemory(requiredMemory);
            //log.info("Allocating {} bytes from attached memory...", reqMem);

            // workaround for init order
            getMemoryHandler().getCudaContext();
            point.setDeviceId(Nd4j.getAffinityManager().getDeviceForCurrentThread());

            val workspace = (CudaWorkspace) Nd4j.getMemoryManager().getCurrentWorkspace();

            val pair = new PointersPair();

            val ptrDev = workspace.alloc(reqMem, MemoryKind.DEVICE, requiredMemory.getDataType(), initialize);
            //val addr = ptrDev.address();
            //log.info("Allocated device pointer: {}; Divider: {}; ReqMem: {}; ReqMem divider: {};", addr, addr % 8, reqMem, reqMem % 8);
            val ptrHost = workspace.alloc(reqMem, MemoryKind.HOST, requiredMemory.getDataType(), initialize);

            pair.setHostPointer(ptrHost);
            if (ptrDev != null) {
                pair.setDevicePointer(ptrDev);
                point.setAllocationStatus(AllocationStatus.DEVICE);
            } else {
                pair.setDevicePointer(ptrHost);
                point.setAllocationStatus(AllocationStatus.HOST);
            }

            point.setAttached(true);

            point.setPointers(pair);
        } else {
            // we stay naive on PointersPair, we just don't know on this level, which pointers are set. MemoryHandler will be used for that
            PointersPair pair = memoryHandler.alloc(location, point, requiredMemory, initialize);
            point.setPointers(pair);
        }

        allocationsMap.put(allocId, point);
        //point.tickHostRead();
        point.tickDeviceWrite();
        return point;
    }
507878
private void ensureCapacity() {
		if (size < selectionKeys.length) {
			return;
		}
		SelectionKey[] newArray = new SelectionKey[selectionKeys.length * 2];
		System.arraycopy(selectionKeys, 0, newArray, 0, size);
		selectionKeys = newArray;
	}
872468
Allocation allocate(Mutation mutation, int size)
    {
        final OpOrder.Group opGroup = appendOrder.start();
        try
        {
            int position = allocate(size);
            if (position < 0)
            {
                opGroup.close();
                return null;
            }
            markDirty(mutation, position);
            return new Allocation(this, opGroup, position, (ByteBuffer) buffer.duplicate().position(position).limit(position + size));
        }
        catch (Throwable t)
        {
            opGroup.close();
            throw t;
        }
    }
348416
private void ensureCapacity(int minCapacity) {
		long currentCapacity = data.length;

		if (minCapacity <= currentCapacity) {
			return;
		}

		// increase capacity by at least ~50%
		long expandedCapacity = Math.max(minCapacity, currentCapacity + (currentCapacity >> 1));
		int newCapacity = (int) Math.min(MAX_ARRAY_SIZE, expandedCapacity);

		if (newCapacity < minCapacity) {
			// throw exception as unbounded arrays are not expected to fill
			throw new RuntimeException("Requested array size " + minCapacity + " exceeds limit of " + MAX_ARRAY_SIZE);
		}

		data = Arrays.copyOf(data, newCapacity);
	}
129731
void realloc(boolean throwIfFail) {
        // Double the capacity while it is "sufficiently small", and otherwise increase by 50%.
        int newLength = capacity <= 65536 ? capacity << 1 : capacity + capacity >> 1;

        try {
            ByteBuffer buffer = Buffer.allocateDirectWithNativeOrder(calculateBufferCapacity(newLength));
            // Copy over the old content of the memory and reset the position as we always act on the buffer as if
            // the position was never increased.
            memory.position(0).limit(size);
            buffer.put(memory);
            buffer.position(0);

            Buffer.free(memory);
            memory = buffer;
            memoryAddress = Buffer.memoryAddress(buffer);
        } catch (OutOfMemoryError e) {
            if (throwIfFail) {
                OutOfMemoryError error = new OutOfMemoryError(
                        "unable to allocate " + newLength + " new bytes! Existing capacity is: " + capacity);
                error.initCause(e);
                throw error;
            }
        }
    }
1329187
protected void fillArray(final short[] array) {
    int pos = 0;
    int base = 0;
    for (int k = 0; k < bitmap.length; ++k) {
      long bitset = bitmap[k];
      while (bitset != 0) {
        array[pos++] = (short) (base + numberOfTrailingZeros(bitset));
        bitset &= (bitset - 1);
      }
      base += 64;
    }
  }
539013
private static void allocateNodeLengths(final int[] array) {
        int firstNode = array.length - 2;
        int nextNode = array.length - 1;

        for (int currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) {
            final int lastNode = firstNode;
            firstNode = first(array, lastNode - 1, 0);

            for (int i = availableNodes - (lastNode - firstNode); i > 0; i--) {
                array[nextNode--] = currentDepth;
            }

            availableNodes = (lastNode - firstNode) << 1;
        }
    }
792426
function() {

    var _buffer = new Array();
    var _length = 0;

    var _this = {};

    _this.getBuffer = function() {
	return _buffer;
    };

    _this.getAt = function(index) {
	var bufIndex = Math.floor(index / 8);
	return ( (_buffer[bufIndex] >>> (7 - index % 8) ) & 1) == 1;
    };

    _this.put = function(num, length) {
	for (var i = 0; i < length; i += 1) {
	    _this.putBit( ( (num >>> (length - i - 1) ) & 1) == 1);
	}
    };

    _this.getLengthInBits = function() {
	return _length;
    };

    _this.putBit = function(bit) {

	var bufIndex = Math.floor(_length / 8);
	if (_buffer.length <= bufIndex) {
	    _buffer.push(0);
	}

	if (bit) {
	    _buffer[bufIndex] |= (0x80 >>> (_length % 8) );
	}

	_length += 1;
    };

    return _this;
}
1223830
private static void writeInt(int value, byte[] array, int offset) {
    for (int i = 0; i < 4; i++) {
      array[offset + i] = (byte) (value >>> (8 * i));
    }
  }
711983
private void ensureCapacity (int n)    {
        if (n <= 0) {
            return;
        }
        int max;
        if (data == null || data.length == 0) {
            max = 25;
        }
        else if (data.length >= n * 5) {
            return;
        }
        else {
            max = data.length;
        }
        while (max < n * 5) {
            max *= 2;
        }

        String newData[] = new String[max];
        if (length > 0) {
            System.arraycopy(data, 0, newData, 0, length*5);
        }
        data = newData;
    }
1282210
def build_pointer_array(array, type)
      buffer = FFI::MemoryPointer.new type, array.length
      buffer.send("write_array_of_#{type}".to_sym,  array)

      buffer
    end