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:org.apache.bookkeeper.common.conf.ConfigDef.java

private void writeNSharps(PrintStream stream, int num) {
    IntStream.range(0, num).forEach(ignored -> stream.print("#"));
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

private void fillMap(NodeList sourceNodeList, Map<String, String> destinationMap) {

    if (sourceNodeList.getLength() == 0) {
        destinationMap.clear();// www.  j  av  a 2 s  .c om
    } else {
        IntStream.range(0, sourceNodeList.getLength()).mapToObj(sourceNodeList::item).forEach(node -> {
            try {
                destinationMap.put(XMLConfig.get(node, "@name"), XMLConfig.get(node, "@value"));
            } catch (Exception e) {
                logger.error("Fail to read configuration", e);
            }
        });
    }
}

From source file:kishida.cnn.layers.FullyConnect.java

@Override
public void prepareBatch() {
    float momentam = parent.getMomentam();
    IntStream.range(0, weightDelta.length).forEach(i -> weightDelta[i] = weightDelta[i] * momentam);
    IntStream.range(0, biasDelta.length).parallel().forEach(i -> biasDelta[i] = biasDelta[i] * momentam);
}

From source file:com.abixen.platform.service.businessintelligence.multivisualisation.application.service.JsonFilterService.java

private Map<String, String> getColumnTypeMapping(ResultSetMetaData rsmd) throws SQLException {
    int columnCount = rsmd.getColumnCount();
    Map<String, String> columnTypeMapping = new HashMap<>();

    IntStream.range(1, columnCount + 1).forEach(i -> {
        try {//from ww  w  .j a  v a 2  s.  co  m
            String columnTypeName = rsmd.getColumnTypeName(i);
            if ("BIGINT".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            if ("VARCHAR".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "STRING";
            }
            if ("FLOAT8".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "DOUBLE";
            }
            if ("INT8".equalsIgnoreCase(columnTypeName)) {
                columnTypeName = "INTEGER";
            }
            columnTypeMapping.put(rsmd.getColumnName(i).toUpperCase(), columnTypeName.toUpperCase());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    return columnTypeMapping;
}

From source file:Imputers.KnniLDProb.java

/**
 * Performs imputation using an already calculated similarity matrix. Used
 * for optimizing parameters as the similarity matrix only has to be calculated
 * once.// w w w  .  j a va 2s .co m
 * 
 * The author is aware this description is a bit light on detail.  Please
 * contact the author if further details are needed.
 * @param original Genotypes called based purely on read counts
 * @param callprobs Called genotype probabilities
 * @param list List of masked genotypes and their masked genotype
 * @param sim Similarity matrix
 * @return List of imputed probabilities
 */
protected List<SingleGenotypeProbability> impute(byte[][] original, List<SingleGenotypeProbability> callprobs,
        List<SingleGenotypeMasked> list, int[][] sim) {
    if (!SingleGenotypePosition.samePositions(callprobs, list)) {
        //Needs a proper error
        throw new ProgrammerException();
    }
    Progress progress = ProgressFactory.get(list.size());
    return IntStream.range(0, list.size()).mapToObj(i -> {
        SingleGenotypeMasked sgr = list.get(i);
        SingleGenotypeProbability sgc = callprobs.get(i);
        SingleGenotypeProbability sgp;
        if (Arrays.stream(sgr.getMasked()).sum() < knownDepth) {
            sgp = new SingleGenotypeProbability(sgr.getSample(), sgr.getSNP(),
                    imputeSingle(original, sgr.getSample(), sgr.getSNP(), true, sim));
        } else {
            sgp = new SingleGenotypeProbability(sgr.getSample(), sgr.getSNP(), sgc.getProb());
        }
        progress.done();
        return sgp;
    }).collect(Collectors.toCollection(ArrayList::new));
}

From source file:io.pravega.controller.store.stream.PersistentStreamBase.java

private CompletableFuture<Void> createNewSegmentTable(final StreamConfiguration configuration, long timestamp) {
    final int numSegments = configuration.getScalingPolicy().getMinNumSegments();
    final double keyRangeChunk = 1.0 / numSegments;

    final int startingSegmentNumber = 0;
    final List<AbstractMap.SimpleEntry<Double, Double>> newRanges = IntStream.range(0, numSegments).boxed()
            .map(x -> new AbstractMap.SimpleEntry<>(x * keyRangeChunk, (x + 1) * keyRangeChunk))
            .collect(Collectors.toList());

    final byte[] segmentTable = TableHelper.updateSegmentTable(startingSegmentNumber, new byte[0], newRanges,
            timestamp);/*from   w  w  w . j a  va  2 s .  c  o m*/

    return createSegmentTableIfAbsent(new Data<>(segmentTable, null));
}

From source file:com.simiacryptus.mindseye.lang.Tensor.java

/**
 * From json tensor.// www .  j  a  v  a  2s  .co  m
 *
 * @param json      the json
 * @param resources the resources
 * @return the tensor
 */
@Nullable
public static Tensor fromJson(@Nullable final JsonElement json, @Nullable Map<CharSequence, byte[]> resources) {
    if (null == json)
        return null;
    if (json.isJsonArray()) {
        final JsonArray array = json.getAsJsonArray();
        final int size = array.size();
        if (array.get(0).isJsonPrimitive()) {
            final double[] doubles = IntStream.range(0, size).mapToObj(i -> {
                return array.get(i);
            }).mapToDouble(element -> {
                return element.getAsDouble();
            }).toArray();
            @Nonnull
            Tensor tensor = new Tensor(doubles);
            assert tensor.isValid();
            return tensor;
        } else {
            final List<Tensor> elements = IntStream.range(0, size).mapToObj(i -> {
                return array.get(i);
            }).map(element -> {
                return Tensor.fromJson(element, resources);
            }).collect(Collectors.toList());
            @Nonnull
            final int[] dimensions = elements.get(0).getDimensions();
            if (!elements.stream().allMatch(t -> Arrays.equals(dimensions, t.getDimensions()))) {
                throw new IllegalArgumentException();
            }
            @Nonnull
            final int[] newDdimensions = Arrays.copyOf(dimensions, dimensions.length + 1);
            newDdimensions[dimensions.length] = size;
            @Nonnull
            final Tensor tensor = new Tensor(newDdimensions);
            @Nullable
            final double[] data = tensor.getData();
            for (int i = 0; i < size; i++) {
                @Nullable
                final double[] e = elements.get(i).getData();
                System.arraycopy(e, 0, data, i * e.length, e.length);
            }
            for (@Nonnull
            Tensor t : elements) {
                t.freeRef();
            }
            assert tensor.isValid();
            return tensor;
        }
    } else if (json.isJsonObject()) {
        JsonObject jsonObject = json.getAsJsonObject();
        @Nonnull
        int[] dims = fromJsonArray(jsonObject.getAsJsonArray("length"));
        @Nonnull
        Tensor tensor = new Tensor(dims);
        SerialPrecision precision = SerialPrecision
                .valueOf(jsonObject.getAsJsonPrimitive("precision").getAsString());
        JsonElement base64 = jsonObject.get("base64");
        if (null == base64) {
            if (null == resources)
                throw new IllegalArgumentException("No Data Resources");
            CharSequence resourceId = jsonObject.getAsJsonPrimitive("resource").getAsString();
            tensor.setBytes(resources.get(resourceId), precision);
        } else {
            tensor.setBytes(Base64.getDecoder().decode(base64.getAsString()), precision);
        }
        assert tensor.isValid();
        JsonElement id = jsonObject.get("id");
        if (null != id) {
            tensor.setId(UUID.fromString(id.getAsString()));
        }
        return tensor;
    } else {
        @Nonnull
        Tensor tensor = new Tensor(json.getAsJsonPrimitive().getAsDouble());
        assert tensor.isValid();
        return tensor;
    }
}

From source file:com.github.lukaszbudnik.dqueue.QueueClientPerformanceTest.java

@Test
public void doIt5Filters() throws ExecutionException, InterruptedException {

    byte[] data = new byte[2045];
    Random r = new Random();
    r.nextBytes(data);/*from w  ww  .  j ava 2  s. co m*/
    ByteBuffer buffer = ByteBuffer.wrap(data);

    Map<String, String> filters = ImmutableMap.of(
            // f1
            "f1", Long.toHexString(r.nextLong()),
            // f2
            "f2", Long.toHexString(r.nextLong()),
            // f3
            "f3", Long.toHexString(r.nextLong()),
            // f4
            "f4", Long.toHexString(r.nextLong()),
            // f5
            "f5", Long.toHexString(r.nextLong()));

    IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> {
        UUID startTime = UUIDs.timeBased();
        Future<UUID> id = queueClient.publish(new Item(startTime, buffer, filters));
        try {
            Assert.assertEquals(startTime, id.get());
        } catch (Exception e) {
            fail(e.getMessage());
        }
    });

    IntStream.range(0, NUMBER_OF_ITERATIONS).forEach((i) -> {
        Future<Optional<Item>> itemFuture = queueClient.consume(filters);

        Optional<Item> item = null;
        try {
            item = itemFuture.get();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        assertTrue(item.isPresent());
    });

}

From source file:net.demilich.metastone.bahaviour.ModifiedMCTS.MCTSCritique.java

@Override
public synchronized GameCritique trainBasedOnActor(Behaviour a, GameContext startingTurn, Player p) {
    f = new FeatureCollector(startingTurn, p);
    if (caffe_net != null) {
        return this;
    }//  ww  w  .j a v  a  2  s .c  o m
    Random generator = new Random();

    f = new FeatureCollector(startingTurn, p);
    f.printFeatures(startingTurn, p);

    playerID = p.getId();
    startingTurn = startingTurn.clone();
    startingTurn.getPlayer1().setBehaviour(a.clone());
    startingTurn.getPlayer2().setBehaviour(a.clone());

    ArrayList<double[]> gameFeatures = new ArrayList<>();
    ArrayList<Double> gameLabels = new ArrayList<>();
    ArrayList<Double> gameWeights = new ArrayList<>();

    ArrayList<double[]> gameFeaturesTesting = new ArrayList<>();
    ArrayList<Double> gameLabelsTesting = new ArrayList<>();
    ArrayList<Double> gameWeightsTesting = new ArrayList<>();

    ArrayList<GameContext> testingSetContexts = new ArrayList<>();
    ArrayList<Double> testingSetReTests = new ArrayList<>();

    // 
    //System.err.println("on sample " + i);
    //GameContext simulation = startingTurn.clone();
    final GameContext simulation = startingTurn.clone();

    behaviours = new ExperimentalMCTS[samples * 2];
    IntStream.range(0, samples).parallel().forEach((int i) -> {
        doPlay(RandomizeSimulation(simulation.clone()), i, f.clone());
    });
    System.err.println("game playing is done!");
    //System.exit(0);
    for (int i = 0; i < samples; i++) {
        boolean testing = !(i < samples - samples / 10);
        if (!testing) {
            gatherSamplesFrom(behaviours[i * 2], gameFeatures, gameLabels, gameWeights, null, 1);
            gatherSamplesFrom(behaviours[i * 2 + 1], gameFeatures, gameLabels, gameWeights, null, 0);
        } else {
            gatherSamplesFrom(behaviours[i * 2], gameFeaturesTesting, gameLabelsTesting, gameWeightsTesting,
                    testingSetReTests, 1);
            gatherSamplesFrom(behaviours[i * 2 + 1], gameFeaturesTesting, gameLabelsTesting, gameWeightsTesting,
                    testingSetReTests, 0);
        }
    }
    System.err.println("total weight: " + getSum(gameWeights));
    System.err.println("total ones: " + getNumOnes(gameWeights));
    double[][] trainingFeatures = new double[gameFeatures.size()][gameFeatures.get(0).length];
    double[][] trainingLabels = new double[gameLabels.size()][1];
    double[][] trainingWeights = new double[gameLabels.size()][1];
    for (int i = 0; i < trainingFeatures.length; i++) {
        trainingFeatures[i] = gameFeatures.get(i);
        double[] arr1 = new double[1];
        arr1[0] = gameLabels.get(i);
        trainingLabels[i] = arr1;
        arr1 = new double[1];
        arr1[0] = gameWeights.get(i);
        trainingWeights[i] = arr1;
    }
    sendCaffeData(trainingFeatures, trainingLabels, trainingWeights, "HearthstoneTrainingALLSTUFF.h5", false,
            false);//(int) (gameFeatures.size() * 1.6),true);

    // train.iteration(1000);
    double[][] testingFeatures = new double[gameFeaturesTesting.size()][gameFeaturesTesting.get(0).length];
    double[][] testingLabels = new double[gameLabelsTesting.size()][1];
    double[][] testingWeights = new double[gameLabelsTesting.size()][1];
    for (int i = 0; i < testingFeatures.length; i++) {
        testingFeatures[i] = gameFeaturesTesting.get(i);
        double[] arr1 = new double[1];
        arr1[0] = gameLabelsTesting.get(i);
        testingLabels[i] = arr1;
        arr1 = new double[1];
        arr1[0] = gameWeightsTesting.get(i);
        testingWeights[i] = arr1;

    }
    sendCaffeData(testingFeatures, testingLabels, testingWeights, "HearthstoneTestingALLSTUFF.h5", true, false);

    System.err.println("testing err if just 0's" + this.getErrorIfZero(testingLabels));
    System.err.println("ideal testing err: "
            + this.getIdealTestingError(testingLabels, testingSetContexts, testingSetReTests));

    return this;
}

From source file:com.twosigma.beakerx.kernel.magic.command.functionality.TimeMagicCommand.java

protected MagicCommandOutput timeIt(TimeItOption timeItOption, String codeToExecute, Message message,
        int executionCount, boolean showResult) {
    String output = "%s  %s per loop (mean  std. dev. of %d run, %d loop each)";

    if (timeItOption.getNumber() < 0) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
                "Number of execution must be bigger then 0");
    }/*from ww  w.ja v  a2  s.  c o  m*/
    int number = timeItOption.getNumber() == 0 ? getBestNumber(codeToExecute, showResult, message)
            : timeItOption.getNumber();

    if (timeItOption.getRepeat() == 0) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Repeat value must be bigger then 0");
    }

    SimpleEvaluationObject seo = createSimpleEvaluationObject(codeToExecute, kernel, message, executionCount);
    seo.noResult();

    TryResult either = kernel.executeCode(codeToExecute, seo);

    try {

        if (either.isError()) {
            return new MagicCommandOutput(MagicCommandOutput.Status.ERROR, "Please correct your statement");
        }

        List<Long> allRuns = new ArrayList<>();
        List<Long> timings = new ArrayList<>();

        CompletableFuture<Boolean> isReady = new CompletableFuture<>();

        IntStream.range(0, timeItOption.getRepeat()).forEach(repeatIter -> {
            IntStream.range(0, number).forEach(numberIter -> {
                SimpleEvaluationObject seo2 = createSimpleEvaluationObject(codeToExecute, kernel, message,
                        executionCount);
                seo2.noResult();
                Long startOfEvaluationInNanoseconds = System.nanoTime();
                TryResult result = kernel.executeCode(codeToExecute, seo2);
                Long endOfEvaluationInNanoseconds = System.nanoTime();
                allRuns.add(endOfEvaluationInNanoseconds - startOfEvaluationInNanoseconds);
                if (repeatIter == timeItOption.getRepeat() - 1 && numberIter == number - 1) {
                    isReady.complete(true);
                }
            });
        });

        if (isReady.get()) {
            allRuns.forEach(run -> timings.add(run / number));

            //calculating average
            long average = timings.stream().reduce((aLong, aLong2) -> aLong + aLong2).orElse(0L)
                    / timings.size();
            double stdev = Math.pow(
                    timings.stream().map(currentValue -> Math.pow(currentValue - average, 2))
                            .reduce((aDouble, aDouble2) -> aDouble + aDouble2).orElse(0.0) / timings.size(),
                    0.5);

            if (timeItOption.getQuietMode()) {
                output = "";
            } else {
                output = String.format(output, format(average), format((long) stdev), timeItOption.getRepeat(),
                        number);
            }

            return new MagicCommandOutput(MagicCommandOutput.Status.OK, output);
        }
    } catch (InterruptedException | ExecutionException e) {
        return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
                "There occurs problem with " + e.getMessage());
    }
    return new MagicCommandOutput(MagicCommandOutput.Status.ERROR,
            "There occurs problem with timeIt operations");
}