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:com.inductiveautomation.xopc.drivers.modbus2.requests.WriteSingleRegisterRequest.java

private short getRegisterValue(ModbusAddress address, Variant variant) {
    ModbusDataType modbusType = address.getModbusDataType();

    switch (modbusType) {
    case BCD16:/* w w  w . jav a2 s.co m*/
        short bcd16 = (Short) TypeUtilities.coerce(variant.getValue(), Short.class);
        byte[] bcdBytes = BCDByteUtilities.get(ByteOrder.BIG_ENDIAN).fromShort(bcd16, 0xFFFF);

        return ByteUtilities.get(ByteOrder.BIG_ENDIAN).getShort(bcdBytes, 0);

    case String:
        // This is copypasta from WriteMultipleRegistersRequest... yuck.
        String s = TypeUtilities.toString(variant.getValue());
        int addressLength = address.getStringLength();

        if (s.length() > addressLength) {
            s = s.substring(0, addressLength);
        }

        byte[] padding = new byte[addressLength - s.length()];
        Arrays.fill(padding, (byte) ' ');

        byte[] stringBytes = rightJustifyStrings ? ArrayUtils.addAll(padding, s.getBytes())
                : ArrayUtils.addAll(s.getBytes(), padding);

        if (reverseStringByteOrder) {
            byte[] reversed = new byte[stringBytes.length];
            for (int i = 0; i < stringBytes.length; i += 2) {
                byte[] swapped = ByteUtilities.swapBytes(stringBytes, i);
                System.arraycopy(swapped, 0, reversed, i, swapped.length);
            }
            stringBytes = reversed;
        }

        return ByteUtilities.get(ByteOrder.BIG_ENDIAN).getShort(stringBytes, 0);

    default:
        return (Short) TypeUtilities.coerce(variant.getValue(), Short.class);
    }
}

From source file:edu.byu.nlp.util.Matrices.java

public static void fill(double[][] matrix, double[] x) {
    Preconditions.checkArgument(matrix.length == x.length);
    for (int i = 0; i < matrix.length; i++) {
        Arrays.fill(matrix[i], x[i]);
    }//  w ww.  j a  v a 2s.  c  o  m
}

From source file:com.neophob.sematrix.generator.Textwriter.java

@Override
public void update() {

    if (wait > 0) {
        wait--;//from  ww  w . java2  s.  co  m
    } else {
        if (maxXPos < getInternalBufferXSize()) {
            //no need to scroll
            xofs = (getInternalBufferXSize() - maxXPos) / 2;
            wait = 99999;
        } else {
            //todo, if image < buffer
            if (scrollRight) {
                xofs += SCROLL_AMMOUNT;
                if (xofs > maxXPos - internalBufferXSize) {
                    scrollRight = false;
                    xofs = maxXPos - internalBufferXSize;
                    wait = CHANGE_SCROLLING_DIRECTION_TIMEOUT;
                }
            } else {
                xofs -= SCROLL_AMMOUNT;
                if (xofs < 1) {
                    scrollRight = true;
                    xofs = 0;
                    wait = CHANGE_SCROLLING_DIRECTION_TIMEOUT;
                }
            }
        }
    }

    int srcOfs = xofs;
    int dstOfs = 0;

    try {
        if (maxXPos < getInternalBufferXSize()) {
            //text image smaller than internal buffer
            srcOfs = 0;
            dstOfs = xofs;
            //we need to clear the buffer first!
            Arrays.fill(tmp, 0);

            for (int y = 0; y < internalBufferYSize; y++) {
                System.arraycopy(textBuffer, srcOfs, tmp, dstOfs, maxXPos);
                dstOfs += internalBufferXSize;
                srcOfs += maxXPos;
            }
        } else {
            for (int y = 0; y < internalBufferYSize; y++) {
                System.arraycopy(textBuffer, srcOfs, tmp, dstOfs, internalBufferXSize);
                dstOfs += internalBufferXSize;
                srcOfs += maxXPos;
            }
        }

        this.internalBuffer = tmp;
    } catch (Exception e) {
        //if the image is resized, this could lead to an arrayoutofboundexception!
    }

}

From source file:com.github.lindenb.jvarkit.tools.bam2wig.Bam2Wig.java

