Example usage for java.util Arrays copyOf

List of usage examples for java.util Arrays copyOf

Introduction

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

Prototype

public static boolean[] copyOf(boolean[] original, int newLength) 

Source Link

Document

Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.

Usage

From source file:Main.java

public static void main(String[] args) {

    // intializing an array arr1
    float[] arr1 = new float[] { 10f, 20f, 25f };

    System.out.println(Arrays.toString(arr1));

    // copying array arr1 to arr2 with newlength as 5
    float[] arr2 = Arrays.copyOf(arr1, 5);
    arr2[3] = 30f;/*from   w  w w  .  j ava  2  s  .  c om*/
    arr2[4] = 40f;

    System.out.println(Arrays.toString(arr2));
}

From source file:Main.java

public static void main(String[] args) {

    // intializing an array arr1
    double[] arr1 = new double[] { 1.5, 2.5, 3.5 };

    System.out.println(Arrays.toString(arr1));

    // copying array arr1 to arr2 with newlength as 5
    double[] arr2 = Arrays.copyOf(arr1, 5);
    arr2[3] = 0.44;/*  ww  w  .  j  a  va 2 s  .  co  m*/
    arr2[4] = 0.55;

    System.out.println(Arrays.toString(arr2));
}

From source file:eu.stratosphere.yarn.YarnTaskManagerRunner.java

