Example usage for java.util Arrays fill

List of usage examples for java.util Arrays fill

Introduction

In this page you can find the example usage for java.util Arrays fill.

Prototype

public static void fill(Object[] a, Object val) 

Source Link

Document

Assigns the specified Object reference to each element of the specified array of Objects.

Usage

From source file:org.powertac.customer.model.LpTest.java

/**
 * Simple tariff eval example./*  w  w w  .j ava  2 s  .  c  o  m*/
 * We ignore periodic charges, because those are handled by the
 * TariffEvaluator. We'll just use a simple TOU with daytime rates
 * (8:00-19:00) of 0.15 and night rates (20:00-7:00) of 0.09.
 * Example is 24 hours, starting at the beginning of a midnight
 * shift. The numbers are from the "idle" version of the
 * futureEnergyNeeds test, with an initial charge of 20 kwh.
 *  end  trk  req  max  sur     min total
 *    8    6  256  240  -16+20    236
 *   16    8    0  240  240       236
 *    0    0  192  240   32       428
 *    8    6  256  240  -16       684
 * We use 5 chargers, 6kW/charger, no battery count constraints,
 * 0.9 charge efficiency.
 */
@Test
public void testLpTOU() {
    Date start = new Date();
    int chargers = 5;
    double kW = 6.0;
    double eff = 0.9;
    int columns = 24;
    int shifts = 3;
    int rps = 2; // rows per shift
    int slackColumns = shifts * rps;
    double[] obj = { .09, .09, .09, .09, .09, .09, .09, .09, .15, .15, .15, .15, .15, .15, .15, .15, .15, .15,
            .15, .15, .09, .09, .09, .09, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
    assertEquals("correct size", columns + slackColumns, obj.length);
    // constraints: 1 row/timeslot + three rows/ShiftEnergy
    int rows = shifts * rps;
    double[][] a = new double[rows][columns + slackColumns];
    double[] b = new double[rows];
    // bounds: lb and ub per column
    double[] ub = new double[columns + slackColumns]; // should be max(chargers, batteries)
    double[] lb = new double[columns + slackColumns];
    // max usage/timeslot
    Arrays.fill(ub, chargers * kW / eff);
    // min usage/timeslot
    Arrays.fill(lb, 0.0);
    // min & max usage per shift
    double[] req = { 240.0 / eff, 0.0, 192.0 / eff };
    double[] cum = { 236.0 / eff, 236.0 / eff, 428.0 / eff };
    for (int i = 0; i < shifts; i++) {
        // sum(p(t)) + slackI1 = min(req, max), t in shift
        for (int j = 0; j < 8; j++) {
            a[i * rps][i * 8 + j] = -1.0;
            a[i * rps][columns + i * rps] = -1.0;
            b[i * rps] = -req[i];
        }
        // -sum(p(t)) + slackI2 = -total
        for (int j = 0; j < (i + 1) * 8; j++) {
            a[i * rps + 1][j] = -1.0;
            a[i * rps + 1][columns + i * rps + 1] = -1.0;
            b[i * rps + 1] = -cum[i];
        }
    }
    LPOptimizationRequest or = new LPOptimizationRequest();
    or.setC(obj);
    or.setA(a);
    or.setB(b);
    or.setLb(lb);
    or.setUb(ub);
    or.setDumpProblem(true);

    //optimization
    LPPrimalDualMethod opt = new LPPrimalDualMethod();

    opt.setLPOptimizationRequest(or);
    try {
        int returnCode = opt.optimize();
        assertEquals("success", OptimizationResponse.SUCCESS, returnCode);
        double[] sol = opt.getOptimizationResponse().getSolution();
        Date end = new Date();
        System.out.println("Duration = " + (end.getTime() - start.getTime()));
        System.out.println("Solution = " + Arrays.toString(sol));
    } catch (Exception e) {
        fail(e.toString());
    }
}

From source file:com.unister.semweb.drums.bucket.hashfunction.RangeHashFunction.java

private void initHashFunction(byte[] minKey, byte[] maxKey, int ranges) {
    this.maxRangeValues = KeyUtils.getMaxValsPerRange(minKey, maxKey, ranges);
    this.filenames = new String[ranges];
    for (int i = 0; i < ranges; i++) {
        filenames[i] = i + ".db";
    }/*from   www  .  ja  v a2  s. co  m*/
    this.keyComposition = new int[minKey.length];
    Arrays.fill(keyComposition, 1);
    sort();
}

From source file:com.github.tteofili.looseen.yay.SGM.java

private RealMatrix[] initBiases() {

    RealMatrix[] initialBiases = new RealMatrix[weights.length];

    for (int i = 0; i < initialBiases.length; i++) {
        double[] data = new double[weights[i].getRowDimension()];
        Arrays.fill(data, 0.01d);
        RealMatrix matrix = MatrixUtils.createRowRealMatrix(data);

        initialBiases[i] = matrix;//from   ww  w .j ava 2s .  c om
    }
    return initialBiases;
}

From source file:bftsmart.consensus.Epoch.java

private void updateArrays() {

    if (lastView.getId() != controller.getCurrentViewId()) {

        int n = controller.getCurrentViewN();

        byte[][] write = new byte[n][];
        byte[][] accept = new byte[n][];

        boolean[] writeSetted = new boolean[n];
        boolean[] acceptSetted = new boolean[n];

        Arrays.fill(writeSetted, false);
        Arrays.fill(acceptSetted, false);

        for (int pid : lastView.getProcesses()) {

            if (controller.isCurrentViewMember(pid)) {

                int currentPos = controller.getCurrentViewPos(pid);
                int lastPos = lastView.getPos(pid);

                write[currentPos] = this.write[lastPos];
                accept[currentPos] = this.accept[lastPos];

                writeSetted[currentPos] = this.writeSetted[lastPos];
                acceptSetted[currentPos] = this.acceptSetted[lastPos];

            }/*w  ww  .  j  av  a 2s.  c o m*/
        }

        this.write = write;
        this.accept = accept;

        this.writeSetted = writeSetted;
        this.acceptSetted = acceptSetted;

        lastView = controller.getCurrentView();

    }
}

From source file:com.vmware.identity.rest.idm.data.PrivateKeyDTO.java

private static String encodePrivateKey(PrivateKey key)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    if (key == null) {
        return null;
    }//from  w w  w  .  j  ava  2s.c  o  m

    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
    byte[] packed = spec.getEncoded();
    String encodePrivateKey = Base64.encodeBase64String(packed);
    Arrays.fill(packed, (byte) 0);
    return encodePrivateKey;
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibMatrixDatagen.java

/**
 * //from   ww  w.  j a  v a  2  s .c o m
 * @param nrow
 * @param ncol
 * @param brlen
 * @param bclen
 * @param sparsity
 * @return
 * @throws DMLRuntimeException
 */
public static long[] computeNNZperBlock(long nrow, long ncol, int brlen, int bclen, double sparsity)
        throws DMLRuntimeException {
    int numBlocks = (int) (Math.ceil((double) nrow / brlen) * Math.ceil((double) ncol / bclen));
    //System.out.println("nrow=" + nrow + ", brlen=" + brlen + ", ncol="+ncol+", bclen=" + bclen + "::: " + Math.ceil(nrow/brlen));

    // CURRENT: 
    //       Total #of NNZ is set to the expected value (nrow*ncol*sparsity).
    // TODO: 
    //      Instead of using the expected value, one should actually 
    //       treat NNZ as a random variable and accordingly generate a random value.
    long nnz = (long) Math.ceil(nrow * (ncol * sparsity));
    //System.out.println("Number of blocks = " + numBlocks + "; NNZ = " + nnz);

    if (numBlocks > Integer.MAX_VALUE) {
        throw new DMLRuntimeException(
                "A random matrix of size [" + nrow + "," + ncol + "] can not be created. Number of blocks ("
                        + numBlocks + ") exceeds the maximum integer size. Try to increase the block size.");
    }

    // Compute block-level NNZ
    long[] ret = new long[numBlocks];
    Arrays.fill(ret, 0);

    if (nnz < numBlocks) {
        // Ultra-sparse matrix

        // generate the number of blocks with at least one non-zero
        // = a random number between [1,nnz]
        Random runif = new Random(System.nanoTime());
        int numNZBlocks = 1;
        if (nnz - 1 > 0)
            numNZBlocks += runif.nextInt((int) (nnz - 1)); // To avoid exception from random.nextInt(0) 

        // distribute non-zeros across numNZBlocks

        // compute proportions for each nzblock 
        // - divide (0,1] interval into numNZBlocks portions of random size
        double[] blockNNZproportions = new double[numNZBlocks];

        runif.setSeed(System.nanoTime());
        for (int i = 0; i < numNZBlocks - 1; i++) {
            blockNNZproportions[i] = runif.nextDouble();
        }
        blockNNZproportions[numNZBlocks - 1] = 1;
        // sort the values in ascending order
        Arrays.sort(blockNNZproportions);

        // compute actual number of non zeros per block according to proportions
        long actualnnz = 0;
        int bid;
        runif.setSeed(System.nanoTime());
        for (int i = 0; i < numNZBlocks; i++) {
            bid = -1;
            do {
                bid = runif.nextInt(numBlocks);
            } while (ret[bid] != 0);

            double prop = (i == 0 ? blockNNZproportions[i]
                    : (blockNNZproportions[i] - blockNNZproportions[i - 1]));
            ret[bid] = (long) Math.floor(prop * nnz);
            actualnnz += ret[bid];
        }

        // Code to make sure exact number of non-zeros are generated
        while (actualnnz < nnz) {
            bid = runif.nextInt(numBlocks);
            ret[bid]++;
            actualnnz++;
        }
    } else {
        int bid = 0;

        //long actualnnz = 0;
        for (long r = 0; r < nrow; r += brlen) {
            long curBlockRowSize = Math.min(brlen, (nrow - r));
            for (long c = 0; c < ncol; c += bclen) {
                long curBlockColSize = Math.min(bclen, (ncol - c));
                ret[bid] = (long) (curBlockRowSize * curBlockColSize * sparsity);
                //actualnnz += ret[bid];
                bid++;
            }
        }
    }
    return ret;
}

From source file:com.linkedin.r2.filter.compression.stream.TestStreamingCompression.java

@Test
public void testBzip2Compressor()
        throws IOException, InterruptedException, CompressionException, ExecutionException {
    StreamingCompressor compressor = new Bzip2Compressor(_executor);
    final byte[] origin = new byte[BUF_SIZE];
    Arrays.fill(origin, (byte) 'c');

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BZip2CompressorOutputStream bzip = new BZip2CompressorOutputStream(out);
    IOUtils.write(origin, bzip);/*from   w  w  w .j  av  a 2s.  c  om*/
    bzip.close();
    byte[] compressed = out.toByteArray();

    testCompress(compressor, origin, compressed);
    testDecompress(compressor, origin, compressed);
    testCompressThenDecompress(compressor, origin);
}

From source file:com.linkedin.pinot.controller.validation.StorageQuotaCheckerTest.java

@Test
public void testWithinQuota() throws IOException {
    File tempFile = new File(TEST_DIR, "small_file");
    tempFile.createNewFile();//from   ww  w .  j  av  a  2  s .  c om
    byte[] data = new byte[1024];
    Arrays.fill(data, (byte) 1);
    try (FileOutputStream ostr = new FileOutputStream(tempFile)) {
        ostr.write(data);
    }
    setupTableSegmentSize(5800, 900);
    when(tableConfig.getQuotaConfig()).thenReturn(quotaConfig);
    when(quotaConfig.storageSizeBytes()).thenReturn(3000L);
    StorageQuotaChecker checker = new StorageQuotaChecker(tableConfig, tableSizeReader);
    StorageQuotaChecker.QuotaCheckerResponse response = checker.isSegmentStorageWithinQuota(TEST_DIR,
            "testTable", "segment1", 1000);
    Assert.assertTrue(response.isSegmentWithinQuota);

    when(quotaConfig.storageSizeBytes()).thenReturn(2800L);
    response = checker.isSegmentStorageWithinQuota(TEST_DIR, "testTable", "segment1", 1000);
    Assert.assertFalse(response.isSegmentWithinQuota);
}

From source file:FastStack.java

/**
 * Clears the stack.// w  ww  .j a  va 2s  .  co m
 */
public void clear() {
    this.size = 0;
    if (this.contents != null) {
        Arrays.fill(this.contents, null);
    }
}

From source file:au.org.ala.delta.translation.TypeSetterTest.java

public void testLineWrapWithSpaceAtWrapPosition() {
    char[] input = new char[_lineWidth * 2];
    Arrays.fill(input, 'a');
    input[_lineWidth - 1] = ' ';

    _typeSetter.writeJustifiedText(new String(input), -1);
    _typeSetter.printBufferLine(false);/*from   w  ww  . j a v  a 2s.  co m*/

    String[] lines = output().split(SystemUtils.LINE_SEPARATOR);
    char[] expectedLine1Chars = Arrays.copyOfRange(input, 0, _lineWidth - 1);
    char[] expectedLine2Chars = Arrays.copyOfRange(input, _lineWidth, input.length);

    String expectedLine1 = new String(expectedLine1Chars);
    String expectedLine2 = new String(expectedLine2Chars);
    assertEquals(expectedLine1, lines[0]);
    assertEquals(expectedLine2, lines[1]);

    // Now do it again as two separate writes
    _typeSetter.writeJustifiedText(expectedLine1, -1);
    _typeSetter.writeJustifiedText(expectedLine2, -1);
    _typeSetter.printBufferLine(false);

    lines = output().split(SystemUtils.LINE_SEPARATOR);
    assertEquals(expectedLine1, lines[0]);
    assertEquals(expectedLine2, lines[1]);
}