private void run(final SamReader sfr) {
    SAMSequenceRecord prev_ssr = null;//from   ww  w .j  a  v  a  2s  .c  o m
    SAMSequenceDictionary dict = sfr.getFileHeader().getSequenceDictionary();
    SAMRecordIterator iter = sfr.iterator();
    int array[] = null;
    SAMSequenceDictionaryProgress progess = new SAMSequenceDictionaryProgress(dict);
    if (custom_track) {
        pw.println("track type=wiggle_0 name=\"__REPLACE_WIG_NAME__\" description=\"__REPLACE_WIG_DESC__\"");
    }

    for (;;) {
        SAMRecord rec = null;
        if (iter.hasNext()) {
            rec = iter.next();
            progess.watch(rec);
            if (rec.getReadUnmappedFlag())
                continue;
            if (rec.getMappingQuality() == 0)
                continue;
            if (rec.getMappingQuality() < min_qual)
                continue;
        }

        if (rec == null || (prev_ssr != null && prev_ssr.getSequenceIndex() != rec.getReferenceIndex())) {
            if (prev_ssr != null) {
                int start0 = 0;
                while (start0 < array.length && array[start0] == 0) {
                    ++start0;
                }

                int end0 = prev_ssr.getSequenceLength();
                while (end0 > 0 && array[end0 - 1] == 0) {
                    --end0;
                }

                int last_non_zero_pos0 = start0;
                int num_zero_regions_skipped = 0;
                boolean need_print_header = true;
                while (start0 < end0) {
                    /* 
                     * http://genome.ucsc.edu/goldenPath/help/wiggle.html
                       Wiggle track data values can be integer or real, positive or negative values.
                       Chromosome positions are specified as 1-relative.
                       For a chromosome of length N, the first position is 1 and the last position is N. Only positions specified have data. Positions not specified do not have data and will not be graphed. 
                     */

                    int n = 0;
                    double sum = 0;
                    for (int j = 0; j < WINDOW_SIZE && start0 + j < array.length; ++j) {
                        sum += array[start0 + j];
                        n++;
                    }

                    if (sum / n < min_depth) {
                        sum = 0;
                    }

                    if (sum == 0) {
                        start0 += WINDOW_SHIFT;
                        num_zero_regions_skipped++;
                        continue;
                    } else {
                        if ((start0 - last_non_zero_pos0) <= min_gap) {
                            for (int r = 0; r < num_zero_regions_skipped; ++r) {
                                pw.println(0);
                            }
                        } else {
                            need_print_header = (num_zero_regions_skipped > 0);
                        }

                        last_non_zero_pos0 = start0;
                        num_zero_regions_skipped = 0;
                    }

                    if (need_print_header) {
                        need_print_header = false;
                        pw.println("fixedStep chrom=" + prev_ssr.getSequenceName() + " start=" + (start0 + 1)
                                + " step=" + WINDOW_SHIFT + " span=" + WINDOW_SIZE);
                    }

                    if (cast_to_integer) {
                        pw.println((int) (sum / n));
                    } else {
                        pw.println((float) (sum / n));
                    }

                    if (pw.checkError())
                        break;
                    start0 += WINDOW_SHIFT;
                }
                array = null;
                System.gc();
                prev_ssr = null;
            }
            if (rec == null)
                break;
            if (pw.checkError())
                break;
        }
        if (prev_ssr == null) {
            prev_ssr = dict.getSequence(rec.getReferenceIndex());
            LOG.info("Allocating int[" + prev_ssr.getSequenceLength() + "]");
            array = new int[prev_ssr.getSequenceLength()];
            LOG.info("Allocating : Done.");
            Arrays.fill(array, 0);
        }

        final Cigar cigar = rec.getCigar();
        if (cigar == null)
            continue;
        int refpos1 = rec.getAlignmentStart();
        for (CigarElement ce : cigar.getCigarElements()) {
            final CigarOperator op = ce.getOperator();
            if (op.consumesReferenceBases()) {
                if (op.consumesReadBases()) {
                    for (int i = 0; i < ce.getLength() && refpos1 <= array.length; ++i) {
                        if (refpos1 >= 1 && refpos1 <= array.length) {
                            array[refpos1 - 1]++;
                        }
                        refpos1++;
                    }
                } else {
                    refpos1 += ce.getLength();
                }
            }
        }
    }
    progess.finish();
    iter.close();
    pw.flush();
}

From source file:alluxio.cli.MiniBenchmark.java

