Example usage for java.util.stream IntStream range

List of usage examples for java.util.stream IntStream range

Introduction

In this page you can find the example usage for java.util.stream IntStream range.

Prototype

public static IntStream range(int startInclusive, int endExclusive) 

Source Link

Document

Returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1 .

Usage

From source file:com.cloudbees.jenkins.support.filter.FilteredWriterTest.java

@Issue("JENKINS-21670")
@Test//from w  ww . j  ava2  s .  c o  m
public void shouldModifyStream() throws Exception {
    final int nrLines = FilteredConstants.DEFAULT_DECODER_CAPACITY;
    String inputContents = IntStream.range(0, nrLines).mapToObj(i -> "ManagedNode" + i)
            .collect(joining(System.lineSeparator()));
    CharSequenceReader reader = new CharSequenceReader(inputContents);
    ContentFilter filter = s -> s.replace("ManagedNode", "Anonymous_");
    StringWriter output = new StringWriter();
    FilteredWriter writer = new FilteredWriter(output, filter);

    IOUtils.copy(reader, writer);
    writer.flush();
    String outputContents = output.toString();

    assertThat(outputContents).isNotEmpty();
    String[] lines = FilteredConstants.EOL.split(outputContents);
    assertThat(lines).allMatch(line -> !line.contains("ManagedNode") && line.startsWith("Anonymous_"))
            .hasSize(nrLines);
}

From source file:edu.washington.gs.skyline.model.quantification.LinearModel.java

public LinearModel(RealMatrix designMatrix, RealMatrix contrastValues) {
    this.designMatrix = designMatrix;
    this.contrastValues = contrastValues;
    qrDecomposition = new QRDecomposition(designMatrix);
    independentColumnIndices = IntStream.range(0, designMatrix.getColumnDimension()).toArray();
    RealMatrix matrixCrossproduct = computeMatrixCrossproduct(designMatrix, independentColumnIndices);
    matrixCrossproductInverse = new LUDecomposition(matrixCrossproduct).getSolver().getInverse();
}

From source file:nova.minecraft.wrapper.mc.forge.v1_11.wrapper.redstone.backward.BWRedstone.java

@Override
public int getOutputStrongPower() {
    BlockPos pos = new BlockPos(block().x(), block().y(), block().z());
    return IntStream.range(0, 6)
            .map(side -> mcWorld().getBlockState(pos).getStrongPower(mcWorld(), pos, EnumFacing.values()[side]))
            .max().orElse(0);/*from   w ww . j a va 2s.c o m*/
}

From source file:edu.vassar.cs.cmpu331.tvi.Main.java

private static void renumber(String filename) throws IOException {
    Path file = Paths.get(filename);
    if (Files.notExists(file)) {
        System.out.println("File not found: " + filename);
        return;//from   w  ww.j  a  v  a2  s. c o m
    }
    System.out.println("Renumbering " + filename);
    Function<String, String> trim = s -> {
        int i = s.indexOf(':');
        if (i > 0) {
            return s.substring(i + 1).trim();
        }
        return s.trim();
    };
    List<String> list = Files.lines(file).filter(line -> !line.startsWith("CODE")).map(line -> trim.apply(line))
            .collect(Collectors.toList());
    int size = list.size();
    PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file));
    //      PrintStream writer = System.out;
    writer.println("CODE");
    IntStream.range(0, size).forEach(index -> {
        String line = list.get(index);

        writer.println(index + ": " + line);
    });
    writer.close();
    System.out.println("Done.");
}

From source file:com.abixen.platform.module.chart.service.impl.AbstractDatabaseService.java