public static void main(final String[] args) throws IOException {
    Map<String, String> envs = System.getenv();
    final String yarnClientUsername = envs.get(Client.ENV_CLIENT_USERNAME);
    final String localDirs = envs.get(Environment.LOCAL_DIRS.key());

    // configure local directory
    final String[] newArgs = Arrays.copyOf(args, args.length + 2);
    newArgs[newArgs.length - 2] = "-" + TaskManager.ARG_CONF_DIR;
    newArgs[newArgs.length - 1] = localDirs;
    LOG.info("Setting log path " + localDirs);
    LOG.info("YARN daemon runs as '" + UserGroupInformation.getCurrentUser().getShortUserName() + "' setting"
            + " user to execute Stratosphere TaskManager to '" + yarnClientUsername + "'");
    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(yarnClientUsername);
    for (Token<? extends TokenIdentifier> toks : UserGroupInformation.getCurrentUser().getTokens()) {
        ugi.addToken(toks);/*  w ww  .j  a va 2s. c o m*/
    }
    ugi.doAs(new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                TaskManager.main(newArgs);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}

From source file:mase.deprecated.SelectionBenchmark.java

public static void main(String[] args) {

    int L = 100, N = 10000;
    double[] truncationP = new double[] { 0.25, 0.50, 0.75 };
    int[] tournamentP = new int[] { 2, 5, 7, 10 };

    DescriptiveStatistics[] truncationStat = new DescriptiveStatistics[truncationP.length];
    for (int i = 0; i < truncationStat.length; i++) {
        truncationStat[i] = new DescriptiveStatistics();
    }//  w w w  . ja va2s .c  o m
    DescriptiveStatistics[] tournamentStat = new DescriptiveStatistics[tournamentP.length];
    DescriptiveStatistics[] tournamentStat2 = new DescriptiveStatistics[tournamentP.length];
    for (int i = 0; i < tournamentStat.length; i++) {
        tournamentStat[i] = new DescriptiveStatistics();
        tournamentStat2[i] = new DescriptiveStatistics();
    }
    DescriptiveStatistics rouletteStat = new DescriptiveStatistics();
    DescriptiveStatistics rouletteStat2 = new DescriptiveStatistics();
    DescriptiveStatistics baseStat = new DescriptiveStatistics();

    for (int i = 0; i < N; i++) {
        // generate test vector
        double[] test = new double[L];
        for (int j = 0; j < L; j++) {
            test[j] = Math.random();
        }

        // truncation
        for (int p = 0; p < truncationP.length; p++) {
            double[] v = Arrays.copyOf(test, test.length);
            Arrays.sort(v);
            int nElites = (int) Math.ceil(truncationP[p] * test.length);
            double cutoff = v[test.length - nElites];
            double[] weights = new double[test.length];
            for (int k = 0; k < test.length; k++) {
                weights[k] = test[k] >= cutoff ? test[k] * (1 / truncationP[p]) : 0;
            }
            truncationStat[p].addValue(sum(weights));
        }

        // tournament
        for (int p = 0; p < tournamentP.length; p++) {
            double[] weights = new double[test.length];
            HashSet<Integer> added = new HashSet<Integer>();
            for (int k = 0; k < test.length; k++) {
                int idx = makeTournament(test, tournamentP[p]);
                weights[idx] += test[idx];
                added.add(idx);
            }
            tournamentStat2[p].addValue(added.size());
            tournamentStat[p].addValue(sum(weights));
        }

        // roulette
        double[] weights = new double[test.length];
        HashSet<Integer> added = new HashSet<Integer>();
        for (int k = 0; k < test.length; k++) {
            int idx = roulette(test);
            weights[idx] += test[idx];
            added.add(idx);
        }
        rouletteStat.addValue(sum(weights));
        rouletteStat2.addValue(added.size());

        // base
        baseStat.addValue(sum(test));
    }

    for (int p = 0; p < truncationP.length; p++) {
        System.out.println("Truncation\t" + truncationP[p] + "\t" + truncationStat[p].getMean() + "\t"
                + truncationStat[p].getStandardDeviation() + "\t" + ((int) Math.ceil(L * truncationP[p]))
                + "\t 0");
    }
    for (int p = 0; p < tournamentP.length; p++) {
        System.out.println("Tournament\t" + tournamentP[p] + "\t" + tournamentStat[p].getMean() + "\t"
                + tournamentStat[p].getStandardDeviation() + "\t" + tournamentStat2[p].getMean() + "\t"
                + tournamentStat2[p].getStandardDeviation());
    }
    System.out.println("Roulette\t\t" + rouletteStat.getMean() + "\t" + rouletteStat.getStandardDeviation()
            + "\t" + rouletteStat2.getMean() + "\t" + rouletteStat2.getStandardDeviation());
    System.out.println(
            "Base    \t\t" + baseStat.getMean() + "\t" + baseStat.getStandardDeviation() + "\t " + L + "\t0");
}

From source file:GrowBufferedReader.java

public static void main(String... args) {
    try {// ww  w.  j a  va 2s .  co  m
        BufferedReader br = new BufferedReader(car);

        Class<?> c = br.getClass();
        Field f = c.getDeclaredField("cb");

        // cb is a private field
        f.setAccessible(true);
        char[] cbVal = char[].class.cast(f.get(br));

        char[] newVal = Arrays.copyOf(cbVal, cbVal.length * 2);
        if (args.length > 0 && args[0].equals("grow"))
            f.set(br, newVal);

        for (int i = 0; i < srcBufSize; i++)
            br.read();

        // see if the new backing array is being used
        if (newVal[srcBufSize - 1] == src[srcBufSize - 1])
            out.format("Using new backing array, size=%d%n", newVal.length);
        else
            out.format("Using original backing array, size=%d%n", cbVal.length);

        // production code should handle these exceptions more gracefully
    } catch (FileNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (IOException x) {
        x.printStackTrace();
    }
}

From source file:com.linkedin.pinot.perf.MultiValueReaderWriterBenchmark.java

public static void main(String[] args) throws Exception {
    List<String> lines = IOUtils.readLines(new FileReader(new File(args[0])));
    int totalDocs = lines.size();
    int max = Integer.MIN_VALUE;
    int maxNumberOfMultiValues = Integer.MIN_VALUE;
    int totalNumValues = 0;
    int data[][] = new int[totalDocs][];
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);
        String[] split = line.split(",");
        totalNumValues = totalNumValues + split.length;
        if (split.length > maxNumberOfMultiValues) {
            maxNumberOfMultiValues = split.length;
        }/*from   w ww  .  jav  a2s . c  o m*/
        data[i] = new int[split.length];
        for (int j = 0; j < split.length; j++) {
            String token = split[j];
            int val = Integer.parseInt(token);
            data[i][j] = val;
            if (val > max) {
                max = val;
            }
        }
    }
    int maxBitsNeeded = (int) Math.ceil(Math.log(max) / Math.log(2));
    int size = 2048;
    int[] offsets = new int[size];
    int bitMapSize = 0;
    File outputFile = new File("output.mv.fwd");

    FixedBitSkipListSCMVWriter fixedBitSkipListSCMVWriter = new FixedBitSkipListSCMVWriter(outputFile,
            totalDocs, totalNumValues, maxBitsNeeded);

    for (int i = 0; i < totalDocs; i++) {
        fixedBitSkipListSCMVWriter.setIntArray(i, data[i]);
        if (i % size == size - 1) {
            MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(offsets);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            rr1.serialize(dos);
            dos.close();
            //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size());
            bitMapSize += bos.size();
        } else if (i == totalDocs - 1) {
            MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(Arrays.copyOf(offsets, i % size));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            rr1.serialize(dos);
            dos.close();
            //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size());
            bitMapSize += bos.size();
        }
    }
    fixedBitSkipListSCMVWriter.close();
    System.out.println("Output file size:" + outputFile.length());
    System.out.println("totalNumberOfDoc\t\t\t:" + totalDocs);
    System.out.println("totalNumberOfValues\t\t\t:" + totalNumValues);
    System.out.println("chunk size\t\t\t\t:" + size);
    System.out.println("Num chunks\t\t\t\t:" + totalDocs / size);
    int numChunks = totalDocs / size + 1;
    int totalBits = (totalNumValues * maxBitsNeeded);
    int dataSizeinBytes = (totalBits + 7) / 8;

    System.out.println("Raw data size with fixed bit encoding\t:" + dataSizeinBytes);
    System.out.println("\nPer encoding size");
    System.out.println();
    System.out.println("size (offset + length)\t\t\t:" + ((totalDocs * (4 + 4)) + dataSizeinBytes));
    System.out.println();
    System.out.println("size (offset only)\t\t\t:" + ((totalDocs * (4)) + dataSizeinBytes));
    System.out.println();
    System.out.println("bitMapSize\t\t\t\t:" + bitMapSize);
    System.out.println("size (with bitmap)\t\t\t:" + (bitMapSize + (numChunks * 4) + dataSizeinBytes));

    System.out.println();
    System.out.println("Custom Bitset\t\t\t\t:" + (totalNumValues + 7) / 8);
    System.out.println("size (with custom bitset)\t\t\t:"
            + (((totalNumValues + 7) / 8) + (numChunks * 4) + dataSizeinBytes));

}