/**
 * Writes a file.//  w  ww  . j a  v a 2 s.com
 *
 * @param count the count to determine the filename
 * @throws Exception if it fails to write
 */
private static void writeFile(CyclicBarrier barrier, AtomicLong runtime, int count) throws Exception {
    FileSystem fileSystem = FileSystem.Factory.get();
    byte[] buffer = new byte[(int) Math.min(sFileSize, 4 * Constants.MB)];
    Arrays.fill(buffer, (byte) 'a');
    AlluxioURI path = filename(count);

    if (fileSystem.exists(path)) {
        fileSystem.delete(path);
    }

    barrier.await();
    long startTime = System.nanoTime();
    long bytesWritten = 0;
    try (FileOutStream outStream = fileSystem.createFile(path)) {
        while (bytesWritten < sFileSize) {
            outStream.write(buffer, 0, (int) Math.min(buffer.length, sFileSize - bytesWritten));
            bytesWritten += buffer.length;
        }
    }
    runtime.addAndGet(System.nanoTime() - startTime);
}

From source file:org.apache.xmlgraphics.util.io.SubInputStream.java

/**
     * Tests SubInputStream./*from   w ww.  j av a 2 s .  com*/
     * @throws Exception if an error occurs
     */
    public void testMain() throws Exception {
        //Initialize test data
        byte[] data = new byte[256];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (i & 0xff);
        }

        int v, c;
        byte[] buf;
        String s;

        SubInputStream subin = new SubInputStream(new ByteArrayInputStream(data), 10);
        v = subin.read();
        assertEquals(0, v);
        v = subin.read();
        assertEquals(1, v);

        buf = new byte[4];
        c = subin.read(buf);
        assertEquals(4, c);
        s = new String(buf, "US-ASCII");
        assertEquals("\u0002\u0003\u0004\u0005", s);

        Arrays.fill(buf, (byte) 0);
        c = subin.read(buf, 2, 2);
        assertEquals(2, c);
        s = new String(buf, "US-ASCII");
        assertEquals("\u0000\u0000\u0006\u0007", s);

        Arrays.fill(buf, (byte) 0);
        c = subin.read(buf);
        assertEquals(2, c);
        s = new String(buf, "US-ASCII");
        assertEquals("\u0008\u0009\u0000\u0000", s);
    }

From source file:com.analog.lyric.dimple.solvers.core.parameterizedMessages.MultivariateNormalParameters.java

private final void set(double[] meanOrInfo, double[] varianceOrPrecision, boolean informationForm) {
    final int n = _size = meanOrInfo.length;

    final double[] infoOrMean = new double[n];
    final double[] precisionOrVariance = new double[n];

    if (ArrayUtil.onlyContains(varianceOrPrecision, 0.0)) {
        // All zero => inverse is infinite
        Arrays.fill(precisionOrVariance, Double.POSITIVE_INFINITY);
        Arrays.fill(infoOrMean, Double.POSITIVE_INFINITY);
    } else if (ArrayUtil.onlyContains(varianceOrPrecision, Double.POSITIVE_INFINITY)) {
        // Infinite => inverse is zero
    } else {//from w w  w .  j  ava2 s .  com
        // Except for the all zero/infinite case, condition eigenvalues to not be too small/large FIXME hacky
        for (int i = 0; i < _size; ++i) {
            double x = varianceOrPrecision[i], inv = 1 / x;
            if (x < MIN_EIGENVALUE) {
                varianceOrPrecision[i] = MIN_EIGENVALUE;
                inv = 1 / MIN_EIGENVALUE;
            } else if (inv < MIN_EIGENVALUE) {
                varianceOrPrecision[i] = 1 / MIN_EIGENVALUE;
                inv = MIN_EIGENVALUE;
            }

            precisionOrVariance[i] = inv;
            infoOrMean[i] = meanOrInfo[i] * inv;
        }
    }

    if (informationForm) {
        _infoVector = meanOrInfo;
        _mean = infoOrMean;
        _precision = varianceOrPrecision;
        _variance = precisionOrVariance;
    } else {
        _mean = meanOrInfo;
        _infoVector = infoOrMean;
        _variance = varianceOrPrecision;
        _precision = precisionOrVariance;
    }

    _matrix = ArrayUtil.EMPTY_DOUBLE_ARRAY_ARRAY;
    _isInInformationForm = informationForm;
    _isDiagonal = true;
    _isDiagonalComputed = true;
    forgetNormalizationEnergy();
}

