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.simiacryptus.mindseye.lang.Tensor.java

/**
 * Gets pixel stream.//from   w ww  .  jav  a2s  .  c o  m
 *
 * @return the pixel stream
 */
@Nonnull
public Stream<double[]> getPixelStream() {
    int[] dimensions = getDimensions();
    int width = dimensions[0];
    int height = dimensions[1];
    int bands = dimensions[2];
    return IntStream.range(0, width).mapToObj(x -> x).parallel().flatMap(x -> {
        return IntStream.range(0, height).mapToObj(y -> y).map(y -> {
            return getPixel(this, x, y, bands);
        });
    });
}

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

/**
 * Scale and create are two tasks where we update the table. For scale to be legitimate, it has to be
 * preceded by create. Which means all appropriate tables exist.
 * Scale Steps://from w w  w.  ja va  2 s .  co m
 * 1. Add new segment information in segment table.
 *
 * @param newRanges      key ranges of new segments to be created
 * @param scaleTimestamp scaling timestamp
 * @param runOnlyIfStarted run only if the scale operation was started.
 * @return : list of newly created segments with current epoch
 */
@Override
public CompletableFuture<StartScaleResponse> startScale(final List<Integer> sealedSegments,
        final List<AbstractMap.SimpleEntry<Double, Double>> newRanges, final long scaleTimestamp,
        boolean runOnlyIfStarted) {
    return verifyState(() -> getHistoryTable()
            .thenCompose(historyTable -> getSegmentTable()
                    .thenApply(segmentTable -> new ImmutablePair<>(historyTable, segmentTable)))
            .thenCompose(pair -> {
                final Data<T> segmentTable = pair.getRight();
                final Data<T> historyTable = pair.getLeft();
                final int activeEpoch = TableHelper.getActiveEpoch(historyTable.getData()).getKey();

                if (TableHelper.isScaleOngoing(historyTable.getData(), segmentTable.getData())) {
                    return isScaleRerun(sealedSegments, newRanges, segmentTable, historyTable, activeEpoch);
                } else {
                    if (!TableHelper.isScaleInputValid(sealedSegments, newRanges, segmentTable.getData())) {
                        log.error("scale input invalid {} {}", sealedSegments, newRanges);
                        throw new ScaleOperationExceptions.ScaleInputInvalidException();
                    }

                    // check input is valid and satisfies preconditions
                    if (!TableHelper.canScaleFor(sealedSegments, historyTable.getData())) {
                        // invalid input, log and ignore
                        log.warn("scale precondition failed {}", sealedSegments);
                        throw new ScaleOperationExceptions.ScalePreConditionFailureException();
                    }

                    if (runOnlyIfStarted) {
                        throw new ScaleOperationExceptions.ScaleStartException();
                    }

                    // fresh run
                    return scaleCreateNewSegments(newRanges, scaleTimestamp, segmentTable, activeEpoch);
                }
            })
            .thenCompose(epochStartSegmentpair -> getSegments(IntStream
                    .range(epochStartSegmentpair.getRight(),
                            epochStartSegmentpair.getRight() + newRanges.size())
                    .boxed().collect(Collectors.toList()))
                            .thenApply(newSegments -> new StartScaleResponse(epochStartSegmentpair.getLeft(),
                                    newSegments))),
            Lists.newArrayList(State.ACTIVE, State.SCALING));
}

From source file:com.facebook.presto.operator.aggregation.AggregationTestUtils.java

public static double[] constructDoublePrimitiveArray(int start, int length) {
    return IntStream.range(start, start + length).asDoubleStream().toArray();
}

From source file:org.ligoj.app.plugin.vm.aws.VmAwsPluginResource.java

/**
 * Return the resource tag value or <code>null</code>
 *//*from w w w . jav  a2s . co m*/
private String getResourceTag(final Element record, final String name) {
    return Optional.ofNullable(record.getElementsByTagName("tagSet").item(0))
            .map(n -> ((Element) n).getElementsByTagName("item"))
            .map(n -> IntStream.range(0, n.getLength()).mapToObj(n::item).map(t -> (Element) t)
                    .filter(t -> xml.getTagText(t, "key").equalsIgnoreCase(name))
                    .map(t -> xml.getTagText(t, "value")).findFirst().orElse(null))
            .orElse(null);
}

From source file:alfio.manager.TicketReservationManager.java

