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.adriss.bucketpool.BucketFactory.java

private void initClusters(int clusterAmount) {
    logger.info("Initializing {} clusters", clusterAmount);
    IntStream.range(0, clusterAmount).forEach(nbr -> {
        WrappedCluster cluster = new WrappedCluster(CouchbaseCluster.create(this.environment, this.nodes),
                this.name);
        logger.debug("Created [{}] cluster", cluster);
        this.unusedClusters.offer(cluster);
    });/*from  w w  w  .  ja v a  2 s. c o  m*/
    logger.info("Initialized {} clusters", clusterAmount);
}

From source file:org.lightjason.agentspeak.beliefbase.TestCView.java

/**
 * random test tree structure/*from  w  w w .  ja va 2s  . co  m*/
 */
@Test
public final void testTree() {
    final int l_max = 1000;
    final IView<IAgent<?>> l_beliefbase = new CBeliefbasePersistent<>(new CMultiStorage<>()).create("root");
    final IViewGenerator<IAgent<?>> l_gen = new CGenerator();

    IntStream.range(0, l_max).boxed()
            .map(i -> CLiteral.from(RandomStringUtils.random(12, "~abcdefghijklmnopqrstuvwxyz/".toCharArray())))
            .forEach(i -> l_beliefbase.generate(l_gen, i.functorpath()).add(i));

    assertEquals("number of beliefs is incorrect", l_beliefbase.size(), l_max);
    System.out.println(l_beliefbase);
}

From source file:com.vsthost.rnd.jdeoptim.utils.Utils.java

/**
 * Creates an Integer sequence starting with 0 and sized given length.
 *
 * @param length The length of the sequence.
 * @return A sequence starting with 0 and ending with <code>length - 1</code>.
 *///from   w w w.  j a va2 s. com
public static int[] sequence(int length) {
    return IntStream.range(0, length).toArray();
}

From source file:kishida.cnn.layers.MaxPoolingLayer.java

@Override
public float[] backward(float[] in, float[] delta) {
    Arrays.fill(newDelta, 0);//from   ww w  .j  a va 2s  .com
    IntStream.range(0, inputChannels).parallel().forEach(ch -> {
        for (int x = 0; x < outputWidth; ++x) {
            for (int y = 0; y < outputHeight; ++y) {
                float max = Float.NEGATIVE_INFINITY;
                int maxX = 0;
                int maxY = 0;
                for (int i = 0; i < size; ++i) {
                    int xx = x * stride + i - size / 2;
                    if (xx < 0 || xx >= inputWidth) {
                        continue;
                    }
                    for (int j = 0; j < size; ++j) {
                        int yy = y * stride + j - size / 2;
                        if (yy < 0 || yy >= inputHeight) {
                            continue;
                        }
                        float d = in[ch * inputWidth * inputHeight + xx * inputWidth + yy];
                        if (max < d) {
                            max = d;
                            maxX = xx;
                            maxY = yy;
                        }
                    }
                }
                int chxy = ch * outputWidth * outputHeight + x * outputHeight + y;
                newDelta[ch * inputWidth * inputHeight + maxX * inputHeight + maxY] += delta[chxy];
            }
        }
    });
    return newDelta;
}

From source file:nova.minecraft.wrapper.mc.forge.v18.wrapper.redstone.backward.BWRedstone.java

@Override
public int getOutputWeakPower() {
    BlockPos pos = new BlockPos(block().x(), block().y(), block().z());
    return IntStream.range(0, 6).map(side -> block().mcBlock.isProvidingWeakPower(mcWorld(), pos,
            mcWorld().getBlockState(pos), EnumFacing.values()[side])).max().orElse(0);
}

From source file:org.apache.samza.tools.benchmark.SystemConsumerWithSamzaBench.java

@Override
public void addMoreSystemConfigs(Properties props) {
    props.put("app.runner.class", LocalApplicationRunner.class.getName());
    List<Integer> partitions = IntStream.range(startPartition, endPartition).boxed()
            .collect(Collectors.toList());
    props.put(ApplicationConfig.APP_NAME, "SamzaBench");
    props.put(JobConfig.PROCESSOR_ID(), "1");
    props.put(JobCoordinatorConfig.JOB_COORDINATOR_FACTORY, PassthroughJobCoordinatorFactory.class.getName());
    props.put(String.format(ConfigBasedSspGrouperFactory.CONFIG_STREAM_PARTITIONS, streamId),
            Joiner.on(",").join(partitions));
    props.put(TaskConfig.GROUPER_FACTORY(), ConfigBasedSspGrouperFactory.class.getName());
}

From source file:nova.minecraft.wrapper.mc.forge.v1_11.wrapper.redstone.backward.BWRedstone.java

@Override
public int getOutputWeakPower() {
    BlockPos pos = new BlockPos(block().x(), block().y(), block().z());
    return IntStream.range(0, 6)
            .map(side -> mcWorld().getBlockState(pos).getWeakPower(mcWorld(), pos, EnumFacing.values()[side]))
            .max().orElse(0);//  w ww.j a  v  a2s  . c  om
}

From source file:org.jbpm.xes.EvaluationExport.java

