java.util.function.ToDoubleFunction Java Examples

The following examples show how to use java.util.function.ToDoubleFunction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReferencePipeline.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #2
Source File: DropwizardMeterRegistry.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Override
protected <T> io.micrometer.core.instrument.Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction<T> valueFunction) {
    final WeakReference<T> ref = new WeakReference<>(obj);
    Gauge<Double> gauge = () -> {
        T obj2 = ref.get();
        if (obj2 != null) {
            try {
                return valueFunction.applyAsDouble(obj2);
            } catch (Throwable ex) {
                logger.log("Failed to apply the value function for the gauge '" + id.getName() + "'.", ex);
            }
        }
        return nullGaugeValue();
    };
    registry.register(hierarchicalName(id), gauge);
    return new DropwizardGauge(id, gauge);
}
 
Example #3
Source File: Collectors.java    From desugar_jdk_libs with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The sum returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * sum will be {@code NaN}.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
summingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the simple sum used to compute
     * the proper result if the stream contains infinite values of
     * the same sign.
     */
    return new CollectorImpl<>(
            () -> new double[3],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t));
                        a[2] += mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]);
                        a[2] += b[2];
                        return sumWithCompensation(a, b[1]); },
            a -> computeFinalSum(a),
            CH_NOID);
}
 
Example #4
Source File: ReferencePipeline.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #5
Source File: ReferencePipeline.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #6
Source File: ReferencePipeline.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #7
Source File: Collectors.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The sum returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * sum will be {@code NaN}.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
summingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the simple sum used to compute
     * the proper result if the stream contains infinite values of
     * the same sign.
     */
    return new CollectorImpl<>(
            () -> new double[3],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t));
                        a[2] += mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]);
                        a[2] += b[2];
                        return sumWithCompensation(a, b[1]); },
            a -> computeFinalSum(a),
            CH_NOID);
}
 
Example #8
Source File: SimpleMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    switch (config.mode()) {
        case CUMULATIVE:
            return new CumulativeFunctionCounter<>(id, obj, countFunction);

        case STEP:
        default:
            return new StepFunctionCounter<>(id, clock, config.step().toMillis(), obj, countFunction);
    }
}
 
Example #9
Source File: OptimizationContext.java    From rheem with Apache License 2.0 5 votes vote down vote up
/**
 * Update the {@link LoadProfile} and {@link TimeEstimate} of this instance.
 *
 * @param configuration provides the necessary functions
 */
private void updateCostEstimate(Configuration configuration) {
    if (!this.operator.isExecutionOperator()) return;

    // Estimate the LoadProfile.
    final LoadProfileEstimator loadProfileEstimator = this.getLoadProfileEstimator();
    try {
        this.loadProfile = LoadProfileEstimators.estimateLoadProfile(this, loadProfileEstimator);
    } catch (Exception e) {
        throw new RheemException(String.format("Load profile estimation for %s failed.", this.operator), e);
    }

    // Calculate the TimeEstimate.
    final ExecutionOperator executionOperator = (ExecutionOperator) this.operator;
    final Platform platform = executionOperator.getPlatform();
    final LoadProfileToTimeConverter timeConverter = configuration.getLoadProfileToTimeConverterProvider().provideFor(platform);
    this.timeEstimate = TimeEstimate.MINIMUM.plus(timeConverter.convert(this.loadProfile));
    if (OptimizationContext.this.logger.isDebugEnabled()) {
        OptimizationContext.this.logger.debug(
                "Setting time estimate of {} to {}.", this.operator, this.timeEstimate
        );
    }

    // Calculate the cost estimate.
    final TimeToCostConverter timeToCostConverter = configuration.getTimeToCostConverterProvider().provideFor(platform);
    this.costEstimate = timeToCostConverter.convertWithoutFixCosts(this.timeEstimate);

    // Squash the cost estimate.
    final ToDoubleFunction<ProbabilisticDoubleInterval> costSquasher = configuration.getCostSquasherProvider().provide();
    this.squashedCostEstimate = costSquasher.applyAsDouble(this.costEstimate);
}
 
