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.orange.ngsi2.server.Ngsi2BaseControllerTest.java

@Test
public void checkListTypeInvalidSyntax() throws Exception {
    String p257times = IntStream.range(0, 257).mapToObj(x -> "p").collect(Collectors.joining());
    String message = "The incoming request is invalid in this context. " + p257times + " has a bad syntax.";
    mockMvc.perform(get("/v2/i/entities").param("type", p257times).contentType(MediaType.APPLICATION_JSON)
            .header("Host", "localhost").accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath("$.error").value("400"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.description").value(message))
            .andExpect(status().isBadRequest());
}

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

/**
 * test percentile/*from   w ww.ja  v  a2 s .  c o  m*/
 */
@Test
public final void percentile() {
    final List<ITerm> l_return = new ArrayList<>();
    final DescriptiveStatistics l_statistic1 = new DescriptiveStatistics();
    final DescriptiveStatistics l_statistic2 = new DescriptiveStatistics();

    IntStream.range(0, 100).peek(l_statistic1::addValue).forEach(i -> l_statistic2.addValue(i * 10));

    new CSinglePercentile().execute(false, IContext.EMPTYPLAN,
            Stream.of(50, l_statistic1, l_statistic2).map(CRawTerm::from).collect(Collectors.toList()),
            l_return);

    new CMultiplePercentile().execute(false, IContext.EMPTYPLAN,
            Stream.of(l_statistic1, 25, 75).map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 4);
    Assert.assertArrayEquals(l_return.stream().map(i -> i.<Number>raw().doubleValue()).toArray(),
            Stream.of(49.5, 495, 24.25, 74.75).mapToDouble(Number::doubleValue).boxed().toArray());
}

From source file:org.apache.sysml.runtime.instructions.cp.ParamservBuiltinCPInstruction.java

@Override
public void processInstruction(ExecutionContext ec) {
    Timing tSetup = DMLScript.STATISTICS ? new Timing(true) : null;

    PSModeType mode = getPSMode();/*from  www  .j  ava 2 s.c o  m*/
    int workerNum = getWorkerNum(mode);
    BasicThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("workers-pool-thread-%d")
            .build();
    ExecutorService es = Executors.newFixedThreadPool(workerNum, factory);
    String updFunc = getParam(PS_UPDATE_FUN);
    String aggFunc = getParam(PS_AGGREGATION_FUN);

    int k = getParLevel(workerNum);

    // Get the compiled execution context
    // Create workers' execution context
    LocalVariableMap newVarsMap = createVarsMap(ec);
    List<ExecutionContext> newECs = ParamservUtils.createExecutionContexts(ec, newVarsMap, updFunc, aggFunc,
            workerNum, k);

    // Create workers' execution context
    List<ExecutionContext> workerECs = newECs.subList(0, newECs.size() - 1);

    // Create the agg service's execution context
    ExecutionContext aggServiceEC = newECs.get(newECs.size() - 1);

    PSFrequency freq = getFrequency();
    PSUpdateType updateType = getUpdateType();
    int epochs = getEpochs();

    // Create the parameter server
    ListObject model = ec.getListObject(getParam(PS_MODEL));
    ParamServer ps = createPS(mode, aggFunc, updateType, workerNum, model, aggServiceEC);

    // Create the local workers
    MatrixObject valFeatures = ec.getMatrixObject(getParam(PS_VAL_FEATURES));
    MatrixObject valLabels = ec.getMatrixObject(getParam(PS_VAL_LABELS));
    List<LocalPSWorker> workers = IntStream.range(0, workerNum).mapToObj(i -> new LocalPSWorker(i, updFunc,
            freq, epochs, getBatchSize(), valFeatures, valLabels, workerECs.get(i), ps))
            .collect(Collectors.toList());

    // Do data partition
    PSScheme scheme = getScheme();
    doDataPartitioning(scheme, ec, workers);

    if (DMLScript.STATISTICS)
        Statistics.accPSSetupTime((long) tSetup.stop());

    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format(
                "\nConfiguration of paramserv func: " + "\nmode: %s \nworkerNum: %d \nupdate frequency: %s "
                        + "\nstrategy: %s \ndata partitioner: %s",
                mode, workerNum, freq, updateType, scheme));
    }

    try {
        // Launch the worker threads and wait for completion
        for (Future<Void> ret : es.invokeAll(workers))
            ret.get(); //error handling
        // Fetch the final model from ps
        ListObject result = ps.getResult();
        ec.setVariable(output.getName(), result);
    } catch (InterruptedException | ExecutionException e) {
        throw new DMLRuntimeException("ParamservBuiltinCPInstruction: some error occurred: ", e);
    } finally {
        es.shutdownNow();
        // Should shutdown the thread pool in param server
        ps.shutdown();
    }
}

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

