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:io.github.carlomicieli.footballdb.starter.pages.Table.java

public Map<String, String> valuesForRow(int n) {
    if (tableWithoutHeader())
        return Collections.emptyMap();

    return rowValues(n).map(cells -> {
        Map<String, String> m = IntStream.range(0, columnsCount()).mapToObj(bindHeaderWithValue(cells))
                .collect(toMap(p -> p.getKey(), p -> p.getValue()));
        return m;
    }).orElse(null);//  ww w  .  j  a v a  2s  .  com
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.vmware.VMWareProviderVirtualMachineUtil.java

public Set<VirtualMachine> getAllVirtualMachines(Folder rootFolder) {
    try {/*from w w w.j ava  2 s  .c o m*/
        ManagedEntity[] managedEntities = new InventoryNavigator(rootFolder)
                .searchManagedEntities(EntityType.VM.getValue());

        return IntStream.range(0, managedEntities.length).mapToObj(i -> (VirtualMachine) managedEntities[i])
                .collect(Collectors.toSet());

    } catch (RemoteException e) {
        throw new RuntimeException("ERROR when retrieving VMWare virtual machines", e);
    }
}

From source file:org.apache.druid.data.input.impl.FileIteratingFirehoseTest.java

public FileIteratingFirehoseTest(List<String> texts, int numSkipHeaderRows) {
    parser = new StringInputRowParser(new CSVParseSpec(new TimestampSpec("ts", "auto", null),
            new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("x")), null, null), ",",
            ImmutableList.of("ts", "x"), false, numSkipHeaderRows), null);

    this.inputs = texts;
    this.expectedResults = inputs.stream().map(input -> input.split("\n")).flatMap(lines -> {
        final List<String> filteredLines = Arrays.asList(lines).stream().filter(line -> line.length() > 0)
                .map(line -> line.split(",")[1]).collect(Collectors.toList());

        final int numRealSkippedRows = Math.min(filteredLines.size(), numSkipHeaderRows);
        IntStream.range(0, numRealSkippedRows).forEach(i -> filteredLines.set(i, null));
        return filteredLines.stream();
    }).collect(Collectors.toList());
}

From source file:org.apache.bookkeeper.stream.storage.impl.sc.DefaultStorageContainerControllerTest.java

private static Set<BookieSocketAddress> newCluster(int numServers, int startServerIdx) {
    Set<BookieSocketAddress> cluster = IntStream.range(0, numServers)
            .mapToObj(idx -> new BookieSocketAddress("127.0.0.1", 4181 + startServerIdx + idx))
            .collect(Collectors.toSet());
    return ImmutableSet.copyOf(cluster);
}

From source file:org.apache.hadoop.hbase.master.assignment.AssignmentManagerUtil.java

static TransitRegionStateProcedure[] createUnassignProceduresForSplitOrMerge(MasterProcedureEnv env,
        Stream<RegionInfo> regions, int regionReplication) throws IOException {
    List<RegionStateNode> regionNodes = regions
            .flatMap(hri -> IntStream.range(0, regionReplication)
                    .mapToObj(i -> RegionReplicaUtil.getRegionInfoForReplica(hri, i)))
            .map(env.getAssignmentManager().getRegionStates()::getOrCreateRegionStateNode)
            .collect(Collectors.toList());
    TransitRegionStateProcedure[] procs = new TransitRegionStateProcedure[regionNodes.size()];
    boolean rollback = true;
    int i = 0;/*  ww  w . j a  va 2  s  . c o  m*/
    // hold the lock at once, and then release it in finally. This is important as SCP may jump in
    // if we release the lock in the middle when we want to do rollback, and cause problems.
    lock(regionNodes);
    try {
        for (; i < procs.length; i++) {
            RegionStateNode regionNode = regionNodes.get(i);
            TransitRegionStateProcedure proc = TransitRegionStateProcedure.unassign(env,
                    regionNode.getRegionInfo());
            if (regionNode.getProcedure() != null) {
                throw new HBaseIOException(
                        "The parent region " + regionNode + " is currently in transition, give up");
            }
            regionNode.setProcedure(proc);
            procs[i] = proc;
        }
        // all succeeded, set rollback to false
        rollback = false;
    } finally {
        if (rollback) {
            for (;;) {
                i--;
                if (i < 0) {
                    break;
                }
                RegionStateNode regionNode = regionNodes.get(i);
                regionNode.unsetProcedure(procs[i]);
            }
        }
        unlock(regionNodes);
    }
    return procs;
}