private void reserveAdditionalServicesForReservation(int eventId, String transactionId,
        ASReservationWithOptionalCodeModification additionalServiceReservation, PromoCodeDiscount discount) {
    Optional.ofNullable(additionalServiceReservation.getAdditionalServiceId())
            .flatMap(id -> optionally(() -> additionalServiceRepository.getById(id, eventId)))
            .filter(as -> additionalServiceReservation.getQuantity() > 0
                    && (as.isFixPrice() || Optional.ofNullable(additionalServiceReservation.getAmount())
                            .filter(a -> a.compareTo(BigDecimal.ZERO) > 0).isPresent()))
            .map(as -> Pair.of(eventRepository.findById(eventId), as)).ifPresent(pair -> {
                Event e = pair.getKey();
                AdditionalService as = pair.getValue();
                IntStream.range(0, additionalServiceReservation.getQuantity()).forEach(i -> {
                    AdditionalServicePriceContainer pc = AdditionalServicePriceContainer
                            .from(additionalServiceReservation.getAmount(), as, e, discount);
                    additionalServiceItemRepository.insert(UUID.randomUUID().toString(),
                            ZonedDateTime.now(Clock.systemUTC()), transactionId, as.getId(),
                            AdditionalServiceItemStatus.PENDING, eventId, pc.getSrcPriceCts(),
                            unitToCents(pc.getFinalPrice()), unitToCents(pc.getVAT()),
                            unitToCents(pc.getAppliedDiscount()));
                });//from w  w w .jav  a2 s . com
            });

}

From source file:delfos.rs.trustbased.WeightedGraph.java

public static final AdjMatrixEdgeWeightedDigraph inverseOfEdgeValue(
        AdjMatrixEdgeWeightedDigraph distanceGraph) {

    AdjMatrixEdgeWeightedDigraph weightGraph = new AdjMatrixEdgeWeightedDigraph(distanceGraph.V());

    List<DirectedEdge> allEdges = IntStream.range(0, distanceGraph.V()).boxed().map(vertex -> {
        Iterable<DirectedEdge> iterator = distanceGraph.adj(vertex);
        ArrayList<DirectedEdge> listOfEdges = new ArrayList<>();
        for (DirectedEdge edge : iterator) {
            listOfEdges.add(edge);//from  w  ww.j a va  2  s .  c  o m
        }
        return listOfEdges;
    }).flatMap(listOfEdges -> listOfEdges.stream()).collect(Collectors.toList());

    List<DirectedEdge> allEdgesConverted = allEdges.stream().map(edge -> {
        final double weight = edge.weight();

        double distance = 1 / weight;

        if (weight == 0) {
            distance = Double.POSITIVE_INFINITY;
        }

        return new DirectedEdge(edge.from(), edge.to(), distance);
    }).collect(Collectors.toList());

    allEdgesConverted.forEach(edge -> weightGraph.addEdge(edge));
    return weightGraph;
}

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

