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.hadoop.hbase.client.TestAsyncTable.java

@Test
public void testCheckAndMutate() throws InterruptedException, ExecutionException {
    AsyncTableBase table = getTable.get();
    int count = 10;
    CountDownLatch putLatch = new CountDownLatch(count + 1);
    table.put(new Put(row).addColumn(FAMILY, QUALIFIER, VALUE)).thenRun(() -> putLatch.countDown());
    IntStream.range(0, count)
            .forEach(i -> table.put(new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), VALUE))
                    .thenRun(() -> putLatch.countDown()));
    putLatch.await();//from   w w  w. j a  v a2 s .c o m

    AtomicInteger successCount = new AtomicInteger(0);
    AtomicInteger successIndex = new AtomicInteger(-1);
    CountDownLatch mutateLatch = new CountDownLatch(count);
    IntStream.range(0, count).forEach(i -> {
        RowMutations mutation = new RowMutations(row);
        try {
            mutation.add(new Delete(row).addColumn(FAMILY, QUALIFIER));
            mutation.add(new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), concat(VALUE, i)));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        table.checkAndMutate(row, FAMILY, QUALIFIER, VALUE, mutation).thenAccept(x -> {
            if (x) {
                successCount.incrementAndGet();
                successIndex.set(i);
            }
            mutateLatch.countDown();
        });
    });
    mutateLatch.await();
    assertEquals(1, successCount.get());
    Result result = table.get(new Get(row)).get();
    IntStream.range(0, count).forEach(i -> {
        if (i == successIndex.get()) {
            assertArrayEquals(concat(VALUE, i), result.getValue(FAMILY, concat(QUALIFIER, i)));
        } else {
            assertArrayEquals(VALUE, result.getValue(FAMILY, concat(QUALIFIER, i)));
        }
    });
}

From source file:com.streamsets.pipeline.stage.bigquery.destination.BigQueryTarget.java

/**
 * Convert the sdc Field to an object for row content
 *//*from  ww w  .j a  v  a2  s.  c  o m*/
private Object getValueFromField(String fieldPath, Field field) {
    LOG.trace("Visiting Field Path '{}' of type '{}'", fieldPath, field.getType());
    switch (field.getType()) {
    case LIST:
        //REPEATED
        List<Field> listField = field.getValueAsList();
        //Convert the list to map with indices as key and Field as value (Map<Integer, Field>)
        Map<Integer, Field> fields = IntStream.range(0, listField.size()).boxed()
                .collect(Collectors.toMap(Function.identity(), listField::get));
        //filter map to remove fields with null value
        fields = fields.entrySet().stream().filter(e -> e.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        //now use the map index to generate field path and generate object for big query write
        return fields.entrySet().stream()
                .map(e -> getValueFromField(fieldPath + "[" + e.getKey() + "]", e.getValue()))
                .collect(Collectors.toList());
    case MAP:
    case LIST_MAP:
        //RECORD
        return field.getValueAsMap().entrySet().stream().filter(me -> me.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey,
                        e -> getValueFromField(fieldPath + "/" + e.getKey(), e.getValue())));
    case DATE:
        return dateFormat.format(field.getValueAsDate());
    case TIME:
        return timeFormat.format(field.getValueAsTime());
    case DATETIME:
        return dateTimeFormat.format(field.getValueAsDatetime());
    case BYTE_ARRAY:
        return Base64.getEncoder().encodeToString(field.getValueAsByteArray());
    case DECIMAL:
    case BYTE:
    case CHAR:
    case FILE_REF:
        throw new IllegalArgumentException(
                Utils.format(Errors.BIGQUERY_12.getMessage(), fieldPath, field.getType()));
    default:
        //Boolean -> Map to Boolean in big query
        //Float, Double -> Map to Float in big query
        //String -> maps to String in big query
        //Short, Integer, Long -> Map to integer in big query
        return field.getValue();
    }
}

From source file:com.wrmsr.neurosis.util.Configs.java