@Override
public final boolean startsWith(final IPath p_path) {
    return p_path.size() <= this.size() && IntStream.range(0, p_path.size()).boxed().parallel()
            .allMatch(i -> this.get(i).equals(p_path.get(i)));

}

From source file:com.simiacryptus.mindseye.applications.ArtistryUtil.java

/**
 * Paint circles./*ww w  . j  av  a2 s. c  o m*/
 *
 * @param canvas the canvas
 * @param scale  the scale
 */
public static void paint_Circles(final Tensor canvas, final int scale) {
    BufferedImage originalImage = canvas.toImage();
    BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = (Graphics2D) newImage.getGraphics();
    IntStream.range(0, 10000).forEach(i -> {
        Random random = new Random();
        int positionX = random.nextInt(originalImage.getWidth());
        int positionY = random.nextInt(originalImage.getHeight());
        int width = 1 + random.nextInt(2 * scale);
        int height = 1 + random.nextInt(2 * scale);
        DoubleStatistics[] stats = { new DoubleStatistics(), new DoubleStatistics(), new DoubleStatistics() };
        canvas.coordStream(false).filter(c -> {
            int[] coords = c.getCoords();
            int x = coords[0];
            int y = coords[1];
            double relX = Math.pow(1 - 2 * ((double) (x - positionX) / width), 2);
            double relY = Math.pow(1 - 2 * ((double) (y - positionY) / height), 2);
            return relX + relY < 1.0;
        }).forEach(c -> stats[c.getCoords()[2]].accept(canvas.get(c)));
        graphics.setStroke(new Stroke() {
            @Override
            public Shape createStrokedShape(final Shape p) {
                return null;
            }
        });
        graphics.setColor(new Color((int) stats[0].getAverage(), (int) stats[1].getAverage(),
                (int) stats[2].getAverage()));
        graphics.fillOval(positionX, positionY, width, height);
    });
    canvas.set(Tensor.fromRGB(newImage));
}

From source file:info.rmarcus.birkhoffvonneumann.MatrixUtils.java

public static int[] randomPermutationSparse(Random r, int n) {
    List<Integer> s = IntStream.range(0, n).mapToObj(i -> i)
            .collect(Collectors.toCollection(() -> new ArrayList<Integer>(n)));
    Collections.shuffle(s, r);/*from   w  w w  .  j  a  v  a2s . c  o m*/
    return NullUtils.orThrow(s.stream().mapToInt(i -> i).toArray(),
            () -> new BVNRuntimeException("Could not convert ArrayList to array!"));
}

From source file:com.intuit.wasabi.tests.service.priority.BatchPriorityAssignmentTest.java

@Test(groups = { "batchAssign" }, dependsOnGroups = { "setup" }, dependsOnMethods = { "t_batchAssign" })
public void t_changePriorityBatchAssign() {
    response = apiServerConnector.doPost("experiments/" + validExperimentsLists.get(0).id + "/priority/5");
    assertReturnCode(response, HttpStatus.SC_CREATED);
    response = apiServerConnector//from   w  w w.  j a  v a  2s.  co m
            .doGet("applications/" + validExperimentsLists.get(0).applicationName + "/priorities");
    assertReturnCode(response, HttpStatus.SC_OK);
    clearAssignmentsMetadataCache();
    String lables = "{\"labels\": ["
            + validExperimentsLists.stream().map(s -> "\"" + s.label + "\"").collect(Collectors.joining(","))
            + "]}";
    response = apiServerConnector.doPost(
            "/assignments/applications/" + validExperimentsLists.get(0).applicationName + "/users/johnDoe2",
            lables);
    assertReturnCode(response, HttpStatus.SC_OK);
    LOGGER.info("output: " + response.asString());
    Type listType = new TypeToken<Map<String, ArrayList<Map<String, Object>>>>() {
    }.getType();
    Map<String, List<Map<String, Object>>> result = new Gson().fromJson(response.asString(), listType);
    List<Map<String, Object>> assignments = result.get("assignments");
    Assert.assertNull(assignments.get(assignments.size() - 1).get("assignment"));
    IntStream.range(0, assignments.size() - 1)
            .forEach(i -> Assert.assertNotNull(assignments.get(i).get("assignment")));
}

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

