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.lightjason.agentspeak.common.CPath.java

/**
 * normalize the internal path//from   w w w.  jav a2 s.  c  o  m
 */
private synchronized void normalize() {
    if (m_path.isEmpty())
        return;

    // create path-copy and nomalize (remove dot, double-dot and empty values)
    final List<String> l_dotremove = m_path.stream()
            .filter(i -> (i != null) && (!i.isEmpty()) && (!".".equals(i))).collect(Collectors.toList());
    if (l_dotremove.isEmpty())
        return;

    final String l_last = l_dotremove.get(l_dotremove.size() - 1);
    final List<String> l_backremove = IntStream.range(0, l_dotremove.size() - 1).boxed()
            .filter(i -> !l_dotremove.get(i + 1).equals("..")).map(l_dotremove::get)
            .collect(Collectors.toList());
    if (!"..".equals(l_last))
        l_backremove.add(l_last);

    // clear internal path and add optimized path
    m_path.clear();
    l_backremove.forEach(m_path::add);
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

/**
 * Add new segments to the segment table.
 * This method is designed to work with chunked creation. So it takes a
 * toCreate count and newRanges and it picks toCreate entries from the end of newranges.
 *
 * @param startingSegmentNumber starting segment number
 * @param segmentTable          segment table
 * @param newRanges             ranges//from  ww  w .jav  a  2s  .co  m
 * @param timeStamp             timestamp
 * @return
 */
public static byte[] updateSegmentTable(final int startingSegmentNumber, final byte[] segmentTable,
        final List<AbstractMap.SimpleEntry<Double, Double>> newRanges, final long timeStamp) {
    final ByteArrayOutputStream segmentStream = new ByteArrayOutputStream();
    try {
        segmentStream.write(segmentTable);

        IntStream.range(0, newRanges.size()).forEach(x -> {
            try {
                segmentStream.write(new SegmentRecord(startingSegmentNumber + x, timeStamp,
                        newRanges.get(x).getKey(), newRanges.get(x).getValue()).toByteArray());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return segmentStream.toByteArray();
}

From source file:org.apache.sysml.runtime.matrix.data.SinglePrecisionCudaSupportFunctions.java

@Override
public void hostToDevice(GPUContext gCtx, double[] src, Pointer dest, String instName) {
    LOG.debug("Potential OOM: Allocated additional space in hostToDevice");
    // TODO: Perform conversion on GPU using double2float and float2double kernels
    long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;
    if (PERFORM_CONVERSION_ON_DEVICE) {
        Pointer deviceDoubleData = gCtx.allocate(((long) src.length) * Sizeof.DOUBLE);
        cudaMemcpy(deviceDoubleData, Pointer.to(src), ((long) src.length) * Sizeof.DOUBLE,
                cudaMemcpyHostToDevice);
        LibMatrixCUDA.double2float(gCtx, deviceDoubleData, dest, src.length);
        gCtx.cudaFreeHelper(instName, deviceDoubleData, DMLScript.EAGER_CUDA_FREE);
    } else {//from w ww . j a v a2 s  .c om
        FloatBuffer floatData = ByteBuffer.allocateDirect(Sizeof.FLOAT * src.length)
                .order(ByteOrder.nativeOrder()).asFloatBuffer();
        IntStream.range(0, src.length).parallel().forEach(i -> floatData.put(i, (float) src[i]));
        cudaMemcpy(dest, Pointer.to(floatData), ((long) src.length) * Sizeof.FLOAT, cudaMemcpyHostToDevice);
    }

    if (DMLScript.STATISTICS) {
        long totalTime = System.nanoTime() - t0;
        GPUStatistics.cudaDouble2FloatTime.add(totalTime);
        GPUStatistics.cudaDouble2FloatCount.add(1);
        if (DMLScript.FINEGRAINED_STATISTICS && instName != null)
            GPUStatistics.maintainCPMiscTimes(instName, GPUInstruction.MISC_TIMER_HOST_TO_DEVICE, totalTime);
    }
}

From source file:org.icgc.dcc.portal.pql.convert.FiltersConverter.java

private static <T> Stream<T> tail(@NonNull List<T> list) {
    val size = list.size();

    return (size < 2) ? Stream.empty() : IntStream.range(1, size).boxed().map(i -> list.get(i));
}

From source file:it.greenvulcano.gvesb.api.controller.GvConfigurationControllerRest.java

@GET
@Path("/configuration/{configId}")
@Produces(MediaType.APPLICATION_JSON)/*from  ww w . j  a  v a  2s. c om*/
@RolesAllowed({ Authority.ADMINISTRATOR, Authority.MANAGER })
public Response getArchivedConfigServices(@PathParam("configId") String id) {

    try {
        byte[] gvcore = gvConfigurationManager.extract(id, "GVCore.xml");

        if (gvcore != null && gvcore.length > 0) {

            Document gvcoreDocument = documentBuilder.parse(new ByteArrayInputStream(gvcore));

            NodeList serviceNodes = XMLConfig.getNodeList(gvcoreDocument, "//Service");

            Map<String, ServiceDTO> services = IntStream.range(0, serviceNodes.getLength())
                    .mapToObj(serviceNodes::item).map(ServiceDTO::buildServiceFromConfig)
                    .filter(Optional::isPresent).map(Optional::get)
                    .collect(Collectors.toMap(ServiceDTO::getIdService, Function.identity()));

            LOG.debug("Services found " + serviceNodes.getLength());
            return Response.ok(toJson(services)).build();

        }

        return Response.status(Response.Status.NOT_FOUND).build();

    } catch (XMLConfigException | JsonProcessingException xmlConfigException) {
        LOG.error("Error reading services configuration", xmlConfigException);
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(toJson(xmlConfigException)).build());
    } catch (Exception e) {
        LOG.error("Error reading services configuration", e);
        return Response.status(Response.Status.NOT_FOUND).build();

    }

}

From source file:org.commonjava.maven.galley.cache.infinispan.FastLocalCacheProviderConcurrentIOTest.java

private void multiWriteOnFilesInFolder(final Map<String, String> fileFolderMap, final int threads)
        throws Exception {
    List<ConcreteResource> resources = new ArrayList<>(fileFolderMap.size());
    for (String fname : fileFolderMap.keySet()) {
        final String folder = fileFolderMap.get(fname);
        resources.add(createTestResource(fname, folder));
    }//  w  w w. jav  a 2s  .  co m

    final CountDownLatch waitLatch = new CountDownLatch(resources.size() * threads);

    for (ConcreteResource resource : resources) {
        IntStream.range(0, threads)
                .forEach(i -> testPool.execute(new WriteTask(provider, content, resource, waitLatch)));
    }

    TestIOUtils.latchWait(waitLatch, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS);

    for (ConcreteResource resource : resources) {
        final String localResult = readLocalResource(resource);
        final String nfsResult = readNFSResource(resource);
        assertThat(localResult, equalTo(nfsResult));
    }
}

From source file:it.greenvulcano.gvesb.virtual.gv_multipart.MultipartCallOperation.java

/**
  * Adds on a Map the key and the value the given NodeList
  * /*from ww w  .  j  a  v  a2s . c  om*/
  * @param sourceNodeList
  * @param destinationMap
  */
private void fillMap(NodeList sourceNodeList, Map<String, String> destinationMap) {

    if (sourceNodeList.getLength() == 0) {
        destinationMap.clear();
    } 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:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

private void checkArticlesInGui(FilterTestType testType, MainGui mainGui, int tableRowCount)
        throws IllegalAccessException {
    int expectedRowCount = mockConfiguration.useSpanTable() ? 2 : 1;

    if (testType == NO_MATCHES) {
        expectedRowCount = 0;/*from   ww w.j  a v a  2 s .  co m*/
    } else if (testType == REMOVE_TEXT) {
        expectedRowCount = 5;
    }

    assertEquals(expectedRowCount, tableRowCount);

    Object filteredArticlesField = FieldUtils.readField(mainGui, "filteredArticles", true);

    assertTrue(filteredArticlesField instanceof List);
    List filteredArticles = (List) filteredArticlesField;

    if (testType == INSERT_TEXT) {
        assertEquals("u1", ((Article) filteredArticles.get(0)).getUrl());
    } else if (testType == CHANGE_TEXT) {
        assertEquals("u2", ((Article) filteredArticles.get(0)).getUrl());
    } else if (testType == REMOVE_TEXT) {
        IntStream.range(0, filteredArticles.size()).forEach(index -> {
            // Test article 3 (with index 2) is archived and should be filtered out: u1, u2, u4, u5, and u6.
            String expectedUrl = "u" + (index + (index < 2 ? 1 : 2));
            assertEquals(expectedUrl, ((Article) filteredArticles.get(index)).getUrl());
        });
    }
}

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

/**
 * test flat action/*from w  w w. ja  va 2s  .  c o  m*/
 */
@Test
public final void flat() {
    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 CFlat().execute(false, IContext.EMPTYPLAN,
            l_list.stream().map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), l_list.size());
    Assert.assertArrayEquals(l_return.stream().map(ITerm::raw).toArray(), l_list.toArray());
}

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

public static final AdjMatrixEdgeWeightedDigraph cloneAdjMatrixEdgeWeightedDigraph(
        AdjMatrixEdgeWeightedDigraph adjMatrixEdgeWeightedDigraph) {
    AdjMatrixEdgeWeightedDigraph copy = new AdjMatrixEdgeWeightedDigraph(adjMatrixEdgeWeightedDigraph.V());

    IntStream.range(0, adjMatrixEdgeWeightedDigraph.V()).sequential().forEach(vertex -> {
        for (DirectedEdge directedEdge : adjMatrixEdgeWeightedDigraph.adj(vertex)) {
            copy.addEdge(directedEdge);//from   w  w  w  .  jav a  2 s. co  m
        }

    });

    return copy;
}