protected static Map<Sigil, String> flattenList(List<?> list) {
    return IntStream.range(0, list.size()).boxed()
            .flatMap(i -> flattenValues(list.get(i)).entrySet().stream()
                    .map(e -> ImmutablePair.of(new ListItemSigil(i, e.getKey()), e.getValue())))
            .collect(ImmutableCollectors.toImmutableMap(e -> e.getKey(), e -> e.getValue()));
}

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

/**
 * test flatconcat action/*from ww  w  .  ja v a2 s  .  co  m*/
 */
@Test
public final void flatconcat() {
    final Random l_random = new Random();

    final List<ITerm> l_return = new ArrayList<>();
    final List<?> l_list = IntStream.range(0, l_random.nextInt(100) + 1)
            .mapToObj(i -> RandomStringUtils.random(l_random.nextInt(100) + 1)).collect(Collectors.toList());

    new CFlatConcat().execute(false, IContext.EMPTYPLAN,
            l_list.stream().map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 1);
    Assert.assertArrayEquals(l_return.get(0).<List<?>>raw().toArray(), l_list.toArray());
}

From source file:at.tfr.securefs.process.ProcessFilesTest.java

private void generateFileHierarchy(Path root, int startIdx, int maxIdx, CrypterProvider cp, BigInteger secret)
        throws Exception {
    IntStream.range(startIdx, maxIdx).forEach((dirIdx) -> {
        try {/*from   w w  w . jav  a  2  s  .  c  o  m*/
            Path subDir = Files.createDirectories(root.resolve(SUBDIR_PFX + dirIdx));
            IntStream.range(startIdx, MAX_FILE_COUNT).forEach((fIdx) -> {
                try {
                    String name = FILE_PFX + dirIdx + "_" + fIdx + FILE_END;
                    Path filePath = subDir.resolve(name);
                    try (OutputStream os = cp.getEncrypter(filePath, secret)) {
                        os.write(name.getBytes());
                    }
                    try (InputStream is = cp.getDecrypter(filePath, secret)) {
                        byte[] content = name.getBytes();
                        IOUtils.readFully(is, content);
                        Assert.assertTrue("failed to correctly generate file hierarchy",
                                Arrays.equals(content, name.getBytes()));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
            if (startIdx < maxIdx) {
                generateFileHierarchy(subDir, startIdx + 1, maxIdx, cp, secret);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:oct.analysis.application.comp.EZWorker.java

@Override
protected EZEdgeCoord doInBackground() throws Exception {
    int foveaCenterXPosition = analysisManager.getFoveaCenterXPosition();
    /*/* w w  w.j  a v  a  2 s .  c om*/
     first get a sharpened version of the OCT and use that to obtain the segmentation
     of the Bruch's membrane. Use a Loess interpolation algorithm to smooth 
     out imperfetions in the segmentation line.
     */
    UnivariateInterpolator interpolator = new LoessInterpolator(0.1, 0);
    ArrayList<Point> rawBrmPoints = new ArrayList<>(analysisManager
            .getSegmentation(new SharpenOperation(15, 0.5F)).getSegment(Segmentation.BrM_SEGMENT));
    double[][] brmSeg = Util.getXYArraysFromPoints(rawBrmPoints);
    UnivariateFunction brmInterp = interpolator.interpolate(brmSeg[0], brmSeg[1]);
    BufferedImage sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F);
    setProgress(10);
    /*
     Starting from the identified location of the fovea search northward in 
     the image until the most northern pixels northward (in a 3x3 matrix of 
     pixels arround the the search point (X,Y) ) are black (ie. the search
     matrix is has found that the search point isn't totally surrounded by
     white pixels). Then a recursive search algorithm determines if the 
     black area signifies the seperation between bands or simply represents
     a closed (a black blob entirely surrounded by white pixels) black band.
     It will continue searching northward in the image until it can find an 
     open region of all blak pixels. Once this is found it will find the contour
     of the edge between the black and white pixels along the width of the image.
     */
    int searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)) + 1;
    do {
        searchY--;
    } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
            || !isContrastPoint(foveaCenterXPosition, searchY, sharpOCT));
    LinkedList<Point> contour = new LinkedList<>();
    Point startPoint = new Point(foveaCenterXPosition, searchY);
    //find contour by searching for white pixel boundary to te right of the fovea
    contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour,
            sharpOCT, 0));
    //search until open black area found (ie. if the search algorithm arrives back at
    //the starting pixel keep moving north to next black area to search)
    while (contour.get(0).equals(startPoint)) {
        contour = new LinkedList<>();
        do {
            searchY--;
        } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0);
        do {
            searchY--;
        } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
                || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT));
        startPoint = new Point(foveaCenterXPosition, searchY);
        contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour,
                sharpOCT, 0));
    }
    setProgress(20);
    //open balck space found, complete contour to left of fovea
    contour.add(
            findContourLeft(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT));
    analysisManager.getImgPanel().setDrawPoint(new Point(foveaCenterXPosition, searchY));
    setProgress(30);
    /*
     since the contour can snake around due to aberations and low image density 
     we need to create a single line (represented by points) from left to right
     to represent the countour. This is easily done by building a line of
     points consisting of the point with the largest Y value (furthest from 
     the top of the image) at each X value. This eliminates overhangs from the 
     contour line.
     */
    Map<Double, List<Point>> grouped = contour.stream().collect(Collectors.groupingBy(Point::getX));
    List<Point> refinedEZContour = grouped.values().stream().map((List<Point> points) -> {
        int maxY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt();
        return new Point(points.get(0).x, maxY);
    }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList());
    setProgress(35);
    /*
     Starting from the identified location of the fovea search southward in 
     the image until the most southern pixels (in a 3x3 matrix of 
     pixels arround the the search point (X,Y) ) are black (ie. the search
     matrix has found that the search point isn't totally surrounded by
     white pixels). Then a recursive search algorithm determines if the 
     black area signifies the bottom of the Bruch's membrane or simply represents
     a closed (a black blob entirely surrounded by white pixels) black band.
     It will continue searching southward in the image until it can find an 
     open region of all black pixels. Once this is found it will find the contour
     of the edge between the black and white pixels, along the width of the image,
     of the bottom of the Bruch's membrane.
     */
    //        sharpOCT = getSharpenedOctImage(5D, 1.0F);
    searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition));
    do {
        searchY++;
    } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
            || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT));
    contour = new LinkedList<>();
    startPoint = new Point(foveaCenterXPosition, searchY);
    /*
     Find contour by searching for white pixel boundary to te right of the fovea.
     Sometimes the crap below the Bruchs membrane causes too much interferance for the
     algorithm to work properly so we must tweak some of the parameters of the 
     sharpening performed on the image until the algorithm succedes or we can no longer
     tweak parameters. In the case of the later event we can use the raw segmented
     Bruchs membrane as a substitute to keep the method from failing.
     */
    contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
            sharpOCT, 0));
    double filtValue = 8.5D;
    boolean tweakFailed = false;
    while (contour.contains(null)) {
        contour = new LinkedList<>();
        filtValue -= 0.5D;
        System.out.println("Reducing sigma to " + filtValue);
        if (filtValue <= 0D) {
            tweakFailed = true;
            break;
        }
        sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F);
        contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
                sharpOCT, 0));
    }

    if (tweakFailed) {
        contour = new LinkedList<>(rawBrmPoints);
    } else {
        //search until open black area found (ie. if the search algorithm arrives back at
        //the starting pixel keep moving south to next black area to search)
        while (contour.get(0).equals(startPoint)) {
            contour = new LinkedList<>();
            do {
                searchY++;
            } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0);
            do {
                searchY++;
            } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
                    || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT));
            startPoint = new Point(foveaCenterXPosition, searchY);
            contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
                    sharpOCT, 0));
        }
        setProgress(45);
        //open balck space found, complete contour to left of fovea
        contour.add(findContourLeft(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
                sharpOCT));
    }
    setProgress(55);
    /*
     since the contour can snake around due to aberations and low image density 
     we need to create a single line (represented by points) from left to right
     to represent the countour. This is easily done by building a line of
     points consisting of the point with the smallest Y value (closest to 
     the top of the image) at each X value. This eliminates overhangs from the 
     contour line.
     */
    grouped = contour.stream().collect(Collectors.groupingBy(Point::getX));
    List<Point> refinedBruchsMembraneContour = grouped.values().stream().map((List<Point> points) -> {
        int minY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt();
        return new Point(points.get(0).x, minY);
    }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList());
    setProgress(70);

    /*
     use a Loess interpolator again to smooth the new contours of the EZ and Bruch's Membrane
     */
    double[][] refinedContourPoints = Util.getXYArraysFromPoints(refinedEZContour);
    UnivariateFunction interpEZContour = interpolator.interpolate(refinedContourPoints[0],
            refinedContourPoints[1]);
    refinedContourPoints = Util.getXYArraysFromPoints(refinedBruchsMembraneContour);
    UnivariateFunction interpBruchsContour = interpolator.interpolate(refinedContourPoints[0],
            refinedContourPoints[1]);

    /*
     find the average difference in the distance in the Y between the 10 pixels
     at each end of the Bruch's Membrane contour and the contour created
     along the top of the EZ.
     */
    //since the lines are sorted on X position it is easy to align the lines
    //based on the tails of each line
    int minX = refinedEZContour.get(0).x;
    int maxX;
    //the interpolator can shorten the range of the X values from the original supplied
    //so we need to test where the end of the range occurs since it isn't directly accessible
    for (maxX = refinedEZContour.get(refinedEZContour.size() - 1).x; maxX > minX; maxX--) {
        try {
            double tmp = interpEZContour.value(maxX) - interpBruchsContour.value(maxX);
            //if this break is reached we have found the max value the interpolators will allow
            break;
        } catch (OutOfRangeException oe) {
            //do nothing but let loop continue
        }
    }
    double avgDif = Stream
            .concat(IntStream.range(minX + 30, minX + 50).boxed(),
                    IntStream.range(maxX - 49, maxX - 28).boxed())
            .mapToDouble(x -> interpBruchsContour.value(x) - interpEZContour.value(x)).average().getAsDouble();

    int height = sharpOCT.getHeight();//make to use in lambda expression
    List<LinePoint> ezLine = IntStream.rangeClosed(minX, maxX)
            .mapToObj(x -> new LinePoint(x, height - interpEZContour.value(x) - avgDif))
            .collect(Collectors.toList());
    List<LinePoint> bmLine = IntStream.rangeClosed(minX, maxX)
            .mapToObj(x -> new LinePoint(x, height - interpBruchsContour.value(x)))
            .collect(Collectors.toList());
    List<LinePoint> bmUnfiltLine = refinedBruchsMembraneContour.stream()
            .map((Point p) -> new LinePoint(p.x, height - p.getY())).collect(Collectors.toList());
    Util.graphPoints(ezLine, bmLine, bmUnfiltLine);
    analysisManager.getImgPanel().setDrawnLines(
            IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpEZContour.value(x)))
                    .collect(Collectors.toList()),
            IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpBruchsContour.value(x)))
                    .collect(Collectors.toList()));
    /*
     Find the difference between the two contours (Bruch's membrane and the
     EZ + Bruch's membrane) and use this to determine where the edge of the
     EZ is
     */
    List<LinePoint> diffLine = findDiffWithAdjustment(interpBruchsContour, 0D, interpEZContour, avgDif, minX,
            maxX);
    setProgress(90);
    //        List<LinePoint> peaks = Util.findPeaksAndVallies(diffLine);
    //        Util.graphPoints(diffLine, peaks);

    /*
     Find the first zero crossings of the difference line on both sides of the fovea.
     If a zero crossing can't be found then search for the first crossing of a
     value of 1, then 2, then 3, etc. until an X coordinate of a crossing is
     found on each side of the fovea.
     */
    OptionalInt ezLeftEdge;
    double crossingThreshold = 0.25D;
    do {
        double filtThresh = crossingThreshold;
        System.out.println("Crossing threshold = " + crossingThreshold);
        ezLeftEdge = diffLine.stream().filter(lp -> lp.getY() <= filtThresh && lp.getX() < foveaCenterXPosition)
                .mapToInt(LinePoint::getX).max();
        crossingThreshold += 0.25D;
    } while (!ezLeftEdge.isPresent());
    OptionalInt ezRightEdge;
    crossingThreshold = 0.25D;
    do {
        double filtThresh = crossingThreshold;
        System.out.println("Crossing threshold = " + crossingThreshold);
        ezRightEdge = diffLine.stream()
                .filter(lp -> lp.getY() <= filtThresh && lp.getX() > foveaCenterXPosition)
                .mapToInt(LinePoint::getX).min();
        crossingThreshold += 0.25D;
    } while (!ezRightEdge.isPresent());
    //return findings
    return new EZEdgeCoord(ezLeftEdge.getAsInt(), ezRightEdge.getAsInt());
}