From source file:com.espertech.esper.epl.join.plan.NStreamOuterQueryPlanBuilder.java

private static QueryPlanNode buildPlanNode(int numStreams, int streamNo, String[] streamNames,
        QueryGraph queryGraph, OuterInnerDirectionalGraph outerInnerGraph, OuterJoinDesc[] outerJoinDescList,
        InnerJoinGraph innerJoinGraph, QueryPlanIndex[] indexSpecs, EventType[] typesPerStream,
        boolean[] ishistorical, DependencyGraph dependencyGraph,
        HistoricalStreamIndexList[] historicalStreamIndexLists, ExprEvaluatorContext exprEvaluatorContext)
        throws ExprValidationException {
    // For each stream build an array of substreams, considering required streams (inner joins) first
    // The order is relevant therefore preserving order via a LinkedHashMap.
    LinkedHashMap<Integer, int[]> substreamsPerStream = new LinkedHashMap<Integer, int[]>();
    boolean[] requiredPerStream = new boolean[numStreams];

    // Recursive populating the required (outer) and optional (inner) relationships
    // of this stream and the substream
    Set<Integer> completedStreams = new HashSet<Integer>();
    // keep track of tree path as only those stream events are always available to historical streams
    Stack<Integer> streamCallStack = new Stack<Integer>();
    streamCallStack.push(streamNo);/*from ww  w .ja v a2 s .co m*/

    // For all inner-joins, the algorithm is slightly different
    if (innerJoinGraph.isAllInnerJoin()) {
        Arrays.fill(requiredPerStream, true);
        recursiveBuildInnerJoin(streamNo, streamCallStack, queryGraph, completedStreams, substreamsPerStream,
                dependencyGraph);

        // compute a best chain to see if all streams are handled and add the remaining
        NStreamQueryPlanBuilder.BestChainResult bestChain = NStreamQueryPlanBuilder.computeBestPath(streamNo,
                queryGraph, dependencyGraph);
        addNotYetNavigated(streamNo, numStreams, substreamsPerStream, bestChain);
    } else {
        recursiveBuild(streamNo, streamCallStack, queryGraph, outerInnerGraph, innerJoinGraph, completedStreams,
                substreamsPerStream, requiredPerStream, dependencyGraph);
    }

    // verify the substreamsPerStream, all streams must exists and be linked
    verifyJoinedPerStream(streamNo, substreamsPerStream);

    // build list of instructions for lookup
    List<LookupInstructionPlan> lookupInstructions = buildLookupInstructions(streamNo, substreamsPerStream,
            requiredPerStream, streamNames, queryGraph, indexSpecs, typesPerStream, outerJoinDescList,
            ishistorical, historicalStreamIndexLists, exprEvaluatorContext);

    // build strategy tree for putting the result back together
    BaseAssemblyNode assemblyTopNode = AssemblyStrategyTreeBuilder.build(streamNo, substreamsPerStream,
            requiredPerStream);
    List<BaseAssemblyNode> assemblyInstructions = BaseAssemblyNode.getDescendentNodesBottomUp(assemblyTopNode);

    return new LookupInstructionQueryPlanNode(streamNo, streamNames[streamNo], numStreams, requiredPerStream,
            lookupInstructions, assemblyInstructions);
}

From source file:io.github.eternalbits.compactvd.CompactVD.java

@Override
public void update(DiskImage image, Object arg) {
    if (arg instanceof DiskImageProgress) {
        DiskImageProgress progress = (DiskImageProgress) arg;
        Arrays.fill(bar, '.');
        Arrays.fill(bar, 0, boundedInt(progress.value, bar.length), '#');
        String pb = String.format("\rProgress: [%3d%%] [%s]", boundedInt(progress.value, 100),
                String.valueOf(bar));
        if (!isCancelled() && !pb.equals(lastProgress)) {
            System.out.print(pb);
            lastProgress = pb;/*from   w  ww  .  ja  v a  2  s .  c  om*/
        }
        if (progress.done) {
            if (verbose || progress.task == task)
                System.out.println();
            lastProgress = null;
        }
    }
}

From source file:net.myrrix.common.collection.FastByIDFloatMap.java

public void clear() {
    numEntries = 0;
    numSlotsUsed = 0;
    Arrays.fill(keys, KEY_NULL);
    Arrays.fill(values, VALUE_NULL);
}