/**
 * test equal//from   ww w  . j ava2  s  .  c  o m
 */
@Test
public final void equal() {
    final List<ITerm> l_return = new ArrayList<>();

    new CEqual().execute(false, null,
            Stream.of(l_return, l_return, new Object()).map(CRawTerm::from).collect(Collectors.toList()),
            l_return);

    Assert.assertEquals(l_return.size(), 2);
    Assert.assertTrue(l_return.get(0).<Boolean>raw());
    Assert.assertFalse(l_return.get(1).<Boolean>raw());

    final List<Integer> l_list1 = IntStream.range(0, 5).boxed().collect(Collectors.toList());
    final List<Integer> l_list2 = IntStream.range(0, 5).boxed().collect(Collectors.toList());

    new CEqual().execute(false, IContext.EMPTYPLAN,
            Stream.of(l_list1, l_list2).map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 3);
    Assert.assertTrue(l_return.get(2).<Boolean>raw());

    final Map<Integer, Integer> l_map1 = new HashMap<>();
    l_map1.put(1, 2);
    final Map<Integer, Integer> l_map2 = new HashMap<>();
    l_map2.put(1, 1);

    new CEqual().execute(false, IContext.EMPTYPLAN,
            Stream.of(l_map1, l_map2).map(CRawTerm::from).collect(Collectors.toList()), l_return);

    Assert.assertEquals(l_return.size(), 4);
    Assert.assertFalse(l_return.get(3).<Boolean>raw());
}

From source file:com.nirmata.workflow.details.TestJsonSerializer.java

private Task randomTask(int index) {
    List<Task> childrenTasks = Lists.newArrayList();
    boolean shouldHaveChildren = (index == 0) || ((index < 2) && random.nextBoolean());
    int childrenQty = shouldHaveChildren ? random.nextInt(5) : 0;
    IntStream.range(0, childrenQty).forEach(i -> childrenTasks.add(randomTask(index + 1)));
    return new Task(new TaskId(), randomTaskType(), childrenTasks, randomMap());
}

From source file:com.rcn.controller.ResourceController.java

@RequestMapping(value = "/license-key", method = RequestMethod.POST)
public String licenseKeyPost(@RequestParam("name") String name, @RequestParam("validFor") Integer validFor,
        @RequestParam("keyExpires") Integer keyExpires,
        @RequestParam("activationsNumber") Integer activationsNumber,
        @RequestParam("customKey") String customKey, @RequestParam("key") Long key,
        @RequestParam("val") String val,
        @RequestParam(name = "resourceGroup", required = false) boolean resourceGroup,
        @RequestParam(name = "customNumber", required = false) boolean customNumber, Authentication principal,
        Model model) {//w  w  w . j  ava 2 s .c o  m

    RcnUserDetail user = (RcnUserDetail) principal.getPrincipal();
    Long targetUserId = user.getTargetUser().getId();
    try {
        String lk = customNumber
                ? IntStream.range(0, 1).mapToObj(a -> customKey.toUpperCase()).filter(a -> a.length() == 16)
                        .filter(a -> resourceRepository.containsKey(a) == null).findFirst()
                        .orElseThrow(() -> new IllegalArgumentException(l("invalid.custom.number")))
                : IntStream.range(0, 10).mapToObj(a -> generateLicenseKey())
                        .filter(a -> resourceRepository.containsKey(a) == null).findFirst()
                        .orElseThrow(() -> new IllegalArgumentException(l("cant.generate.license.key")));

        Long id = resourceRepository.createLicenseKey(targetUserId, name, lk, validFor, keyExpires,
                activationsNumber);
        if (resourceGroup) {
            resourceRepository.licenseKeyToResourceGroup(targetUserId, id, key);
        }
    } catch (IllegalArgumentException e) {
        model.addAttribute("error", e.getMessage());
    }

    return "license-key";
}