Example #10
Source File: StatsdGauge.java    From micrometer with Apache License 2.0 5 votes vote down vote up
StatsdGauge(Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, @Nullable T obj, ToDoubleFunction<T> value, boolean alwaysPublish) {
    super(id);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
    this.ref = new WeakReference<>(obj);
    this.value = value;
    this.alwaysPublish = alwaysPublish;
}
 
Example #11
Source File: ArrayBase.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
@Override
public final Array<T> applyDoubles(ToDoubleFunction<ArrayValue<T>> function) {
    final int length = length();
    if (length > 0) {
        final ApplyValues action = new ApplyValues(0, length - 1, function);
        if (isParallel()) {
            ForkJoinPool.commonPool().invoke(action);
        } else {
            action.compute();
        }
    }
    return this;
}
 
Example #12
Source File: BasicTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void testDoubleComparator() {
    Thing[] things = new Thing[doubleValues.length];
    for (int i=0; i<doubleValues.length; i++)
        things[i] = new Thing(0, 0L, doubleValues[i], null);
    Comparator<Thing> comp = Comparator.comparingDouble(new ToDoubleFunction<Thing>() {
        @Override
        public double applyAsDouble(Thing thing) {
            return thing.getDoubleField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example #13
Source File: Function1.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an DOUBLE 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,Double> toDouble(ToDoubleFunction<I> function) {
    return new Function1<I,Double>(FunctionStyle.DOUBLE) {
        @Override
        public final double applyAsDouble(I value) {
            return function.applyAsDouble(value);
        }
    };
}
 
Example #14
Source File: DropwizardMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> FunctionTimer newFunctionTimer(Meter.Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit) {
    DropwizardFunctionTimer<T> ft = new DropwizardFunctionTimer<>(id, clock, obj, countFunction, totalTimeFunction,
            totalTimeFunctionUnit, getBaseTimeUnit());
    registry.register(hierarchicalName(id), ft.getDropwizardMeter());
    return ft;
}
 
Example #15
Source File: DropwizardFunctionCounter.java    From micrometer with Apache License 2.0 5 votes vote down vote up
DropwizardFunctionCounter(Id id, Clock clock,
                          T obj, ToDoubleFunction<T> f) {
    super(id);
    this.ref = new WeakReference<>(obj);
    this.f = f;
    this.rate = new DropwizardRate(clock);
    this.dropwizardMeter = new Meter(new DropwizardClock(clock)) {
        @Override
        public double getFifteenMinuteRate() {
            count();
            return rate.getFifteenMinuteRate();
        }

        @Override
        public double getFiveMinuteRate() {
            count();
            return rate.getFiveMinuteRate();
        }

        @Override
        public double getOneMinuteRate() {
            count();
            return rate.getOneMinuteRate();
        }

        @Override
        public long getCount() {
            return (long) count();
        }
    };
}
 
Example #16
Source File: StatsdFunctionTimer.java    From micrometer with Apache License 2.0 5 votes vote down vote up
StatsdFunctionTimer(Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction,
                    TimeUnit totalTimeFunctionUnit, TimeUnit baseTimeUnit,
                    StatsdLineBuilder lineBuilder, FluxSink<String> sink) {
    super(id, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit, baseTimeUnit);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
}
 
Example #17
Source File: BasicTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void testDoubleComparator() {
    Thing[] things = new Thing[doubleValues.length];
    for (int i=0; i<doubleValues.length; i++)
        things[i] = new Thing(0, 0L, doubleValues[i], null);
    Comparator<Thing> comp = Comparator.comparingDouble(new ToDoubleFunction<Thing>() {
        @Override
        public double applyAsDouble(Thing thing) {
            return thing.getDoubleField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example #18
Source File: PrometheusMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    FunctionCounter fc = new CumulativeFunctionCounter<>(id, obj, countFunction);
    applyToCollector(id, (collector) -> {
        List<String> tagValues = tagValues(id);
        collector.add(tagValues, (conventionName, tagKeys) -> Stream.of(new MicrometerCollector.Family(Collector.Type.COUNTER, conventionName,
                new Collector.MetricFamilySamples.Sample(conventionName, tagKeys, tagValues, fc.count())
        )));
    });
    return fc;
}
 
Example #19
Source File: Gauge.java    From micrometer with Apache License 2.0 4 votes vote down vote up
private Builder(String name, @Nullable T obj, ToDoubleFunction<T> f) {
    this.name = name;
    this.obj = obj;
    this.f = f;
}
 
Example #20
Source File: SpectatorToDoubleGauge.java    From micrometer with Apache License 2.0 4 votes vote down vote up
SpectatorToDoubleGauge(Clock clock, Id id, @Nullable T obj, ToDoubleFunction<T> f) {
    super(clock, id, obj);
    this.f = f;
}
 
Example #21
Source File: OpenTSDBMeterRegistry.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> FunctionTimer newFunctionTimer(Meter.Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit) {
    return new CumulativeFunctionTimer<>(id, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit, getBaseTimeUnit());
}
 
Example #22
Source File: TimeGauge.java    From micrometer with Apache License 2.0 4 votes vote down vote up
private Builder(String name, @Nullable T obj, TimeUnit fUnits, ToDoubleFunction<T> f) {
    this.name = name;
    this.obj = obj;
    this.fUnits = fUnits;
    this.f = f;
}
 
Example #23
Source File: OpenTSDBMeterRegistry.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    return new CumulativeFunctionCounter<>(id, obj, countFunction);
}
 
Example #24
Source File: CompositeFunctionCounter.java    From micrometer with Apache License 2.0 4 votes vote down vote up
CompositeFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> f) {
    super(id);
    this.ref = new WeakReference<>(obj);
    this.f = f;
}
 
Example #25
Source File: GoalDeciders.java    From freecol with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Goal decider to find the best land tile to disembark a unit that
 * is planning to attack a given target.
 *
 * The result must be:
 * - Unoccupied
 * - Have at least one unoccupied high-seas-connected neighbour
 * - Favour the best natural defence of the alternatives
 * - Favour a short journey to the target
 * - Prioritize not landing next to a hostile fort/fortress.
 *
 * @param target The target {@code Tile}.
 * @return A suitable {@code GoalDecider}.
 */
public static GoalDecider getDisembarkGoalDecider(final Tile target) {
    final double NO_DANGER_BONUS = 1000.0;
    
    return new GoalDecider() {
        private double bestScore = -1.0;
        private PathNode goal = null;

        @Override
        public PathNode getGoal() { return goal; }
        @Override
        public boolean hasSubGoals() { return true; }
        @Override
        public boolean check(Unit u, PathNode pathNode) {
            final Tile tile = pathNode.getTile();
            if (tile == null || !tile.isLand() || !tile.isEmpty()
                || tile.hasSettlement()) return false;

            final Player owner = u.getOwner();
            final Map map = u.getGame().getMap();
            final Predicate<Tile> dockPred = t ->
                t.isHighSeasConnected() && !t.isLand();
            final Predicate<Tile> dangerPred = t -> {
                Settlement settlement = t.getSettlement();
                return (settlement != null
                    && !owner.owns(settlement)
                    && settlement.hasAbility(Ability.BOMBARD_SHIPS)
                    && (owner.atWarWith(settlement.getOwner())
                        || u.hasAbility(Ability.PIRACY)));
            };
            final ToDoubleFunction<Tile> tileScorer = cacheDouble(t ->
                (t.getDefenceValue() / (1.0 + map.getDistance(target, t))
                    + ((none(t.getSurroundingTiles(1, 1), dangerPred))
                        ? NO_DANGER_BONUS : 0.0)));
            Tile best = maximize(tile.getSurroundingTiles(1, 1), dockPred,
                                 Comparator.comparingDouble(tileScorer));
            double score;
            if (best != null
                && (score = tileScorer.applyAsDouble(best)) > bestScore) {
                bestScore = score;
                goal = pathNode;
                return true;
            }
            return false;
        }
    };
}
 
Example #26
Source File: Configuration.java    From rheem with Apache License 2.0 4 votes vote down vote up
public ValueProvider<ToDoubleFunction<ProbabilisticDoubleInterval>> getCostSquasherProvider() {
    return this.costSquasherProvider;
}
 
Example #27
Source File: FunctionTimer.java    From micrometer with Apache License 2.0 4 votes vote down vote up
static <T> Builder<T> builder(String name, T obj, ToLongFunction<T> countFunction,
                              ToDoubleFunction<T> totalTimeFunction,
                              TimeUnit totalTimeFunctionUnit) {
    return new Builder<>(name, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit);
}
 
Example #28
Source File: WavefrontMeterRegistry.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    return new CumulativeFunctionCounter<>(id, obj, countFunction);
}
 
Example #29
Source File: ClickAuraHack.java    From Wurst7 with GNU General Public License v3.0 4 votes vote down vote up
private Priority(String name,
	ToDoubleFunction<LivingEntity> keyExtractor)
{
	this.name = name;
	comparator = Comparator.comparingDouble(keyExtractor);
}
 
Example #30
Source File: PlanEnumerator.java    From rheem with Apache License 2.0 4 votes vote down vote up
/**
 * Basic constructor that will always be called and initializes all fields.
 */
private PlanEnumerator(Collection<Operator> startOperators,
                       OptimizationContext optimizationContext,
                       OperatorAlternative.Alternative enumeratedAlternative,
                       Map<OperatorAlternative, OperatorAlternative.Alternative> presettledAlternatives,
                       Map<ExecutionOperator, ExecutionTask> executedTasks,
                       Map<OutputSlot<?>, Collection<Channel>> openChannels) {

    this.optimizationContext = optimizationContext;
    this.enumeratedAlternative = enumeratedAlternative;
    this.presettledAlternatives = presettledAlternatives;
    this.executedTasks = executedTasks;
    this.openChannels = openChannels;


    // Set up start Operators.
    for (Operator startOperator : startOperators) {
        this.scheduleForEnumeration(startOperator, optimizationContext);
    }

    // Configure the enumeration.
    final Configuration configuration = this.optimizationContext.getConfiguration();
    this.isEnumeratingBranchesFirst = configuration.getBooleanProperty(
            "rheem.core.optimizer.enumeration.branchesfirst", true
    );

    // Configure the concatenations.
    final String priorityFunctionName = configuration.getStringProperty(
            "rheem.core.optimizer.enumeration.concatenationprio"
    );
    ToDoubleFunction<ConcatenationActivator> concatenationPriorityFunction;
    switch (priorityFunctionName) {
        case "slots":
            concatenationPriorityFunction = ConcatenationActivator::countNumOfOpenSlots;
            break;
        case "plans":
            concatenationPriorityFunction = ConcatenationActivator::estimateNumConcatenatedPlanImplementations;
            break;
        case "plans2":
            concatenationPriorityFunction = ConcatenationActivator::estimateNumConcatenatedPlanImplementations2;
            break;
        case "random":
            // Randomly generate a priority. However, avoid re-generate priorities, because that would increase
            // of a concatenation activator being processed, the longer it is in the queue (I guess).
            concatenationPriorityFunction = activator -> {
                if (!Double.isNaN(activator.priority)) return activator.priority;
                return Math.random();
            };
            break;
        case "none":
            concatenationPriorityFunction = activator -> 0d;
            break;
        default:
            throw new RheemException("Unknown concatenation priority function: " + priorityFunctionName);
    }

    boolean isInvertConcatenationPriorities = configuration.getBooleanProperty(
            "rheem.core.optimizer.enumeration.invertconcatenations", false
    );
    this.concatenationPriorityFunction = isInvertConcatenationPriorities ?
            activator -> -concatenationPriorityFunction.applyAsDouble(activator) :
            concatenationPriorityFunction;


}