From source file:delfos.dataset.util.DatasetPrinter.java

private static String actuallyDoTheTable(final List<Item> itemsAllUsersRated, final List<User> users,
        DatasetLoader<? extends Rating> datasetLoader) {
    List<String> columnNames = new ArrayList<>();
    columnNames.add("user\\items");
    columnNames.addAll(//w w  w.  j a  v  a 2 s  . c om
            itemsAllUsersRated.stream().map(item -> "Item_" + item.getId()).collect(Collectors.toList()));

    Object[][] data = new Object[users.size()][itemsAllUsersRated.size() + 1];

    DecimalFormat format = new DecimalFormat("0.0000");

    IntStream.range(0, users.size()).forEach(indexUser -> {
        User user = users.get(indexUser);

        data[indexUser][0] = user.toString();

        Map<Integer, ? extends Rating> userRatingsRated = datasetLoader.getRatingsDataset()
                .getUserRatingsRated(user.getId());

        IntStream.range(0, itemsAllUsersRated.size()).forEach(indexItem -> {
            Item item = itemsAllUsersRated.get(indexItem);
            if (userRatingsRated.containsKey(item.getId())) {
                data[indexUser][indexItem + 1] = format
                        .format(userRatingsRated.get(item.getId()).getRatingValue().doubleValue());
            } else {
                data[indexUser][indexItem + 1] = "";
            }
        });
    });

    TextTable textTable = new TextTable(columnNames.toArray(new String[0]), data);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream recordingStream = new PrintStream(baos);
    textTable.printTable(recordingStream, 0);

    return baos.toString();
}