@Test
public void shouldFailUntilImportExecutes() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();

    final Set<String> imports = new HashSet<String>() {
        {/*from w w  w .ja v  a 2  s .  c  om*/
            add("import java.awt.Color");
        }
    };

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

    // 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 t1 = new Thread(
            () -> IntStream.range(0, 1000).mapToObj(i -> gremlinExecutor.eval("Color.BLACK")).forEach(f -> {
                f.exceptionally(t -> failures.incrementAndGet()).join();
                if (!f.isCompletedExceptionally())
                    successes.incrementAndGet();
            }));

    final Thread t2 = new Thread(() -> {
        while (failures.get() < 500) {
        }
        gremlinExecutor.getScriptEngines().addImports(imports);
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    assertTrue(successes.intValue() > 0);
    assertTrue(failures.intValue() >= 500);

    gremlinExecutor.close();
}

From source file:org.ligoj.app.plugin.vm.aws.VmAwsSnapshotResource.java

/**
 * Delete a snapshot./*from   ww  w .  jav a 2 s. com*/
 * 
 * @param task
 *            A transient instance of the related task, and also linked to a subscription. Note it is a read-only
 *            view.
 * @throws ParserConfigurationException
 *             XML parsing failed.
 * @throws IOException
 *             XML reading failed by the parser.
 * @throws SAXException
 *             XML processing failed.
 */
public void delete(final VmSnapshotStatus task) throws SAXException, IOException, ParserConfigurationException {
    final int subscription = task.getLocked().getId();
    // Initiate the task, validate the AMI to delete
    snapshotResource.nextStep(subscription, s -> {
        s.setPhase("searching-ami");
        s.setWorkload(3);
    });

    final String amiId = task.getSnapshotInternalId();
    final Snapshot ami = findById(subscription, amiId);

    if (ami == null) {
        // AMI has been deleted of never been correctly created
        snapshotResource.endTask(subscription, true, s -> {
            s.setStatusText(VmAwsPluginResource.KEY + ":ami-not-found");
            s.setFinishedRemote(true);
        });
        return;
    }

    // AMI has been found, unregister it
    snapshotResource.nextStep(subscription, s -> {
        s.setPhase("deregistering-ami");
        s.setDone(1);
    });
    if (!isReturnTrue(resource.processEC2(subscription, p -> "Action=DeregisterImage&ImageId=" + amiId))) {
        // Unregistering failed
        snapshotResource.endTask(subscription, true, s -> {
            s.setStatusText(VmAwsPluginResource.KEY + ":ami-unregistering-failed");
            s.setFinishedRemote(true);
        });
        return;
    }

    // AMI unregistering has been forwarded, need to delete the snapshot now
    snapshotResource.nextStep(subscription, s -> {
        s.setPhase("deleting-snapshots");
        s.setDone(2);
    });
    final StringBuilder query = new StringBuilder();
    IntStream.range(0, ami.getVolumes().size())
            .forEach(i -> query.append("&SnapshotId." + (i + 1) + "=" + ami.getVolumes().get(i).getId()));
    if (!isReturnTrue(resource.processEC2(subscription, p -> "Action=DeleteSnapshot" + query.toString()))) {
        // Deleting snapshots failed
        snapshotResource.endTask(subscription, true, s -> {
            s.setStatusText(VmAwsPluginResource.KEY + ":ami-deleting-snapshots-failed");
            s.setFinishedRemote(true);
        });
        return;
    }
    snapshotResource.endTask(subscription, false, s -> {
        s.setDone(3);
        s.setFinishedRemote(true);
    });
}

From source file:edu.pitt.dbmi.ccd.anno.annotation.AnnotationController.java

private Annotation newAnnotationData(Annotation annotation, @Valid List<AnnotationDataForm> data) {
    IntStream.range(0, data.size()).forEach(i -> {
        final Long attributeId = data.get(i).getAttribute();
        final Attribute attribute = attributeService.findById(attributeId);
        if (attribute == null) {
            throw new AttributeNotFoundException(attributeId);
        }/* w w w.java2s . co  m*/
        final String value = data.get(i).getValue();
        final List<AnnotationDataForm> subData = data.get(i).getChildren();
        AnnotationData annoData = new AnnotationData(annotation, attribute, value);
        annoData = annotationDataService.save(annoData);
        if (subData.size() > 0) {
            newAnnotationDataSubData(annotation, annoData, subData);
        }
    });
    return annotation;
}

From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java

@Test
public void testBlob() throws Exception {
    try (final Statement stmt = con.createStatement()) {
        stmt.executeUpdate("CREATE TABLE blobtest (id INT, b BLOB(64 K))");
        stmt.execute("INSERT INTO blobtest VALUES (41, NULL)");
        PreparedStatement ps = con.prepareStatement("INSERT INTO blobtest VALUES (?, ?)");
        ps.setInt(1, 42);/*from  w w  w  .  j  av a  2 s .c  o m*/
        final byte[] buffer = new byte[4002];
        IntStream.range(0, 4002).forEach((i) -> buffer[i] = (byte) ((i % 10) + 65));
        ByteArrayInputStream bais = new ByteArrayInputStream(buffer);

        // - set the value of the input parameter to the input stream
        ps.setBlob(2, bais, 4002);
        ps.execute();
        bais.close();

        final ResultSet resultSet = stmt.executeQuery("select * from blobtest");

        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        JdbcCommon.convertToAvroStream(resultSet, outStream, false);

        final byte[] serializedBytes = outStream.toByteArray();
        assertNotNull(serializedBytes);

        // Deserialize bytes to records
        final InputStream instream = new ByteArrayInputStream(serializedBytes);

        final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
        try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) {
            GenericRecord record = null;
            while (dataFileReader.hasNext()) {
                // Reuse record object by passing it to next(). This saves us from
                // allocating and garbage collecting many objects for files with
                // many items.
                record = dataFileReader.next(record);
                Integer id = (Integer) record.get("ID");
                Object o = record.get("B");
                if (id == 41) {
                    assertNull(o);
                } else {
                    assertNotNull(o);
                    assertTrue(o instanceof ByteBuffer);
                    assertEquals(4002, ((ByteBuffer) o).array().length);
                }
            }
        }
    }
}