public List<String> getColumns(Connection connection, String tableName) {

    List<String> columns = new ArrayList<>();

    try {// w ww .  jav  a2s  .com
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName);
        ResultSetMetaData rsmd = rs.getMetaData();

        int columnCount = rsmd.getColumnCount();

        IntStream.range(1, columnCount + 1).forEach(i -> {
            try {
                columns.add(rsmd.getColumnName(i));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return columns;
}

From source file:org.apache.hadoop.hbase.client.TestZKAsyncRegistry.java

static void waitUntilAllReplicasHavingRegionLocation(TableName tbl) throws IOException {
    TEST_UTIL.waitFor(TEST_UTIL.getConfiguration().getLong("hbase.client.sync.wait.timeout.msec", 60000), 200,
            true, new ExplainingPredicate<IOException>() {
                @Override/*w  ww .j  a  v  a  2  s .  c  om*/
                public String explainFailure() throws IOException {
                    return TEST_UTIL.explainTableAvailability(tbl);
                }

                @Override
                public boolean evaluate() throws IOException {
                    AtomicBoolean ready = new AtomicBoolean(true);
                    try {
                        RegionLocations locs = REGISTRY.getMetaRegionLocation().get();
                        assertEquals(3, locs.getRegionLocations().length);
                        IntStream.range(0, 3).forEach(i -> {
                            HRegionLocation loc = locs.getRegionLocation(i);
                            if (loc == null) {
                                ready.set(false);
                            }
                        });
                    } catch (Exception e) {
                        ready.set(false);
                    }
                    return ready.get();
                }
            });
}

From source file:org.deeplearning4j.examples.cifar.NearestNeighbor.java

private static void processCifar10Images() throws IOException {
    Map<INDArray, Byte> trainingMap = readTrainingData();

    CifarLoader cifarLoader = new CifarLoader(false);
    final byte[] testImageData = IOUtils.toByteArray(cifarLoader.getInputStream());
    int imageLen = HEIGHT * WIDTH * CHANNELS;
    Random random = new Random(100);
    final int numberOfEpochs = 10;
    long timeTaken = 0;
    for (int epochIndex = 0; epochIndex < numberOfEpochs; epochIndex++) {
        log.info("Epoch " + epochIndex);
        final Instant start = Instant.now();
        float l1MatchCount = 0f, l2MatchCount = 0f;
        //Test Random 20 images
        final int numberOfImagesToTest = 20;
        for (int i = 0; i < numberOfImagesToTest; i++) {
            int imageIndex = random.nextInt(10000) * (imageLen + 1);
            final byte[] imageByteArray = Arrays.copyOfRange(testImageData, imageIndex + 1,
                    imageIndex + (imageLen + 1));
            final double[] imageDoubles = IntStream.range(0, imageByteArray.length)
                    .mapToDouble(idx -> imageByteArray[idx]).toArray();
            final INDArray testImage = abs(Nd4j.create(imageDoubles));
            final Byte testLabel = testImageData[imageIndex];
            l1MatchCount += trainingMap.entrySet().stream().min((o1, o2) -> {
                final double o1Difference = manhattanDistance(testImage, o1.getKey());
                final double o2Difference = manhattanDistance(testImage, o2.getKey());
                return (int) Math.abs(o1Difference - o2Difference);
            }).map(entry -> entry.getValue().equals(testLabel) ? 1 : 0).get();
            l2MatchCount += trainingMap.entrySet().stream().min((o1, o2) -> {
                final double o1Difference = euclideanDistance(testImage, o1.getKey());
                final double o2Difference = euclideanDistance(testImage, o2.getKey());
                return (int) Math.abs(o1Difference - o2Difference);
            }).map(entry -> entry.getValue().equals(testLabel) ? 1 : 0).get();
        }/*w  w  w.  jav  a 2s  .com*/
        log.info("Manhattan distance accuracy = " + (l1MatchCount / 20f) * 100f + "%");
        log.info("Euclidean distance accuracy = " + (l2MatchCount / 20f) * 100f + "%");
        timeTaken += MILLIS.between(start, Instant.now());
    }
    log.info("Average time = " + timeTaken / numberOfEpochs);
}

From source file:org.adriss.bucketpool.BucketPool.java

/**
 * @param config/*from  w  w  w  . j av  a  2 s.  co  m*/
 *            The configuration to use for this pool instance. The
 *            configuration is used by value. Subsequent changes to the
 *            configuration object will not be reflected in the pool.
 * @param abandonedConfig
 *            Configuration for abandoned object identification and removal.
 *            The configuration is used by value.
 * @throws Exception
 */
public BucketPool(BucketPoolConfig config, BucketPoolAbandonedConfig abandonedConfig) throws Exception {
    super(new BucketFactory(config), config, abandonedConfig);
    logger.info("Initializing {} buckets", config.getMinIdle());
    Bucket bucket[] = new Bucket[config.getMinIdle()];
    IntStream.range(0, config.getMinIdle()).forEach(x -> {
        try {
            bucket[x] = borrowObject();
            logger.debug("Bucket [{}] borrowed", bucket[x]);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    });
    IntStream.range(0, config.getMinIdle()).forEach(x -> {
        returnObject(bucket[x]);
        logger.debug("Bucket [{}] returned", bucket[x]);
    });
    logger.info("Initialized {} buckets", config.getMinIdle());
}

From source file:de.bund.bfr.knime.chart.ChartUtils.java

public static List<Color> createColorList(int n) {
    return IntStream.range(0, n).mapToObj(i -> COLORS.get(i % COLORS.size())).collect(Collectors.toList());
}

From source file:Callers.Caller.java

/**
 * Calls genotypes for every genotype//from w w w  .j  a v a2s. c om
 * @param reads Array of reads, dimensions are number of positions, number
 * of snps, 2 (i.e. counts for each allele)
 * @return The probability of each genotypes
 */
public double[][][] call(int[][][] reads) {
    double[][][] probs = new double[reads.length][][];

    Progress progress = ProgressFactory.get(reads.length);

    IntStream.range(0, reads.length).parallel().forEach(i -> {
        int[][] d = reads[i];
        double[][] p = new double[d.length][];
        probs[i] = p;
        IntStream.range(0, d.length).forEach(j -> p[j] = callSingle(reads[i][j], i, j));
        progress.done();
    });

    return probs;
}