From source file:nl.rivm.cib.episim.model.disease.infection.MSEIRSTest.java

public static Observable<Entry<Double, long[]>> stochasticSellke(final SIRConfig config, final double maxDt) {
    return Observable.create(sub -> {
        final double beta = config.reproduction() / config.recovery();
        final long[] y = config.population();
        final double[] T = config.t();
        final double dt = Double.isFinite(maxDt) && maxDt > 0 ? maxDt : T[1];

        final Long seed = config.seed();
        final RandomGenerator rng = new MersenneTwister(seed == null ? System.currentTimeMillis() : seed);

        final ExponentialDistribution resistanceDist = new ExponentialDistribution(rng, 1),
                recoverDist = new ExponentialDistribution(rng, config.recovery());

        // pending infections (mapping resistance -> amount)
        final TreeMap<Double, Integer> tInfect = IntStream.range(0, (int) y[0])
                .mapToObj(i -> resistanceDist.sample())
                .collect(Collectors.toMap(r -> r, r -> 1, Integer::sum, TreeMap::new));
        // pending recoveries (mapping time -> amount)
        final TreeMap<Double, Integer> tRecover = new TreeMap<>();

        double cumPres = 0;
        // Re-initialize infectives as susceptibles with zero resistance
        tInfect.put(cumPres, (int) y[1]);
        y[0] += y[1]; // I -> S
        y[1] -= y[1]; // I -> 0
        for (double t = T[0]; t < T[1];) {
            publishCopy(sub, t, y);/*from  w  w  w.j  av  a2s  . c om*/
            final long localPopSize = y[0] + y[1] + y[2];
            final Double ri = tInfect.isEmpty() ? null : tInfect.firstKey(), ti = ri == null ? null :
            // now + remaining resistance per relative pressure
            t + (ri - cumPres) / (beta * Math.max(y[1], 1) / localPopSize),
                    tr = tRecover.isEmpty() ? null : tRecover.firstKey();

            // time of next infection is earliest
            if (ti != null && (tr == null || ti < tr)) {
                final int ni = tInfect.remove(ri);
                cumPres = ri;

                // publish intermediate values
                for (double t1 = Math.min(ti, t + dt), tMax = Math.min(T[1], ti); t1 < tMax; t1 += dt)
                    publishCopy(sub, t1, y);

                // infect
                t = ti;
                y[0] -= ni; // from S
                y[1] += ni; // to I

                // schedule S_t recoveries at t+Exp(1/gamma)
                for (int i = 0; i < ni; i++)
                    tRecover.compute(t + recoverDist.sample(), (k, v) -> v == null ? 1 : v + 1);
            }
            // time of next recovery is earliest
            else if (tr != null) {
                final int nr = tRecover.remove(tr);
                if (ri != null)
                    // advance cumulative pressure by dt * relative pressure
                    cumPres += (tr - t) * beta * y[1] / localPopSize;

                // publish intermediate values
                for (double t1 = Math.min(tr, t + dt), tMax = Math.min(T[1], tr); t1 < tMax; t1 += dt)
                    publishCopy(sub, t1, y);

                // recover
                t = tr;
                y[1] -= nr; // from I
                y[2] += nr; // to R
            }
            // no events remaining
            else {
                // publish intermediate values
                for (double t1 = t + dt; t1 < T[1]; t1 += dt)
                    publishCopy(sub, t1, y);

                // time ends
                break;
            }
        }
        sub.onComplete();
    });
}