From source file:Imputers.KnniLDProb.java

public double[][][] impute(double[][][] callprobs, int[][][] readCounts) {
    ProbToCallMinDepth p2c = new ProbToCallMinDepth(knownDepth);

    byte[][] original = p2c.call(callprobs, readCounts);

    Correlation corr = new Pearson();

    byte[][] transposed = Matrix.transpose(original);

    //Map<Integer,List<Integer>> ld = corr.topn(transposed, 100);
    Map<Integer, int[]> ld = corr.topn(transposed, 100);

    //Integer[][] sim = new Integer[original[0].length][];
    int[][] sim = new int[original[0].length][];
    //for (Entry<Integer,List<Integer>> e: ld.entrySet())
    for (Entry<Integer, int[]> e : ld.entrySet()) {
        //Integer[] a = new Integer[e.getValue().size()];
        //sim[e.getKey()] = e.getValue().toArray(a);
        sim[e.getKey()] = e.getValue();/* w w  w  .  j  a v a  2 s .  c  o m*/
    }

    double[][][] probs = new double[original.length][][];

    Progress progress = ProgressFactory.get(original.length);

    IntStream.range(0, original.length).parallel().forEach(i -> {
        double[][] p = new double[original[i].length][];
        probs[i] = p;
        IntStream.range(0, original[i].length).forEach(j -> {
            if (Arrays.stream(readCounts[i][j]).sum() < knownDepth) {
                p[j] = imputeSingle(original, i, j, false, sim);
            } else {
                p[j] = callprobs[i][j];
            }
        });
        progress.done();
    });

    return probs;
}

From source file:io.mandrel.worker.WorkerContainer.java

public WorkerContainer(ExtractorService extractorService, Accumulators accumulators, Spider spider,
        Clients clients, DiscoveryClient discoveryClient) {
    super(accumulators, spider, clients);
    context.setDefinition(spider);//from w ww. j av  a  2 s .c o  m

    this.extractorService = extractorService;

    // Create the thread factory
    BasicThreadFactory threadFactory = new BasicThreadFactory.Builder()
            .namingPattern("worker-" + spider.getId() + "-%d").daemon(true).priority(Thread.MAX_PRIORITY)
            .build();

    // Get number of parallel loops
    int parallel = Runtime.getRuntime().availableProcessors();
    // Prepare a pool for the X parallel loops and the barrier refresh
    executor = Executors.newScheduledThreadPool(parallel + 1, threadFactory);

    // Prepare the barrier
    Barrier barrier = new Barrier(spider.getFrontier().getPoliteness(), discoveryClient);
    executor.scheduleAtFixedRate(() -> barrier.updateBuckets(), 10, 10, TimeUnit.SECONDS);

    // Create loop
    loops = new ArrayList<>(parallel);
    IntStream.range(0, parallel).forEach(idx -> {
        Loop loop = new Loop(extractorService, spider, clients, accumulators.spiderAccumulator(spider.getId()),
                accumulators.globalAccumulator(), barrier);
        loops.add(loop);
        executor.submit(loop);
    });

    // Init stores
    MetadataStore metadatastore = spider.getStores().getMetadataStore().build(context);
    metadatastore.init();
    MetadataStores.add(spider.getId(), metadatastore);

    BlobStore blobStore = spider.getStores().getBlobStore().build(context);
    blobStore.init();
    BlobStores.add(spider.getId(), blobStore);

    if (spider.getExtractors().getData() != null) {
        spider.getExtractors().getData().forEach(ex -> {
            DocumentStore documentStore = ex.getDocumentStore().metadataExtractor(ex).build(context);
            documentStore.init();
            DocumentStores.add(spider.getId(), ex.getName(), documentStore);
        });
    }

    // Init requesters
    spider.getClient().getRequesters().forEach(r -> {
        Requester<?> requester = r.build(context);

        // Prepare client
        if (requester.strategy().nameResolver() != null) {
            requester.strategy().nameResolver().init();
        }
        if (requester.strategy().proxyServersSource() != null) {
            requester.strategy().proxyServersSource().init();
        }
        requester.init();

        Requesters.add(spider.getId(), requester);
    });

    current.set(ContainerStatus.INITIATED);
}

