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.intuit.wasabi.tests.service.assignment.DailyAssignmentCountsTest.java

/**
 * Asserts that all assignment ratios for each day are given and correct: on the first and last day 0 percent (= 0.0),
 * on the day in the middle 100 percent (= 1.0).
 *
 * @param experiments the expected experiments
 * @param result      the result/*w w  w .  jav  a 2 s. c om*/
 */
private void assertAssignmentRatios(List<Experiment> experiments, Map<String, List<?>> result) {
    Assert.assertTrue(result.containsKey("assignmentRatios"), "Expected 'assignmentRatios' key.");

    List<Float> ones = IntStream.range(0, experiments.size()).mapToObj(i -> 1f).collect(Collectors.toList());
    List<Float> zeros = IntStream.range(0, experiments.size()).mapToObj(i -> 0f).collect(Collectors.toList());

    @SuppressWarnings("unchecked")
    List<Map<String, ?>> assignmentRatios = (List<Map<String, ?>>) result.get("assignmentRatios");
    List<Map<String, ?>> expectedAssignmentRatios = IntStream.range(0, 3).mapToObj(startDate::plusDays)
            .map(date -> {
                Map<String, Object> m = new HashMap<>(2);
                m.put("date", TestUtils.formatDateForUI(date));
                m.put("values", zeros);
                if (date.isAfter(startDate.plusHours(1)) && date.isBefore(endDate.minusHours(1))) {
                    m.put("values", ones);
                }
                return m;
            }).collect(Collectors.toList());
    Assert.assertEqualsNoOrder(assignmentRatios.toArray(), expectedAssignmentRatios.toArray(),
            "Not all assignment ratios are correct.");
}

From source file:com.facebook.buck.android.ResourcesFilter.java

private ImmutableList<Path> getRawResDirectories() {
    Path resDestinationBasePath = BuildTargetPaths.getScratchPath(getProjectFilesystem(), getBuildTarget(),
            "__filtered__%s__");

    return IntStream.range(0, resDirectories.size())
            .mapToObj(count -> resDestinationBasePath.resolve(String.valueOf(count)))
            .collect(ImmutableList.toImmutableList());
}

From source file:io.mandrel.metrics.impl.MongoMetricsRepository.java

public void prepareMinutes(LocalDateTime keytime) {
    List<? extends WriteModel<Document>> requests = Arrays
            .asList(MetricKeys.globalTotalSize(), MetricKeys.globalNbPages()).stream().map(el -> {
                Document document = new Document();
                document.append("type", el).append("timestamp_hour", keytime);
                document.append("values", IntStream.range(0, 60).collect(Document::new,
                        (doc, val) -> doc.put(Integer.toString(val), Long.valueOf(0)), Document::putAll));
                return document;
            })/*  w  ww  .j  a v a2s  . c o  m*/
            .map(doc -> new UpdateOneModel<Document>(
                    Filters.and(Filters.eq("type", doc.getString("type")),
                            Filters.eq("timestamp_hour", keytime)),
                    new Document("$set", doc), new UpdateOptions().upsert(true)))
            .collect(Collectors.toList());

    timeseries.bulkWrite(requests);
}

From source file:org.lightjason.agentspeak.common.CPath.java

@Override
public final synchronized IPath toLower() {
    IntStream.range(0, m_path.size()).boxed().parallel()
            .forEach(i -> m_path.set(i, m_path.get(i).toLowerCase()));
    return this;
}

From source file:com.vsthost.rnd.commons.math.ext.linear.DMatrixUtils.java

/**
 * Get the order of the elements in descending or ascending order.
 *
 * @param values A vector of double values.
 * @param descending Flag indicating if we go descending or not.
 * @return A vector of indices sorted in the provided order.
 *///from  w  w w .  j a va2  s .c  o m
public static int[] getOrder(double[] values, boolean descending) {
    return DMatrixUtils.getOrder(values, IntStream.range(0, values.length).toArray(), descending);
}

From source file:no.ssb.jsonstat.v2.deser.DimensionDeserializer.java