From source file:org.apache.bookkeeper.metadata.etcd.EtcdLedgerManagerTest.java

static List<BookieSocketAddress> createNumBookies(int numBookies) {
    return IntStream.range(0, numBookies).mapToObj(idx -> new BookieSocketAddress("127.0.0.1", 3181 + idx))
            .collect(Collectors.toList());
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

@Test
public void shouldRespectHighWaterMarkSettingAndSucceed() throws Exception {
    // the highwatermark should get exceeded on the server and thus pause the writes, but have no problem catching
    // itself up - this is a tricky tests to get passing on all environments so this assumption will deny the
    // test for most cases
    assumeThat("Set the 'assertNonDeterministic' property to true to execute this test",
            System.getProperty("assertNonDeterministic"), is("true"));

    final Cluster cluster = Cluster.open();
    final Client client = cluster.connect();

    try {/*from w ww  . j av  a  2s .  com*/
        final int resultCountToGenerate = 1000;
        final int batchSize = 3;
        final String fatty = IntStream.range(0, 175).mapToObj(String::valueOf).collect(Collectors.joining());
        final String fattyX = "['" + fatty + "'] * " + resultCountToGenerate;

        // don't allow the thread to proceed until all results are accounted for
        final CountDownLatch latch = new CountDownLatch(resultCountToGenerate);
        final AtomicBoolean expected = new AtomicBoolean(false);
        final AtomicBoolean faulty = new AtomicBoolean(false);
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_BATCH_SIZE, batchSize).addArg(Tokens.ARGS_GREMLIN, fattyX).create();

        client.submitAsync(request).thenAcceptAsync(r -> {
            r.stream().forEach(item -> {
                try {
                    final String aFattyResult = item.getString();
                    expected.set(aFattyResult.equals(fatty));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    faulty.set(true);
                } finally {
                    latch.countDown();
                }
            });
        });

        assertTrue(latch.await(30000, TimeUnit.MILLISECONDS));
        assertEquals(0, latch.getCount());
        assertFalse(faulty.get());
        assertTrue(expected.get());

        assertTrue(recordingAppender.getMessages().stream()
                .anyMatch(m -> m.contains("Pausing response writing as writeBufferHighWaterMark exceeded on")));
    } catch (Exception ex) {
        fail("Shouldn't have tossed an exception");
    } finally {
        cluster.close();
    }
}