From source file:com.karus.danktitles.commands.HelpSubcommand.java

@Override
public void execute(CommandSender sender, String[] args) {

    // Methods inheritied from CommandChecker
    if (!checkLength(sender, args, 1, 3))
        return;//from  www.  j  ava 2 s.c  o m
    if (!checkSender(sender, "danktitles.help"))
        return;

    LinkedHashMap<String, MutablePair<String, String>> parsedCommands;

    // Checks if the list needs to be filtered
    if (args.length == 1 || args[1].equals("all")) {
        parsedCommands = new LinkedHashMap<>(
                commands.entrySet().stream().filter(entry -> sender.hasPermission(entry.getValue().getLeft()))
                        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
    } else {
        parsedCommands = new LinkedHashMap<>(commands.entrySet().stream().filter(
                entry -> entry.getKey().contains(args[1]) && sender.hasPermission(entry.getValue().getLeft()))
                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
    }

    if (parsedCommands.isEmpty()) {
        sender.sendMessage(ChatColor.RED + "No matches found.");
        return;
    }

    if (args.length == 3) {
        try {
            page = Integer.parseInt(args[2]);
        } catch (NumberFormatException e) {
            sender.sendMessage(ChatColor.RED + "Invalid page number!");
            return;
        }
    } else {
        page = 1;
    }

    int totalPages = (int) Math.max(1, Math.floor(parsedCommands.size() / SIZE));

    if (page <= 0 || page > totalPages) {
        sender.sendMessage(ChatColor.RED + "Invalid page number!");
        return;
    }

    sender.sendMessage(ChatColor.GOLD + "[Commands - (" + ChatColor.RED + page + "/" + totalPages
            + ChatColor.GOLD + ") ]");

    ArrayList<String> keys = new ArrayList<>(parsedCommands.keySet());

    IntStream.range(page * SIZE - SIZE, parsedCommands.size()).limit(SIZE)
            .forEach(i -> sender.sendMessage(ChatColor.GOLD + commands.get(keys.get(i)).getRight()));

}

From source file:fr.scc.elo.controller.EloController.java

private Map<String, Object> getMatchMap(HttpServletRequest http, Integer taille) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("elotypes", EloType.values());
    map.put("taille", taille);
    String allTags = StringUtils.join(
            IntStream.range(1, taille + 1).mapToObj(i -> "#b" + i + ",#r" + i).collect(Collectors.toList()),
            ',');

    map.put("allTags", allTags);
    map.put("modif", connectionService.acceptIPUpdate(http.getRemoteAddr()));
    return map;//from   w w  w .j  av a2  s  . co m
}

From source file:com.epam.ta.reportportal.demo_data.DemoLaunchesService.java

private List<String> generateLaunches(DemoDataRq rq, Map<String, Map<String, List<String>>> suitesStructure,
        String user, String project, StatisticsCalculationStrategy statsStrategy) {
    return IntStream.range(0, rq.getLaunchesQuantity()).mapToObj(i -> {
        String launchId = startLaunch(NAME + "_" + rq.getPostfix(), i, project, user);
        generateSuites(suitesStructure, i, launchId, statsStrategy);
        finishLaunch(launchId);//  w  w  w.ja v  a2 s.c o  m
        return launchId;
    }).collect(toList());
}