private ImmutableMap<String, String> parseIndexAsArray(JsonParser p) throws IOException {
    ImmutableMap<String, String> index;

    List<String> listIndex = p.readValueAs(INDEX_LIST);
    index = IntStream.range(0, listIndex.size()).boxed()
            .collect(toImmutableMap(listIndex::get, Object::toString));
    return index;
}

From source file:org.lightjason.agentspeak.action.builtin.TestCActionCollectionList.java

/**
 * test remove action/*from w  w w.  jav a2 s.c o  m*/
 */
@Test
public final void remove() {
    final Random l_random = new Random();

    final List<?> l_elements = IntStream.range(0, l_random.nextInt(100) + 1).map(i -> l_random.nextInt())
            .boxed().collect(Collectors.toList());
    final List<?> l_list = new ArrayList<>(l_elements);
    final List<Integer> l_index = new ArrayList<>(IntStream.range(0, l_list.size() / 3)
            .map(i -> l_random.nextInt(l_list.size())).boxed().collect(Collectors.toSet()));

    final int l_startsize = l_list.size();
    final List<ITerm> l_return = new ArrayList<>();

    new CRemove().execute(false, IContext.EMPTYPLAN,
            Stream.concat(Stream.of(l_list), l_index.stream()).map(CRawTerm::from).collect(Collectors.toList()),
            l_return);

    Assert.assertEquals(l_startsize, l_list.size() + l_index.size());
    Assert.assertTrue(l_index.parallelStream().map(l_elements::get)
            .allMatch(i -> l_return.parallelStream().map(ITerm::<Number>raw).anyMatch(j -> j.equals(i))));
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.ScriptEnginesTest.java

@Test
public void shouldFailUntilImportExecutes() throws Exception {
    final ScriptEngines engines = new ScriptEngines(se -> {
    });//from  w  ww .j  ava  2  s . c o  m
    engines.reload("gremlin-groovy", Collections.<String>emptySet(), Collections.<String>emptySet(),
            Collections.emptyMap());

    final Set<String> imports = new HashSet<String>() {
        {
            add("import java.awt.Color");
        }
    };

    final AtomicInteger successes = new AtomicInteger(0);
    final AtomicInteger failures = new AtomicInteger(0);

    final Thread threadImport = new Thread(() -> {
        engines.addImports(imports);
    });

    // issue 1000 scripts in one thread using a class that isn't imported.  this will result in failure.
    // while that thread is running start a new thread that issues an addImports to include that class.
    // this should block further evals in the first thread until the import is complete at which point
    // evals in the first thread will resume and start to succeed
    final Thread threadEvalAndTriggerImport = new Thread(() -> IntStream.range(0, 1000).forEach(i -> {
        try {
            engines.eval("Color.BLACK", new SimpleBindings(), "gremlin-groovy");
            successes.incrementAndGet();
        } catch (Exception ex) {
            if (failures.incrementAndGet() == 500)
                threadImport.start();
            Thread.yield();
        }
    }));

    threadEvalAndTriggerImport.start();

    threadEvalAndTriggerImport.join();
    threadImport.join();

    assertTrue("Success: " + successes.intValue() + " - Failures: " + failures.intValue(),
            successes.intValue() > 0);
    assertTrue("Success: " + successes.intValue() + " - Failures: " + failures.intValue(),
            failures.intValue() >= 500);

    engines.close();
}

From source file:de.flashpixx.rrd_antlr4.antlr.CASTVisitorPCRE.java

/**
 * filters the pair list of string or quantifier
 *
 * @param p_start start index/*from  ww  w .j  a  v a  2s.co  m*/
 * @param p_list list
 * @return end position of a string or quantifier element, -1 on non found
 */
private int filter(final int p_start, final List<Pair<?, String>> p_list) {
    return IntStream.range(p_start, p_list.size()).boxed()
            .filter(i -> (p_list.get(i).getLeft() instanceof String) || (!p_list.get(i).getRight().isEmpty()))
            .findFirst().orElse(-1);
}

From source file:com.uber.hoodie.func.TestBoundedInMemoryQueue.java

/**
 * Test to ensure that we are reading all records from queue iterator when we have multiple producers
 *//*from  w w w  . j a  v  a 2 s. c o m*/
@SuppressWarnings("unchecked")
@Test(timeout = 60000)
public void testCompositeProducerRecordReading() throws Exception {
    final int numRecords = 1000;
    final int numProducers = 40;
    final List<List<HoodieRecord>> recs = new ArrayList<>();

    final BoundedInMemoryQueue<HoodieRecord, Tuple2<HoodieRecord, Optional<IndexedRecord>>> queue = new BoundedInMemoryQueue(
            FileUtils.ONE_KB, getTransformFunction(HoodieTestDataGenerator.avroSchema));

    // Record Key to <Producer Index, Rec Index within a producer>
    Map<String, Tuple2<Integer, Integer>> keyToProducerAndIndexMap = new HashMap<>();

    for (int i = 0; i < numProducers; i++) {
        List<HoodieRecord> pRecs = hoodieTestDataGenerator.generateInserts(commitTime, numRecords);
        int j = 0;
        for (HoodieRecord r : pRecs) {
            Assert.assertTrue(!keyToProducerAndIndexMap.containsKey(r.getRecordKey()));
            keyToProducerAndIndexMap.put(r.getRecordKey(), new Tuple2<>(i, j));
            j++;
        }
        recs.add(pRecs);
    }

    List<BoundedInMemoryQueueProducer<HoodieRecord>> producers = new ArrayList<>();
    for (int i = 0; i < recs.size(); i++) {
        final List<HoodieRecord> r = recs.get(i);
        // Alternate between pull and push based iterators
        if (i % 2 == 0) {
            producers.add(new IteratorBasedQueueProducer<>(r.iterator()));
        } else {
            producers.add(new FunctionBasedQueueProducer<HoodieRecord>((buf) -> {
                Iterator<HoodieRecord> itr = r.iterator();
                while (itr.hasNext()) {
                    try {
                        buf.insertRecord(itr.next());
                    } catch (Exception e) {
                        throw new HoodieException(e);
                    }
                }
                return true;
            }));
        }
    }

    final List<Future<Boolean>> futureList = producers.stream().map(producer -> {
        return executorService.submit(() -> {
            producer.produce(queue);
            return true;
        });
    }).collect(Collectors.toList());

    // Close queue
    Future<Boolean> closeFuture = executorService.submit(() -> {
        try {
            for (Future f : futureList) {
                f.get();
            }
            queue.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    });

    // Used to ensure that consumer sees the records generated by a single producer in FIFO order
    Map<Integer, Integer> lastSeenMap = IntStream.range(0, numProducers).boxed()
            .collect(Collectors.toMap(Function.identity(), x -> -1));
    Map<Integer, Integer> countMap = IntStream.range(0, numProducers).boxed()
            .collect(Collectors.toMap(Function.identity(), x -> 0));

    // Read recs and ensure we have covered all producer recs.
    while (queue.iterator().hasNext()) {
        final Tuple2<HoodieRecord, Optional<IndexedRecord>> payload = queue.iterator().next();
        final HoodieRecord rec = payload._1();
        Tuple2<Integer, Integer> producerPos = keyToProducerAndIndexMap.get(rec.getRecordKey());
        Integer lastSeenPos = lastSeenMap.get(producerPos._1());
        countMap.put(producerPos._1(), countMap.get(producerPos._1()) + 1);
        lastSeenMap.put(producerPos._1(), lastSeenPos + 1);
        // Ensure we are seeing the next record generated
        Assert.assertEquals(lastSeenPos + 1, producerPos._2().intValue());
    }

    for (int i = 0; i < numProducers; i++) {
        // Ensure we have seen all the records for each producers
        Assert.assertEquals(Integer.valueOf(numRecords), countMap.get(i));
    }

    //Ensure Close future is done
    closeFuture.get();
}