/** * Sort possible goods types according to potential. * * @param unitType The {@code UnitType} to do the work. * @param owner the {@code Player} owning the unit. * @return A list of goods, highest potential production first. */ public List<AbstractGoods> getSortedPotential(UnitType unitType, Player owner) { // Defend against calls while partially read. if (getType() == null) return Collections.<AbstractGoods>emptyList(); final ToIntFunction<GoodsType> productionMapper = cacheInt(gt -> getPotentialProduction(gt, unitType)); final Predicate<GoodsType> productionPred = gt -> productionMapper.applyAsInt(gt) > 0; final Function<GoodsType, AbstractGoods> goodsMapper = gt -> new AbstractGoods(gt, productionMapper.applyAsInt(gt)); final Comparator<AbstractGoods> goodsComp = ((owner == null || owner.getMarket() == null) ? AbstractGoods.descendingAmountComparator : owner.getMarket().getSalePriceComparator()); // It is necessary to consider all farmed goods, since the // tile might have a resource that produces goods not produced // by the tile type. return transform(getSpecification().getFarmedGoodsTypeList(), productionPred, goodsMapper, goodsComp); }
@Override public Mono<Double> getAveAge() { ToIntFunction<Employee> sizeEmpArr = (e) -> { System.out.println("flux:toIntFunction task executor: " + Thread.currentThread().getName()); System.out.println("flux:toIntFunction task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); return e.getAge(); }; Callable<Double> task = () ->{ System.out.println("flux:callable task executor: " + Thread.currentThread().getName()); System.out.println("flux:callable task executor login: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal()); return employeeDaoImpl.getEmployees().stream() .mapToInt(sizeEmpArr) .average() .getAsDouble(); }; Mono<Double> aveAge= Mono.fromCallable(task); return aveAge; }
private static int testApacheServer(List<MethodInvocationFilter> filters) throws Exception { ScribeService scribeService = new ScribeService(); TProcessor processor = new scribe.Processor<>(scribeService); int invocationCount = 0; for (boolean secure : ImmutableList.of(true, false)) { for (Transport transport : Transport.values()) { for (Protocol protocol : Protocol.values()) { invocationCount += testApacheServer(secure, transport, protocol, processor, ImmutableList.<ToIntFunction<HostAndPort>>builder() .addAll(legacyApacheThriftTestClients(filters, transport, protocol, secure)) .addAll(driftNettyTestClients(filters, transport, protocol, secure)) .addAll(apacheThriftTestClients(filters, transport, protocol, secure)) .build()); } } } assertEquals(scribeService.getMessages(), newArrayList(concat(nCopies(invocationCount, MESSAGES)))); return invocationCount; }
private static <A extends Annotation, E extends Throwable> int callInt( AnnotationInterceptor<A> annotationInterceptor, int annotationId, A[] annotations, CallContext context, Arguments currentArguments, ToIntFunction<Arguments> terminalInvokeFun) throws E { A annotation = annotations[annotationId]; if (annotationId == annotations.length - 1) { // last annotation return annotationInterceptor.onCall(annotation, context, new SimpleIntInterceptionHandler(currentArguments, terminalInvokeFun)); } else { return annotationInterceptor.onCall(annotation, context, new SimpleIntInterceptionHandler(currentArguments, (args) -> callInt(annotationInterceptor, annotationId + 1, annotations, context, args, terminalInvokeFun))); } }
/** * Maps the specified column to ints using the mapper function provided * @param frame the frame reference * @param colKey the column key to apply mapper function to * @param mapper the mapper function to apply * @return the newly created content, with update column */ @SuppressWarnings("unchecked") final XDataFrameContent<R,C> mapToInts(XDataFrame<R,C> frame, C colKey, ToIntFunction<DataFrameValue<R,C>> mapper) { if (!isColumnStore()) { throw new DataFrameException("Cannot apply columns of a transposed DataFrame"); } else { final int rowCount = rowKeys.size(); final boolean parallel = frame.isParallel(); final int colIndex = colKeys.getIndexForKey(colKey); return new XDataFrameContent<>(rowKeys, colKeys, true, Mapper.apply(data, parallel, (index, array) -> { if (index != colIndex) { return array; } else { final int colOrdinal = colKeys.getOrdinalForKey(colKey); final Array<?> targetValues = Array.of(Integer.class, array.length()); final Cursor cursor = new Cursor(frame, rowKeys.isEmpty() ? -1 : 0, colOrdinal); for (int i = 0; i < rowCount; ++i) { cursor.atRowOrdinal(i); final int value = mapper.applyAsInt(cursor); targetValues.setInt(cursor.rowIndex, value); } return targetValues; } })); } }
private int getOrdinal(ResourcePoolEntry resource) { String path = resource.path(); Integer value = orderedPaths.get(stripModule(path)); if (value != null) { return value; } for (ToIntFunction<String> function : filters) { int ordinal = function.applyAsInt(path); if (ordinal != Integer.MAX_VALUE) { return ordinal; } } return Integer.MAX_VALUE; }
@Override public final IntStream mapToInt(ToIntFunction<? super P_OUT> mapper) { Objects.requireNonNull(mapper); return new IntPipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE, StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) { @Override Sink<P_OUT> opWrapSink(int flags, Sink<Integer> sink) { return new Sink.ChainedReference<P_OUT, Integer>(sink) { @Override public void accept(P_OUT u) { downstream.accept(mapper.applyAsInt(u)); } }; } }; }
public double getParallelAverageAge(){ ToIntFunction<Employee> sizeEmpArr = (e) -> { System.out.println("Thread: " + Thread.currentThread().getName()); return e.getAge(); }; return employeeDaoImpl.getEmployees().parallelStream().mapToInt(sizeEmpArr).average().getAsDouble(); }
public double getAverageMoreProcessors() throws InterruptedException, ExecutionException{ ToIntFunction<Employee> sizeEmpArr = (e) -> { System.out.println("Thread: " + Thread.currentThread().getName()); return e.getAge(); }; Callable<Double> task = () -> employeeDaoImpl.getEmployees().stream().mapToInt(sizeEmpArr).average().getAsDouble(); ForkJoinPool forkJoinPool = new ForkJoinPool(4); double avgAge = forkJoinPool.submit(task).get(); return avgAge; }
private static int testProcessor(TProcessor processor, List<ToIntFunction<HostAndPort>> clients) throws Exception { try (TServerSocket serverTransport = new TServerSocket(0)) { TProtocolFactory protocolFactory = new Factory(); TTransportFactory transportFactory = new TFramedTransport.Factory(); TServer server = new TSimpleServer(new Args(serverTransport) .protocolFactory(protocolFactory) .transportFactory(transportFactory) .processor(processor)); Thread serverThread = new Thread(server::serve); try { serverThread.start(); int localPort = serverTransport.getServerSocket().getLocalPort(); HostAndPort address = HostAndPort.fromParts("localhost", localPort); int sum = 0; for (ToIntFunction<HostAndPort> client : clients) { sum += client.applyAsInt(address); } return sum; } finally { server.stop(); serverThread.interrupt(); } } }
private static int testProcessor(TProcessor processor, List<ToIntFunction<HostAndPort>> clients) throws Exception { try (TServerSocket serverTransport = new TServerSocket(0)) { TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); TTransportFactory transportFactory = new TFramedTransport.Factory(); TServer server = new TSimpleServer(new Args(serverTransport) .protocolFactory(protocolFactory) .transportFactory(transportFactory) .processor(processor)); Thread serverThread = new Thread(server::serve); try { serverThread.start(); int localPort = serverTransport.getServerSocket().getLocalPort(); HostAndPort address = HostAndPort.fromParts("localhost", localPort); int sum = 0; for (ToIntFunction<HostAndPort> client : clients) { sum += client.applyAsInt(address); } return sum; } finally { server.stop(); serverThread.interrupt(); } } }
public static List<ToIntFunction<HostAndPort>> driftNettyTestClients(List<MethodInvocationFilter> filters, Transport transport, Protocol protocol, boolean secure) { return ImmutableList.of( address -> logNettyDriftClient(address, DRIFT_MESSAGES, filters, transport, protocol, secure), address -> logNettyStaticDriftClient(address, DRIFT_MESSAGES, filters, transport, protocol, secure), address -> logNettyDriftClientAsync(address, DRIFT_MESSAGES, filters, transport, protocol, secure), address -> logNettyClientBinder(address, DRIFT_MESSAGES, filters, transport, protocol, secure)); }
public static List<ToIntFunction<HostAndPort>> apacheThriftTestClients(List<MethodInvocationFilter> filters, Transport transport, Protocol protocol, boolean secure) { return ImmutableList.of( address -> logApacheThriftDriftClient(address, DRIFT_MESSAGES, filters, transport, protocol, secure), address -> logApacheThriftStaticDriftClient(address, DRIFT_MESSAGES, filters, transport, protocol, secure), address -> logApacheThriftDriftClientAsync(address, DRIFT_MESSAGES, filters, transport, protocol, secure), address -> logApacheThriftClientBinder(address, DRIFT_MESSAGES, filters, transport, protocol, secure)); }
protected DoubleTestData(String name, I state, Function<I, DoubleStream> streamFn, Function<I, DoubleStream> parStreamFn, Function<I, Spliterator.OfDouble> splitrFn, ToIntFunction<I> sizeFn) { super(name, StreamShape.DOUBLE_VALUE, state, streamFn, parStreamFn, splitrFn, sizeFn); }
public void testIntComparator() { Thing[] things = new Thing[intValues.length]; for (int i=0; i<intValues.length; i++) things[i] = new Thing(intValues[i], 0L, 0.0, null); Comparator<Thing> comp = Comparator.comparingInt(new ToIntFunction<Thing>() { @Override public int applyAsInt(Thing thing) { return thing.getIntField(); } }); assertComparisons(things, comp, comparisons); }
protected LongTestData(String name, I state, Function<I, LongStream> streamFn, Function<I, LongStream> parStreamFn, Function<I, Spliterator.OfLong> splitrFn, ToIntFunction<I> sizeFn) { super(name, StreamShape.LONG_VALUE, state, streamFn, parStreamFn, splitrFn, sizeFn); }
private static <E extends Throwable> int callInt(int interceptorId, Interceptor[] interceptors, CallContext context, Arguments currentArguments, ToIntFunction<Arguments> terminalInvokeFun) throws E { Interceptor interceptor = interceptors[interceptorId]; if (interceptorId == interceptors.length - 1) { // last interceptor return interceptor.onCall(context, new SimpleIntInterceptionHandler(currentArguments, terminalInvokeFun)); } else { return interceptor.onCall(context, new SimpleIntInterceptionHandler(currentArguments, (args) -> callInt(interceptorId + 1, interceptors, context, args, terminalInvokeFun))); } }
/** * Is it a good idea to produce a goods type at this work location * using a better unit type? * * @param unit The {@code Unit} that is doing the job at * present, which may be null if none is at work. * @param productionType The {@code ProductionType} to use. * @param goodsType The {@code GoodsType} to produce. * @return A {@code Suggestion} for a better worker, or null if * improvement is not worthwhile. */ private Suggestion getSuggestion(Unit unit, ProductionType productionType, GoodsType goodsType) { // Check first if there is space. if (((unit == null || !contains(unit)) && isFull()) || productionType == null || goodsType == null) return null; final Specification spec = getSpecification(); final Player owner = getOwner(); final UnitType expert = spec.getExpertForProducing(goodsType); // Require there be a better unit to do this work, and that it // would actually improve production. final UnitType better = (expert != null) ? expert : spec.getDefaultUnitType(owner); if (unit != null && better == unit.getType()) return null; int delta = getPotentialProduction(goodsType, better); if (unit != null) { delta -= getPotentialProduction(goodsType, unit.getType()); } // Do we have a chance of satisfying the inputs? final ToIntFunction<AbstractGoods> prod = ag -> getColony().getNetProductionOf(ag.getType()); delta = Math.min(delta, min(productionType.getInputs(), prod)); if (delta <= 0) return null; // Is the production actually a good idea? Not if we are independent // and have maximized liberty, or for immigration. if (owner.getPlayerType() == Player.PlayerType.INDEPENDENT && ((goodsType.isLibertyType() && getColony().getSoL() >= 100) || goodsType.isImmigrationType())) return null; final Boolean ok = goodSuggestionCheck(better,unit, goodsType); return (!ok) ? null : new Suggestion(this, (unit == null) ? null : unit.getType(), better, goodsType, delta); }
/** * Returns the net production of the given GoodsType adjusted by * the possible consumption of BuildQueues. * * @param goodsType a {@code GoodsType} value * @return an {@code int} value */ public int getAdjustedNetProductionOf(final GoodsType goodsType) { final ToIntFunction<BuildQueue> consumes = q -> { ProductionInfo pi = productionCache.getProductionInfo(q); return (pi == null) ? 0 : AbstractGoods.getCount(goodsType, pi.getConsumption()); }; return productionCache.getNetProductionOf(goodsType) + sum(Stream.of(buildQueue, populationQueue), consumes); }
/** * Chooses a type of goods for some of the natives in a settlement * to manufacture. * Simple rule: choose the refined goods that is the greatest shortage * for which there is a surplus of the raw material. * * @return A {@code GoodsType} to manufacture, or null if * none suitable. */ private GoodsType goodsToMake() { final ToIntFunction<GoodsType> deficit = cacheInt(gt -> getWantedGoodsAmount(gt) - getGoodsCount(gt)); final Predicate<GoodsType> goodsPred = gt -> gt.isRawMaterial() && gt.getOutputType() != null && !gt.getOutputType().isBreedable() && gt.getOutputType().isStorable() && deficit.applyAsInt(gt) < 0 && deficit.applyAsInt(gt.getOutputType()) > 0; final Comparator<GoodsType> comp = Comparator.comparingInt(deficit); return maximize(getSpecification().getGoodsTypeList(), goodsPred, comp); }
public final void compute() { final ToIntFunction<? super V> transformer; final IntBinaryOperator reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { int r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceValuesToIntTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork(); } for (Node<K,V> p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.val)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V> t = (MapReduceValuesToIntTask<K,V>)c, s = t.rights; while (s != null) { t.result = reducer.applyAsInt(t.result, s.result); s = t.rights = s.nextRight; } } } }
/** * Creates an INTEGER mapper that wraps to function provided * @param function the function to wrap * @param <I> the input type * @return the newly created mapper */ public static <I,O> Function1<I,Integer> toInt(ToIntFunction<I> function) { return new Function1<I,Integer>(FunctionStyle.INTEGER) { @Override public final int applyAsInt(I value) { return function.applyAsInt(value); } }; }
public static void squareRootAndRemainder() { ToIntFunction<BigInteger> g = (n) -> { int failCount = 0; BigInteger n2 = n.pow(2); // square root of n^2 -> n BigInteger[] actual = n2.sqrtAndRemainder(); failCount += checkResult(n, actual[0], "sqrtAndRemainder()[0]"); failCount += checkResult(BigInteger.ZERO, actual[1], "sqrtAndRemainder()[1]"); // square root of n^2 + 1 -> n BigInteger n2up = n2.add(BigInteger.ONE); actual = n2up.sqrtAndRemainder(); failCount += checkResult(n, actual[0], "sqrtAndRemainder()[0]"); failCount += checkResult(BigInteger.ONE, actual[1], "sqrtAndRemainder()[1]"); // square root of (n + 1)^2 - 1 -> n BigInteger up = n.add(BigInteger.ONE).pow(2).subtract(BigInteger.ONE); actual = up.sqrtAndRemainder(); failCount += checkResult(n, actual[0], "sqrtAndRemainder()[0]"); BigInteger r = up.subtract(n2); failCount += checkResult(r, actual[1], "sqrtAndRemainder()[1]"); return failCount; }; IntStream bits = random.ints(SIZE, 3, Short.MAX_VALUE); report("sqrtAndRemainder", bits.mapToObj(x -> BigInteger.valueOf(x)).collect(Collectors.summingInt(g))); }
protected RefTestData(String name, I state, Function<I, Stream<T>> streamFn, Function<I, Stream<T>> parStreamFn, Function<I, Spliterator<T>> splitrFn, ToIntFunction<I> sizeFn) { super(name, StreamShape.REFERENCE, state, streamFn, parStreamFn, splitrFn, sizeFn); }
@Override public void configure(Map<String, String> config) { List<String> patterns = Utils.parseList(config.get(NAME)); int ordinal = 0; for (String pattern : patterns) { if (pattern.startsWith("@")) { File file = new File(pattern.substring(1)); if (file.exists()) { List<String> lines; try { lines = Files.readAllLines(file.toPath()); } catch (IOException ex) { throw new UncheckedIOException(ex); } for (String line : lines) { if (!line.startsWith("#")) { orderedPaths.put(line + ".class", ordinal++); } } } } else { final int result = ordinal++; final PathMatcher matcher = Utils.getPathMatcher(JRT_FILE_SYSTEM, pattern); ToIntFunction<String> function = (path)-> matcher.matches(JRT_FILE_SYSTEM.getPath(path)) ? result : Integer.MAX_VALUE; filters.add(function); } } }
MapReduceKeysToIntTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceKeysToIntTask<K,V> nextRight, ToIntFunction<? super K> transformer, int basis, IntBinaryOperator reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; }
public final void compute() { final ToIntFunction<? super K> transformer; final IntBinaryOperator reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { int r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceKeysToIntTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork(); } for (Node<K,V> p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p.key)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V> t = (MapReduceKeysToIntTask<K,V>)c, s = t.rights; while (s != null) { t.result = reducer.applyAsInt(t.result, s.result); s = t.rights = s.nextRight; } } } }
MapReduceValuesToIntTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceValuesToIntTask<K,V> nextRight, ToIntFunction<? super V> transformer, int basis, IntBinaryOperator reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; }
public final void compute() { final ToIntFunction<Map.Entry<K,V>> transformer; final IntBinaryOperator reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { int r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceEntriesToIntTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork(); } for (Node<K,V> p; (p = advance()) != null; ) r = reducer.applyAsInt(r, transformer.applyAsInt(p)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V> t = (MapReduceEntriesToIntTask<K,V>)c, s = t.rights; while (s != null) { t.result = reducer.applyAsInt(t.result, s.result); s = t.rights = s.nextRight; } } } }
@Override public final Array<Integer> mapToInts(ToIntFunction<ArrayValue<T>> mapper) { final Array<Integer> result = Array.of(Integer.class, length()); final MapValues<Integer> action = new MapValues<>(0, length() - 1, mapper, result); if (isParallel()) { ForkJoinPool.commonPool().invoke(action); return result; } else { action.compute(); return result; } }
MapReduceEntriesToIntTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceEntriesToIntTask<K,V> nextRight, ToIntFunction<Map.Entry<K,V>> transformer, int basis, IntBinaryOperator reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; }
AbstractTestData(String name, StreamShape shape, T_STATE state, Function<T_STATE, S> streamFn, Function<T_STATE, S> parStreamFn, Function<T_STATE, T_SPLITR> splitrFn, ToIntFunction<T_STATE> sizeFn) { this.name = name; this.shape = shape; this.state = state; this.streamFn = streamFn; this.parStreamFn = parStreamFn; this.splitrFn = splitrFn; this.sizeFn = sizeFn; }