From source file:edu.msu.cme.rdp.readseq.utils.QualityTrimmer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("f", "fastq-out", false, "Write fastq instead of fasta file");
    options.addOption("l", "less-than", false, "Trim at <= instead of strictly =");
    options.addOption("i", "illumina", false, "Illumina trimming mode");

    FastqWriter fastqOut = null;/* w  w w  . j a v  a 2s .c o m*/
    FastaWriter fastaOut = null;

    byte qualTrim = -1;

    boolean writeFasta = true;
    boolean trimle = false;
    boolean illumina = false;

    List<SeqReader> readers = new ArrayList();
    List<File> seqFiles = new ArrayList();

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("fastq-out")) {
            writeFasta = false;
        }

        if (line.hasOption("less-than")) {
            trimle = true;
        }
        if (line.hasOption("illumina")) {
            illumina = true;
        }

        args = line.getArgs();

        if (args.length < 2) {
            throw new Exception("Unexpected number of arguments");
        }

        if (args[0].length() != 1) {
            throw new Exception("Expected single character quality score");
        }

        qualTrim = FastqCore.Phred33QualFunction.translate(args[0].charAt(0));

        for (int index = 1; index < args.length; index++) {
            File seqFile = new File(args[index]);
            SeqReader reader;
            if (SeqUtils.guessFileFormat(seqFile) == SequenceFormat.FASTA) {
                if (index + 1 == args.length) {
                    throw new Exception("Fasta files must be immediately followed by their quality file");
                }

                File qualFile = new File(args[index + 1]);
                if (SeqUtils.guessFileFormat(qualFile) != SequenceFormat.FASTA) {
                    throw new Exception(seqFile + " was not followed by a fasta quality file");
                }

                reader = new QSeqReader(seqFile, qualFile);
                index++;
            } else {
                if (seqFile.getName().endsWith(".gz")) {
                    reader = new SequenceReader(new GZIPInputStream(new FileInputStream(seqFile)));
                } else {
                    reader = new SequenceReader(seqFile);
                }
            }

            readers.add(reader);
            seqFiles.add(seqFile);
        }
    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: QualityTrimmer [options] <ascii_score> <seq_file> [qual_file]",
                options, true);
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    for (int readerIndex = 0; readerIndex < readers.size(); readerIndex++) {
        File seqFile = seqFiles.get(readerIndex);
        String outStem = "trimmed_" + seqFile.getName().substring(0, seqFile.getName().lastIndexOf("."));
        if (writeFasta) {
            fastaOut = new FastaWriter(outStem + ".fasta");
        } else {
            fastqOut = new FastqWriter(outStem + ".fastq", FastqCore.Phred33QualFunction);
        }

        int[] lengthHisto = new int[200];

        SeqReader reader = readers.get(readerIndex);

        QSequence qseq;

        long totalLength = 0;
        int totalSeqs = 0;
        long trimmedLength = 0;
        int trimmedSeqs = 0;

        int zeroLengthAfterTrimming = 0;

        long startTime = System.currentTimeMillis();

        while ((qseq = (QSequence) reader.readNextSequence()) != null) {
            char[] bases = qseq.getSeqString().toCharArray();
            byte[] qual = qseq.getQuality();

            if (bases.length != qual.length) {
                System.err.println(qseq.getSeqName() + ": Quality length doesn't match seq length for seq");
                continue;
            }

            totalSeqs++;
            totalLength += bases.length;

            int trimIndex = -1;
            if (illumina && qual[bases.length - 1] == qualTrim) {
                trimIndex = bases.length - 1;
                while (trimIndex >= 0 && qual[trimIndex] == qualTrim) {
                    trimIndex--;
                }

                trimIndex++; //Technically we're positioned over the first good base, move back to the last bad base
            } else if (!illumina) {
                for (int index = 0; index < bases.length; index++) {
                    if (qual[index] == qualTrim || (trimle && qual[index] < qualTrim)) {
                        trimIndex = index;
                        break;
                    }
                }
            }

            String outSeq;
            byte[] outQual;
            if (trimIndex == -1) {
                outSeq = qseq.getSeqString();
                outQual = qseq.getQuality();
            } else {
                outSeq = new String(bases, 0, trimIndex);
                outQual = Arrays.copyOfRange(qual, 0, trimIndex);
                trimmedSeqs++;
            }
            int len = outSeq.length();
            trimmedLength += len;

            if (len >= lengthHisto.length) {
                lengthHisto = Arrays.copyOf(lengthHisto, len + 1);
            }
            lengthHisto[len]++;

            if (outSeq.length() == 0) {
                //System.err.println(qseq.getSeqName() + ": length 0 after trimming");
                zeroLengthAfterTrimming++;
                continue;
            }

            if (writeFasta) {
                fastaOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq);
            } else {
                fastqOut.writeSeq(qseq.getSeqName(), qseq.getDesc(), outSeq, outQual);
            }
        }

        reader.close();

        if (writeFasta) {
            fastaOut.close();
        } else {
            fastqOut.close();
        }

        System.out.println(
                "Processed " + seqFile + " in " + (System.currentTimeMillis() - startTime) / 1000.0 + "s");
        System.out.println("Before trimming:");
        System.out.println("Total Sequences:           " + totalSeqs);
        System.out.println("Total Sequence Data:       " + totalLength);
        System.out.println("Average sequence length:   " + ((float) totalLength / totalSeqs));
        System.out.println();
        System.out.println("After trimming:");
        System.out.println("Total Sequences:           " + (totalSeqs - zeroLengthAfterTrimming));
        System.out.println("Sequences Trimmed:         " + trimmedSeqs);
        System.out.println("Total Sequence Data:       " + trimmedLength);
        System.out.println("Average sequence length:   "
                + ((float) trimmedLength / (totalSeqs - zeroLengthAfterTrimming)));
        System.out.println();

        System.out.println("Length\tCount");
        for (int index = 0; index < lengthHisto.length; index++) {
            if (lengthHisto[index] == 0) {
                continue;
            }

            System.out.println(index + "\t" + lengthHisto[index]);
        }

        System.out.println();
        System.out.println();
        System.out.println();
    }
}

From source file:Main.java

public static String[] copyArray(String[] arr) {
    String[] arrNew = Arrays.copyOf(arr, arr.length);
    return arrNew;
}

From source file:Main.java

public static <T> T[] concatArrays(T[] a, T[] b) {
    T[] result = Arrays.copyOf(a, a.length + b.length);
    System.arraycopy(b, 0, result, a.length, b.length);
    return result;
}

From source file:Main.java

public static <T> T[] concat(T[] first, T[] second) {
    T[] result = Arrays.copyOf(first, first.length + second.length);
    System.arraycopy(second, 0, result, first.length, second.length);
    return result;
}