static void testRandomized(BiFunction<int[], Integer, List<Integer>> solution) { Random rnd = new Random(0); for (int test = 0; test < 20; test++) { int[] arr = new int[rnd.nextInt(MAX_ITEMS) + 1]; for (int i = 0; i < arr.length; i++) { arr[i] = rnd.nextInt(MAX_VALUE); } for (int j = 0; j < 5; j++) { int target = randomDifference(arr, 0, arr.length - 1, rnd); System.out.println("Array length: " + arr.length); System.out.println("Target: " + target); System.out.println("Array:"); System.out.println(Arrays.toString(arr).replaceAll("[\\[\\],]", " ").trim()); List<Integer> subtractcionOrder = solution.apply(arr, target); verifySolution(arr, target, subtractcionOrder); System.out.println("Result: " + subtractcionOrder.toString().replaceAll("[\\[\\],]", " ").trim()); System.out.println(); } } }
public static <R,P1, P2> R test2(String name, R receiver, BiFunction<P1, P2, R> m, P1 arg1, P2 arg2, Class<? extends Exception> ...ex) { try { R result = m.apply(arg1, arg2); if (!shouldFail(ex)) { System.out.println("success: " + name + "(" + arg1 + ", " + arg2 + ")"); return result; } else { throw new AssertionError("Expected " + expectedNames(ex) + " not raised for " + name + "(" + arg1 +", " + arg2 + ")"); } } catch (Exception x) { if (!isExpected(x, ex)) { throw x; } else { System.out.println("success: " + name + "(" + arg1 + ", " + arg2 + ") - Got expected exception: " + x); return receiver; } } }
@Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Node<K,V>[] tab; if (function == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) { e.value = function.apply(e.key, e.value); } } if (modCount != mc) throw new ConcurrentModificationException(); } }
/** * Applies the function {@code f} to each element of the stream. * The function {@code f} is called with the index (in {@code ys}) of the * element to map (first argument) and with the element itself (second * argument). That is: {@code map(f,[v,w,...]) = [f(0,v),f(1,w),...]}. * For example (pseudo code) if {@code f(i,x) = i+x} then * {@code map(f,[1,2,3]) = [1,3,5]}. * @param <Y> any type. * @param <Z> any type. * @param f turns an index and a {@code Y} into a {@code Z}. * @param ys the list to map. * @return a new list with the mapped elements. * @throws NullPointerException if any argument is {@code null}. */ public static <Y, Z> Stream<Z> map(BiFunction<Integer, Y, Z> f, Stream<Y> ys) { requireNonNull(f, "f"); requireNonNull(ys, "ys"); Iterator<Y> iy = ys.iterator(); List<Z> zs = new ArrayList<>(); int index = 0; while (iy.hasNext()) { zs.add(f.apply(index++, iy.next())); } return zs.stream(); }
@Test public void executePreparedStatement() throws CheckedFutureException { final Long result = 413L; final String command = "command"; final Integer set = 223; final PreparedStatement ps = PreparedStatement.apply(command).setInteger(set); final Supplier<Connection> sup = new ConnectionSupplier() { @Override BiFunction<String, List<Value<?>>, Exchange<Long>> extendedExecuteExchange() { return (c, b) -> { assertEquals(command, c); assertEquals(Arrays.asList(new IntegerValue(set)), b); return Exchange.value(result); }; } }; assertEquals(result, sup.get().execute(ps).get(timeout)); }
/** * @param first * @param second * @param function * @param <F> * @param <S> * @param <T> * @return */ public static <F, S, T> List<T> zipper( final List<F> first, final List<S> second, final BiFunction<F, S, T> function ) { final List<T> result = new ArrayList<>(); Fn.itList(first, (key, index) -> { final S value = getEnsure(second, index); final T merged = function.apply(key, value); if (null != merged) { result.add(merged); } }); return result; }
public JsonArrayMatcher(T vnetEntityValue, Function<T, String> getKey1, BiPredicate<T, JsonObject> checkKey1, List<String> jsonFieldNames1, BiFunction<T, String, String> getValue1) { vnetEntity = vnetEntityValue; getKey = getKey1; checkKey = checkKey1; jsonFieldNames = jsonFieldNames1; getValue = getValue1; }
/** * Constructs a {@code TerminalOp} that implements a functional reduce on * reference values. * * @param <T> the type of the input elements * @param <U> the type of the result * @param seed the identity element for the reduction * @param reducer the accumulating function that incorporates an additional * input element into the result * @param combiner the combining function that combines two intermediate * results * @return a {@code TerminalOp} implementing the reduction */ public static <T, U> TerminalOp<T, U> makeRef(U seed, BiFunction<U, ? super T, U> reducer, BinaryOperator<U> combiner) { Objects.requireNonNull(reducer); Objects.requireNonNull(combiner); class ReducingSink extends Box<U> implements AccumulatingSink<T, U, ReducingSink> { @Override public void begin(long size) { state = seed; } @Override public void accept(T t) { state = reducer.apply(state, t); } @Override public void combine(ReducingSink other) { state = combiner.apply(state, other.state); } } return new ReduceOp<T, U, ReducingSink>(StreamShape.REFERENCE) { @Override public ReducingSink makeSink() { return new ReducingSink(); } }; }
private BiFunction<List<RangeStatistics>, RangeStatistics, List<RangeStatistics>> accumulatingFunction() { return (rangeStatistics, rangeStatistic) -> { List<RangeStatistics> result = new ArrayList<>(rangeStatistics); addOrReplace(rangeStatistics, result, rangeStatistic); return result; }; }
@Test(dataProvider = "arrayTypesProvider") public void testArray(ArrayType<?> arrayType) { BiFunction<ArrayType<?>, Integer, Object> constructor = (at, s) -> { Object a = at.construct(s); for (int x = 0; x < s; x++) { at.set(a, x, x % 8); } return a; }; BiFunction<ArrayType<?>, Object, Object> cloner = (at, a) -> constructor.apply(at, Array.getLength(a)); testArrayType(arrayType, constructor, cloner); }
@Before public void setUp() throws Exception { clusterCommunicator = createNiceMock(ClusterCommunicationService.class); clusterCommunicator.addSubscriber(anyObject(MessageSubject.class), anyObject(ClusterMessageHandler.class), anyObject(ExecutorService.class)); expectLastCall().anyTimes(); replay(clusterCommunicator); ClusterService clusterService = new TestClusterService(); testGossipDeviceStore = new TestGossipDeviceStore(deviceClockService, clusterService, clusterCommunicator); testGossipDeviceStore.mastershipService = new TestMastershipService(); ecMapBuilder = createNiceMock(EventuallyConsistentMapBuilder.class); expect(ecMapBuilder.withName(anyObject(String.class))).andReturn(ecMapBuilder).anyTimes(); expect(ecMapBuilder.withSerializer(anyObject(KryoNamespace.Builder.class))).andReturn(ecMapBuilder).anyTimes(); expect(ecMapBuilder.withAntiEntropyPeriod(5, TimeUnit.SECONDS)).andReturn(ecMapBuilder).anyTimes(); expect(ecMapBuilder.withTimestampProvider(anyObject(BiFunction.class))).andReturn(ecMapBuilder).anyTimes(); expect(ecMapBuilder.withTombstonesDisabled()).andReturn(ecMapBuilder).anyTimes(); ecMap = createNiceMock(EventuallyConsistentMap.class); expect(ecMapBuilder.build()).andReturn(ecMap).anyTimes(); testStorageService = createNiceMock(StorageService.class); expect(testStorageService.eventuallyConsistentMapBuilder()).andReturn(ecMapBuilder).anyTimes(); replay(testStorageService, ecMapBuilder, ecMap); testGossipDeviceStore.storageService = testStorageService; testGossipDeviceStore.deviceClockService = deviceClockService; gossipDeviceStore = testGossipDeviceStore; gossipDeviceStore.activate(); deviceStore = gossipDeviceStore; verify(clusterCommunicator); reset(clusterCommunicator); }
/** * Converts the provided bifunction into a regular BiFunction, where any thrown exceptions * are wrapped in a RuntimeException */ static <A, B, R, X extends Exception> BiFunction<A, B, R> throwingRuntime(ThrowingBiFunction<A, B, R, X> f) { return (a, b) -> { try { return f.apply(a, b); } catch (Exception ex) { throw new RuntimeException(ex); } }; }
public Future<Void> asyncRecoverReplica(IndexShard replica, BiFunction<IndexShard, DiscoveryNode, RecoveryTarget> targetSupplier) throws IOException { FutureTask<Void> task = new FutureTask<>(() -> { recoverReplica(replica, targetSupplier); return null; }); threadPool.generic().execute(task); return task; }
UninstallNpmDependencyButtonListener(BiFunction<Collection<String>, IProgressMonitor, IStatus> uninstallAction, Supplier<IInputValidator> validator, StatusHelper statusHelper, Supplier<String> initalValue) { this.statusHelper = statusHelper; this.validator = validator; this.uninstallAction = uninstallAction; this.initalValue = initalValue; }
public Vector3d pairOp(Vector3d other, BiFunction<Double, Double, Double> function) { setX(function.apply(x(), other.x())); setY(function.apply(y(), other.y())); setZ(function.apply(z(), other.z())); return this; }
SymmetricEncryptionAlgorithm(final KeyGenerator keyGenerator, final BiFunction<SecretKey, byte[], byte[]> encryptionFunction, final BiFunction<byte[], byte[], byte[]> decryptionFunction) { this.keyGenerator = keyGenerator; this.encryptionFunction = encryptionFunction; this.decryptionFunction = decryptionFunction; }
static void testRandomized1(BiFunction<Road[], Integer, Integer> tested) { Random rnd = new Random(1); for (int i = 0; i < 100; i++) { int citiesCount = rnd.nextInt(10) + 1; Road[] roads = new Road[Math.min(10, citiesCount + rnd.nextInt(11 - citiesCount))]; for (int j = 0; j < roads.length; j++) { roads[j] = new Road(rnd.nextInt(citiesCount) + 1, rnd.nextInt(citiesCount) + 1, rnd.nextInt(citiesCount) + 1, rnd.nextInt(101), rnd .nextInt(101)); } compareResults(roads, citiesCount, tested); } }
/** * @param start Beginning of iteration (inclusive) * @param finish End of iteration (exclusive - depends on the {@code sliceGenerator} * @param sliceSize Slice size. * @param sliceGenerator A BiFunction used to get the next slicing iterator. Called with the next start and overall finish. */ public BatchingIterator(X start, X finish, int sliceSize, BiFunction<X, X, Iterator<X>> sliceGenerator ) { if ( sliceSize <= 0 ) throw new IllegalArgumentException("Slice size must be positive"); this.start = requireNonNull(start, "Argument start"); this.nextStart = start; this.finish = requireNonNull(finish, "Argument finish"); this.sliceSize = sliceSize; this.sliceGenerator = requireNonNull(sliceGenerator, "Argument sliceGenerator"); this.current = null; }
@Override public CompletableFuture<Versioned<V>> computeIf(K key, Predicate<? super V> condition, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { final MeteringAgent.Context timer = monitor.startTimer(COMPUTE_IF); return super.computeIf(key, condition, remappingFunction) .whenComplete((r, e) -> timer.stop(e)); }
AbstractFilterValue(final KeyParser keyParser, final BiFunction<Object, Object, Condition> conditionCreator, final boolean throwOnMissingKeysFound) { this.conditionSupplier = null; this.keyParser = Objects.requireNonNull(keyParser); this.conditionCreator = null; this.conditionCreator2 = Objects.requireNonNull(conditionCreator); this.throwOnMissingKeysFound = throwOnMissingKeysFound; }
/** * Interpose a consumer that asserts it is called at most N times. */ <T, S extends BaseStream<T, S>, R> S assertNCallsOnly(S s, BiFunction<S, Consumer<T>, S> pf, int n) { AtomicInteger boxedInt = new AtomicInteger(); return pf.apply(s, i -> { assertFalse(boxedInt.incrementAndGet() > n, "Intermediate op called more than " + n + " time(s)"); }); }
/** * Based on username and JsonObject parameter -> returns database movie history results. */ private BiFunction<String, JsonObject, Object> getDatabaseMovieHistory() { return (user, json) -> { json.remove("results"); json.getJsonArray("rows").stream() .map(obj -> (JsonObject) obj) .forEach(jsonObj -> jsonObj .put("WasCinema", getCinema(jsonObj.getBoolean("WasCinema"))) .put("Start", getNormalDTFromDB(jsonObj.getString("Start"), LONG_DATE))); return json; }; }
private static void collectStartupExtenderArgs( @NonNull final Context ctx, @NonNull final BiFunction<String,String,Void> consummer) { StringBuilder b = new StringBuilder(); for (String arg : runJvmargsIde(ctx)) { b.append(' ').append(arg); } if (b.length() > 0) { consummer.apply(ProjectProperties.RUN_JVM_ARGS_IDE, b.toString()); } }
public final void compute() { final BiFunction<? super K, ? super V, ? extends U> searchFunction; final AtomicReference<U> result; if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) { for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { if (result.get() != null) return; addToPendingCount(1); new SearchMappingsTask<K,V,U> (this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork(); } while (result.get() == null) { U u; Node<K,V> p; if ((p = advance()) == null) { propagateCompletion(); break; } if ((u = searchFunction.apply(p.key, p.val)) != null) { if (result.compareAndSet(null, u)) quietlyCompleteRoot(); break; } } } }
public final void compute() { final Function<Map.Entry<K,V>, ? extends U> transformer; final BiFunction<? super U, ? super U, ? extends U> reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceEntriesTask<K,V,U> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork(); } U r = null; for (Node<K,V> p; (p = advance()) != null; ) { U u; if ((u = transformer.apply(p)) != null) r = (r == null) ? u : reducer.apply(r, u); } result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U> t = (MapReduceEntriesTask<K,V,U>)c, s = t.rights; while (s != null) { U tr, sr; if ((sr = s.result) != null) t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr)); s = t.rights = s.nextRight; } } } }
static void testBuiltIn() { java.util.function.Function<String, String> foo = (x) -> x.toString(); BiFunction<String, Object, String> bar = (x, y) -> x.toString() + y.toString(); Function<String, Object> foo2 = (x) -> null; // java.util.Function is unnanotated Function<String, Object> foo3 = (x) -> { return null; }; }
ReduceValuesTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, ReduceValuesTask<K,V> nextRight, BiFunction<? super V, ? super V, ? extends V> reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.reducer = reducer; }
public static Image map(MultiResolutionImage mrImage, Function<Image, Image> mapper) { if (mrImage instanceof MultiResolutionToolkitImage) { MultiResolutionToolkitImage mrtImage = (MultiResolutionToolkitImage) mrImage; return MultiResolutionToolkitImage.map(mrtImage, mapper); } BiFunction<Integer, Integer, Image> sizeMapper = (w, h) -> mapper.apply(mrImage.getResolutionVariant(w, h)); if (mrImage instanceof MultiResolutionCachedImage) { MultiResolutionCachedImage mrcImage = (MultiResolutionCachedImage) mrImage; return new MultiResolutionCachedImage(mrcImage.baseImageWidth, mrcImage.baseImageHeight, mrcImage.sizes, sizeMapper, false); } Image image = (Image) mrImage; int width = image.getWidth(null); int height = image.getHeight(null); return new MultiResolutionCachedImage(width, height, sizeMapper); }
public final void compute() { final Function<? super V, ? extends U> transformer; final BiFunction<? super U, ? super U, ? extends U> reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceValuesTask<K,V,U> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, reducer)).fork(); } U r = null; for (Node<K,V> p; (p = advance()) != null; ) { U u; if ((u = transformer.apply(p.val)) != null) r = (r == null) ? u : reducer.apply(r, u); } result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U> t = (MapReduceValuesTask<K,V,U>)c, s = t.rights; while (s != null) { U tr, sr; if ((sr = s.result) != null) t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr)); s = t.rights = s.nextRight; } } } }
/** * Compare values by null. * @param left left value. * @param right right value. * @param compare if left and right not null then compare by function. * @return 1, 0, -1. */ public int compareIfNull(User left, User right, BiFunction<User, User, Integer> compare) { int rsl; if (left != null && right != null) { rsl = compare.apply(left, right); } else if (left != null) { rsl = -1; } else if (right != null) { rsl = 1; } else { rsl = 0; } return rsl; }
/** * {@inheritDoc} * * <p>This method will, on a best-effort basis, throw a * {@link java.util.ConcurrentModificationException} if the remapping * function modified this map during computation. * * @throws ConcurrentModificationException if it is detected that the * remapping function modified this map */ @Override public synchronized V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>)tab[index]; for (Entry<K,V> prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash && e.key.equals(key)) { int mc = modCount; V newValue = remappingFunction.apply(key, e.value); if (mc != modCount) { throw new ConcurrentModificationException(); } if (newValue == null) { if (prev != null) { prev.next = e.next; } else { tab[index] = e.next; } modCount = mc + 1; count--; } else { e.value = newValue; } return newValue; } } return null; }
private <U,V> CompletableFuture<V> biApplyStage( Executor e, CompletionStage<U> o, BiFunction<? super T,? super U,? extends V> f) { CompletableFuture<U> b; if (f == null || (b = o.toCompletableFuture()) == null) throw new NullPointerException(); CompletableFuture<V> d = new CompletableFuture<V>(); if (e != null || !d.biApply(this, b, f, null)) { BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f); bipush(b, c); c.tryFire(SYNC); } return d; }
@SuppressWarnings("unchecked") @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { for (int i = 0; i < totalEntries; i++) { Object entryKey = getKey(i); if (entryKey != null) { Object newValue = function.apply((K) entryKey, (V) getValue(i)); setValue(i, newValue); } } }
@Override public synchronized void setHandshakeApplicationProtocolSelector( BiFunction<SSLEngine, List<String>, String> selector) { applicationProtocolSelector = selector; if ((handshaker != null) && !handshaker.activated()) { handshaker.setApplicationProtocolSelectorSSLEngine(selector); } }
ReduceEntriesTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, ReduceEntriesTask<K,V> nextRight, BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.reducer = reducer; }
@Override public synchronized V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>)tab[index]; for (Entry<K,V> prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash && e.key.equals(key)) { V newValue = remappingFunction.apply(e.value, value); if (newValue == null) { modCount++; if (prev != null) { prev.next = e.next; } else { tab[index] = e.next; } count--; } else { e.value = newValue; } return newValue; } } if (value != null) { addEntry(hash, key, value, index); } return value; }
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> function) { stopwatch.start(); V previousValue; try { previousValue = oldValue.waitForValue(); } catch (ExecutionException e) { previousValue = null; } V newValue = function.apply(key, previousValue); this.set(newValue); return newValue; }
private static <T> void testComputeIfPresent(Map<T, T> map, String desc, T[] keys, BiFunction<T, T, T> mappingFunction) { // remove a third of the keys // call testComputeIfPresent for all keys[] // removed keys should remain absent, even keys should be mapped to $RESULT // no value from keys[] should be in map T funcResult = mappingFunction.apply(keys[0], keys[0]); int expectedSize1 = 0; removeThirdKeys(map, keys); for (int i = 0; i < keys.length; i++) { T retVal = map.computeIfPresent(keys[i], mappingFunction); if (i % 3 != 2) { // key present if (funcResult == null) { // was removed assertFalse(map.containsKey(keys[i]), String.format("replaceIfMapped: containsKey(%s[%d])", desc, i)); } else { // value was replaced assertTrue(map.containsKey(keys[i]), String.format("replaceIfMapped: containsKey(%s[%d])", desc, i)); expectedSize1++; } assertEquals(retVal, funcResult, String.format("computeIfPresent: retVal(%s[%s])", desc, i)); assertEquals(funcResult, map.get(keys[i]), String.format("replaceIfMapped: get(%s[%d])", desc, i)); } else { // odd: was removed, should not be replaced assertNull(retVal, String.format("replaceIfMapped: retVal(%s[%d])", desc, i)); assertNull(map.get(keys[i]), String.format("replaceIfMapped: get(%s[%d])", desc, i)); assertFalse(map.containsKey(keys[i]), String.format("replaceIfMapped: containsKey(%s[%d])", desc, i)); } assertFalse(map.containsValue(keys[i]), String.format("replaceIfMapped: !containsValue(%s[%d])", desc, i)); } assertEquals(map.size(), expectedSize1, String.format("map expected size#1 m%d != k%d", map.size(), expectedSize1)); }
protected final Map<M, ?> unmapWithResult(Map<M, ?> context, BiFunction<M, ?, ?> func) { Map<M, Object> resultMap = new HashMap<>(context.size()); for (M delegate : delegates) { Object delegateContext = context.get(delegate); if (delegateContext != null || context.containsKey(delegate)) { Object result = ((BiFunction) func).apply(delegate, delegateContext); resultMap.put(delegate, result); } } return resultMap; }
@Override public V merge(K key, V newValue, BiFunction<? super V, ? super V, ? extends V> function) { checkNotNull(key); checkNotNull(newValue); checkNotNull(function); return compute( key, (k, oldValue) -> (oldValue == null) ? newValue : function.apply(oldValue, newValue)); }