@Test
@Ignore//from w w  w .  ja v  a2 s  . c o  m
public void exportProcess() throws Exception {
    //users
    final String administrator = "Administrator";

    // create runtime manager with single process - hello.bpmn
    createRuntimeManager("evaluation.bpmn");

    // take RuntimeManager to work with process engine
    RuntimeEngine runtimeEngine = getRuntimeEngine();

    // get access to KieSession instance
    KieSession ksession = runtimeEngine.getKieSession();

    List<Long> pIds = new ArrayList<>();

    int instances = 100;

    IntStream.range(0, instances).forEach(i -> {
        Map<String, Object> vars = new HashMap<>();
        vars.put("employee", administrator);
        vars.put("reason", "test instance " + i);
        vars.put("performance", RandomUtils.nextInt(0, 11));

        // start process
        ProcessInstance processInstance = ksession.startProcess("evaluation", vars);

        // check whether the process instance has completed successfully
        assertProcessInstanceActive(processInstance.getId(), ksession);

        pIds.add(processInstance.getId());
    });

    final TaskService taskService = getRuntimeEngine().getTaskService();
    final List<TaskSummary> tasks = taskService.getTasksAssignedAsBusinessAdministrator(administrator, null);
    final ExecutorService executorService = Executors.newFixedThreadPool(5);
    CountDownLatch count = new CountDownLatch(instances * 3);
    tasks.forEach(t -> {
        executorService.submit(() -> {
            taskService.start(t.getId(), administrator);
            try {
                Thread.sleep(2 * 1000);
            } catch (Exception ex) {
            }
            taskService.complete(t.getId(), administrator, null);
            count.countDown();
            taskService.getTasksByProcessInstanceId(t.getProcessInstanceId()).stream()
                    .filter(newTaskId -> newTaskId.equals(t.getId()) == false).forEach(taskId -> {
                        executorService.submit(() -> {
                            final Task task = taskService.getTaskById(taskId);
                            final String userId = "HR Evaluation".equals(task.getName()) ? "mary" : "john";
                            taskService.claim(taskId, userId);
                            taskService.start(taskId, userId);
                            if ("HR Evaluation".equals(task.getName())) {
                                try {
                                    Thread.sleep(4 * 1000);
                                } catch (Exception ex) {
                                }
                            } else {
                                try {
                                    Thread.sleep(2 * 1000);
                                } catch (Exception ex) {
                                }
                            }
                            taskService.complete(taskId, userId, null);

                            count.countDown();
                        });
                    });
        });
    });

    count.await();
    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    pIds.forEach(id -> assertProcessInstanceCompleted(id));

    DataSetService dataSetService = new DataSetServiceImpl(() -> xesDataSource);
    XESExportServiceImpl service = new XESExportServiceImpl();
    service.setDataSetService(dataSetService);
    final String xml = service.export(XESProcessFilter.builder().withProcessId("evaluation").build());

    FileUtils.write(new File("evaluation.xes"), xml);
}

From source file:com.cyc.tool.distributedrepresentations.Word2VecSpaceFromFile.java

/**
 * Create a W2V space in a DB.// w w w  .j  av a  2  s  .  c  om
 * 
 * @param w2vZipFile
 * @throws FileNotFoundException
 * @throws IOException
 */
protected final void createW2VinDB(String w2vZipFile) throws FileNotFoundException, IOException {
    try (DataInputStream data_in = new DataInputStream(
            new GZIPInputStream(new FileInputStream(new File(w2vZipFile))))) {
        getWordsAndSize(data_in);
        if (vectors.size() == words) {
            System.out.println("Word2Vec is in DB");
        } else {
            System.out.println("DB Size:" + vectors.size());

            System.out.println("Want to read Word Count: " + words);
            System.out.println("Size:" + getSize());
            for (int w = 0; w < words; w++) {
                float[] v = new float[getSize()];
                String key = getVocabString(data_in);
                System.out.println(w + ":\t" + key);

                IntStream.range(0, getSize()).forEach(i -> v[i] = getFloat(data_in));
                vectors.put(key, normVector(v));
                if (w % 100000 == 1) {
                    db.commit();
                }
            }
            db.commit();
            db.compact();
        }
    }
}

From source file:com.wrmsr.search.dsl.util.DerivedSuppliers.java

public static <T> Class<? extends Supplier<T>> compile(java.lang.reflect.Method target,
        ClassLoader parentClassLoader) throws ReflectiveOperationException {
    checkArgument((target.getModifiers() & STATIC.getModifier()) > 0);
    List<TargetParameter> targetParameters = IntStream.range(0, target.getParameterCount()).boxed()
            .map(i -> new TargetParameter(target, i)).collect(toImmutableList());

    java.lang.reflect.Type targetReturnType = target.getGenericReturnType();
    java.lang.reflect.Type suppliedType = boxType(targetReturnType);
    checkArgument(suppliedType instanceof Class);

    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL),
            CompilerUtils.makeClassName(
                    "DerivedSupplier__" + target.getDeclaringClass().getName() + "__" + target.getName()),
            type(Object.class), type(Supplier.class, fromReflectType(suppliedType)));

    targetParameters.forEach(p -> classDefinition.addField(a(PRIVATE, FINAL), p.name,
            type(Supplier.class, p.parameterizedBoxedType)));
    Map<String, FieldDefinition> classFieldDefinitionMap = classDefinition.getFields().stream()
            .collect(toImmutableMap(f -> f.getName(), f -> f));

    compileConstructor(classDefinition, classFieldDefinitionMap, targetParameters);
    compileGetter(classDefinition, classFieldDefinitionMap, target, targetParameters);

    Class clazz = defineClass(classDefinition, Object.class, ImmutableMap.of(),
            new DynamicClassLoader(parentClassLoader));
    return clazz;
}