Example usage for java.lang Double compare

List of usage examples for java.lang Double compare

Introduction

In this page you can find the example usage for java.lang Double compare.

Prototype

public static int compare(double d1, double d2) 

Source Link

Document

Compares the two specified double values.

Usage

From source file:org.bonej.wrapperPlugins.AnalyseSkeletonWrapper.java

private void showAdditionalResults(final SkeletonResult results) {
    if (!verbose) {
        return;//w w w .j  a  va2s.  c om
    }
    final DefaultGenericTable table = new DefaultGenericTable();
    final List<PrimitiveColumn<?, ?>> columns = Arrays.asList(new IntColumn("# Skeleton"),
            new IntColumn("# Branch"), new DoubleColumn("Branch length"), new IntColumn("V1 x"),
            new IntColumn("V1 y"), new IntColumn("V1 z"), new IntColumn("V2 x"), new IntColumn("V2 y"),
            new IntColumn("V2 z"), new DoubleColumn("Euclidean distance"),
            new DoubleColumn("running average length"), new DoubleColumn("average intensity (inner 3rd)"),
            new DoubleColumn("average intensity"));
    final Graph[] graphs = results.getGraph();
    for (int i = 0; i < graphs.length; i++) {
        final ArrayList<Edge> edges = graphs[i].getEdges();
        // Sort into descending order by length
        edges.sort((a, b) -> -Double.compare(a.getLength(), b.getLength()));
        for (int j = 0; j < edges.size(); j++) {
            final Edge edge = edges.get(j);
            ((IntColumn) columns.get(0)).add((i + 1));
            ((IntColumn) columns.get(1)).add((j + 1));
            ((DoubleColumn) columns.get(2)).add((edge.getLength()));
            final Point point = edge.getV1().getPoints().get(0);
            ((IntColumn) columns.get(3)).add((point.x));
            ((IntColumn) columns.get(4)).add((point.y));
            ((IntColumn) columns.get(5)).add((point.z));
            final Point point2 = edge.getV2().getPoints().get(0);
            ((IntColumn) columns.get(6)).add((point2.x));
            ((IntColumn) columns.get(7)).add((point2.y));
            ((IntColumn) columns.get(8)).add((point2.z));
            final double distance = MathArrays.distance(new double[] { point.x, point.y, point.z },
                    new double[] { point2.x, point2.y, point2.z });
            ((DoubleColumn) columns.get(9)).add((distance));
            ((DoubleColumn) columns.get(10)).add((edge.getLength_ra()));
            ((DoubleColumn) columns.get(11)).add((edge.getColor3rd()));
            ((DoubleColumn) columns.get(12)).add((edge.getColor()));
        }
    }
    table.addAll(columns);
    if (!table.isEmpty()) {
        verboseTable = table;
    }
}

From source file:gobblin.compaction.dataset.Dataset.java

@Override
public int compareTo(Dataset o) {
    return Double.compare(o.priority, this.priority);
}

From source file:ml.shifu.shifu.core.dtrain.nn.AbstractNNWorker.java

@Override
public void init(WorkerContext<NNParams, NNParams> context) {
    // load props firstly
    this.props = context.getProps();

    loadConfigFiles(context.getProps());

    this.trainerId = Integer.valueOf(context.getProps().getProperty(CommonConstants.SHIFU_TRAINER_ID, "0"));
    GridSearch gs = new GridSearch(modelConfig.getTrain().getParams(),
            modelConfig.getTrain().getGridConfigFileContent());
    this.validParams = this.modelConfig.getTrain().getParams();
    if (gs.hasHyperParam()) {
        this.validParams = gs.getParams(trainerId);
        LOG.info("Start grid search master with params: {}", validParams);
    }/*from   w ww.  j  a  va 2s  . co  m*/

    Integer kCrossValidation = this.modelConfig.getTrain().getNumKFold();
    if (kCrossValidation != null && kCrossValidation > 0) {
        isKFoldCV = true;
        LOG.info("Cross validation is enabled by kCrossValidation: {}.", kCrossValidation);
    }

    this.poissonSampler = Boolean.TRUE.toString()
            .equalsIgnoreCase(context.getProps().getProperty(NNConstants.NN_POISON_SAMPLER));
    this.rng = new PoissonDistribution(1.0d);
    Double upSampleWeight = modelConfig.getTrain().getUpSampleWeight();
    if (Double.compare(upSampleWeight, 1d) != 0 && (modelConfig.isRegression()
            || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll()))) {
        // set mean to upSampleWeight -1 and get sample + 1to make sure no zero sample value
        LOG.info("Enable up sampling with weight {}.", upSampleWeight);
        this.upSampleRng = new PoissonDistribution(upSampleWeight - 1);
    }
    Integer epochsPerIterationInteger = this.modelConfig.getTrain().getEpochsPerIteration();
    this.epochsPerIteration = epochsPerIterationInteger == null ? 1 : epochsPerIterationInteger.intValue();
    LOG.info("epochsPerIteration in worker is :{}", epochsPerIteration);

    // Object elmObject = validParams.get(DTrainUtils.IS_ELM);
    // isELM = elmObject == null ? false : "true".equalsIgnoreCase(elmObject.toString());
    // LOG.info("Check isELM: {}", isELM);

    Object dropoutRateObj = validParams.get(CommonConstants.DROPOUT_RATE);
    if (dropoutRateObj != null) {
        this.dropoutRate = Double.valueOf(dropoutRateObj.toString());
    }
    LOG.info("'dropoutRate' in worker is :{}", this.dropoutRate);

    Object miniBatchO = validParams.get(CommonConstants.MINI_BATCH);
    if (miniBatchO != null) {
        int miniBatchs;
        try {
            miniBatchs = Integer.parseInt(miniBatchO.toString());
        } catch (Exception e) {
            miniBatchs = 1;
        }
        if (miniBatchs < 0) {
            this.batchs = 1;
        } else if (miniBatchs > 1000) {
            this.batchs = 1000;
        } else {
            this.batchs = miniBatchs;
        }
        LOG.info("'miniBatchs' in worker is : {}, batchs is {} ", miniBatchs, batchs);
    }

    int[] inputOutputIndex = DTrainUtils.getInputOutputCandidateCounts(modelConfig.getNormalizeType(),
            this.columnConfigList);
    this.inputNodeCount = inputOutputIndex[0] == 0 ? inputOutputIndex[2] : inputOutputIndex[0];
    // if is one vs all classification, outputNodeCount is set to 1, if classes=2, outputNodeCount is also 1
    int classes = modelConfig.getTags().size();
    this.outputNodeCount = (isLinearTarget || modelConfig.isRegression()) ? inputOutputIndex[1]
            : (modelConfig.getTrain().isOneVsAll() ? inputOutputIndex[1] : (classes == 2 ? 1 : classes));
    this.candidateCount = inputOutputIndex[2];
    boolean isAfterVarSelect = inputOutputIndex[0] != 0;
    LOG.info("isAfterVarSelect {}: Input count {}, output count {}, candidate count {}", isAfterVarSelect,
            inputNodeCount, outputNodeCount, candidateCount);
    // cache all feature list for sampling features
    this.allFeatures = NormalUtils.getAllFeatureList(columnConfigList, isAfterVarSelect);
    String subsetStr = context.getProps().getProperty(CommonConstants.SHIFU_NN_FEATURE_SUBSET);
    if (StringUtils.isBlank(subsetStr)) {
        this.subFeatures = this.allFeatures;
    } else {
        String[] splits = subsetStr.split(",");
        this.subFeatures = new ArrayList<Integer>(splits.length);
        for (String split : splits) {
            int featureIndex = Integer.parseInt(split);
            this.subFeatures.add(featureIndex);
        }
    }
    this.subFeatureSet = new HashSet<Integer>(this.subFeatures);
    LOG.info("subFeatures size is {}", subFeatures.size());
    this.featureInputsCnt = DTrainUtils.getFeatureInputsCnt(this.modelConfig, this.columnConfigList,
            this.subFeatureSet);

    this.wgtInit = "default";
    Object wgtInitObj = validParams.get(CommonConstants.WEIGHT_INITIALIZER);
    if (wgtInitObj != null) {
        this.wgtInit = wgtInitObj.toString();
    }

    Object lossObj = validParams.get("Loss");
    this.lossStr = lossObj != null ? lossObj.toString() : "squared";
    LOG.info("Loss str is {}", this.lossStr);

    this.isDry = Boolean.TRUE.toString()
            .equalsIgnoreCase(context.getProps().getProperty(CommonConstants.SHIFU_DRY_DTRAIN));
    this.isSpecificValidation = (modelConfig.getValidationDataSetRawPath() != null
            && !"".equals(modelConfig.getValidationDataSetRawPath()));
    this.isStratifiedSampling = this.modelConfig.getTrain().getStratifiedSample();
    if (isOnDisk()) {
        LOG.info("NNWorker is loading data into disk.");
        try {
            initDiskDataSet();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // cannot find a good place to close these two data set, using Shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                ((BufferedFloatMLDataSet) (AbstractNNWorker.this.trainingData)).close();
                ((BufferedFloatMLDataSet) (AbstractNNWorker.this.validationData)).close();
            }
        }));
    } else {
        LOG.info("NNWorker is loading data into memory.");
        double memoryFraction = Double
                .valueOf(context.getProps().getProperty("guagua.data.memoryFraction", "0.6"));
        long memoryStoreSize = (long) (Runtime.getRuntime().maxMemory() * memoryFraction);
        LOG.info("Max heap memory: {}, fraction: {}", Runtime.getRuntime().maxMemory(), memoryFraction);
        double crossValidationRate = this.modelConfig.getValidSetRate();
        try {
            if (StringUtils.isNotBlank(modelConfig.getValidationDataSetRawPath())) {
                // fixed 0.6 and 0.4 of max memory for trainingData and validationData
                this.trainingData = new MemoryDiskFloatMLDataSet((long) (memoryStoreSize * 0.6),
                        DTrainUtils.getTrainingFile().toString(), this.featureInputsCnt, this.outputNodeCount);
                this.validationData = new MemoryDiskFloatMLDataSet((long) (memoryStoreSize * 0.4),
                        DTrainUtils.getTestingFile().toString(), this.featureInputsCnt, this.outputNodeCount);
            } else {
                this.trainingData = new MemoryDiskFloatMLDataSet(
                        (long) (memoryStoreSize * (1 - crossValidationRate)),
                        DTrainUtils.getTrainingFile().toString(), this.featureInputsCnt, this.outputNodeCount);
                this.validationData = new MemoryDiskFloatMLDataSet(
                        (long) (memoryStoreSize * crossValidationRate), DTrainUtils.getTestingFile().toString(),
                        this.featureInputsCnt, this.outputNodeCount);
            }
            // cannot find a good place to close these two data set, using Shutdown hook
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    ((MemoryDiskFloatMLDataSet) (AbstractNNWorker.this.trainingData)).close();
                    ((MemoryDiskFloatMLDataSet) (AbstractNNWorker.this.validationData)).close();
                }
            }));
        } catch (IOException e) {
            throw new GuaguaRuntimeException(e);
        }
    }

    // create Splitter
    String delimiter = context.getProps().getProperty(Constants.SHIFU_OUTPUT_DATA_DELIMITER);
    this.splitter = MapReduceUtils.generateShifuOutputSplitter(delimiter);
}

From source file:org.esa.snap.engine_utilities.util.Maths.java

/**
 * The sinc function./*  ww w . jav  a 2s .c om*/
 *
 * @param x The input variable.
 * @return The sinc function value.
 */
private static double sinc(final double x) {

    return (Double.compare(x, 0.0) == 0) ? 1.0 : FastMath.sin(x * Math.PI) / (x * Math.PI);
}

From source file:com.opendoorlogistics.core.scripts.formulae.FmLookupNearest.java

@Override
public Object execute(FunctionParameters parameters) {
    TableParameters tp = (TableParameters) parameters;
    ODLTableReadOnly table = (ODLTableReadOnly) tp.getTableById(refs.datastoreIndx, refs.tableId);

    if (type == LCType.LL) {
        return executeLL(parameters, table);
    }/*from www .j  a  v a 2 s . c o  m*/

    CachedProcessedGeom searchObject = getSearchGeom(parameters);
    if (searchObject == null || searchObject.geometry == null) {
        return Functions.EXECUTION_ERROR;
    }

    class RowElement implements Comparable<RowElement> {
        int row;
        CachedProcessedGeom geom;
        double minDistance;

        @Override
        public int compareTo(RowElement o) {
            int ret = Double.compare(minDistance, o.minDistance);
            if (ret == 0) {
                ret = Integer.compare(row, o.row);
            }
            return ret;
        }
    }

    // Get all geometries, transformed into the coord system and with bounding circles.
    // Place them in a binary heap, sorted by their minimum possible distance according to bounding circle
    int nr = table.getRowCount();
    BinaryHeap sortedHeap = new BinaryHeap();
    for (int row = 0; row < nr; row++) {
        CachedProcessedGeom otherGeom = null;
        switch (type) {
        case GL:
            Pair<LatLong, Boolean> result = getLatLongFromRow(table, row);
            if (result.getSecond() == false) {
                // critical error
                return Functions.EXECUTION_ERROR;
            } else if (result.getFirst() != null) {

                LatLong ll = result.getFirst();

                // put into our comparison object and convert
                otherGeom = new CachedProcessedGeom(ll, transform);
            }
            break;

        case GG:
        case LG: {
            Object val = table.getValueAt(row, refs.columnIndices[0]);
            if (val != null) {

                ODLGeomImpl odlGeom = (ODLGeomImpl) ColumnValueProcessor.convertToMe(ODLColumnType.GEOM, val);
                if (odlGeom == null) {
                    // critical error
                    return Functions.EXECUTION_ERROR;
                }

                otherGeom = toCoordSystem(odlGeom);
                if (otherGeom == null || otherGeom.geometry == null) {
                    // critical error
                    return Functions.EXECUTION_ERROR;
                }
            }
        }
        default:
            break;
        }

        if (otherGeom != null) {
            RowElement rowElement = new RowElement();
            rowElement.row = row;
            rowElement.minDistance = searchObject.boundingCircle.minimumSeparation(otherGeom.boundingCircle);
            rowElement.geom = otherGeom;
            sortedHeap.add(rowElement);
        }
    }

    // loop over the table
    RowElement closest = null;
    double closestDistance = Double.MAX_VALUE;
    while (sortedHeap.size() > 0) {
        RowElement row = (RowElement) sortedHeap.pop();
        if (row.minDistance > closestDistance) {
            // We can stop searching now as the minimum possible distance is greater than our closest
            break;
        }

        // Explicitly get the distance
        double distance = searchObject.geometry.distance(row.geom.geometry);
        if (distance < closestDistance) {
            closestDistance = distance;
            closest = row;
        }
    }

    if (closest != null) {
        return getReturnObject(table, closest.row);
    }

    return null;
}

From source file:darks.learning.word2vec.Word2Vec.java

/**
 * Calculate similar between two words lists with weights by statistic way
 * /*from  w w w . j  a  va 2 s.  co  m*/
 * @param sources Source words list
 * @param sourceWeights Source words weight
 * @param targets Target words list
 * @param targetWeights Target words weight
 * @return Similar score
 */
private double distanceStatistic(Collection<String> sources, Map<String, Double> sourceWeights,
        Collection<String> targets, Map<String, Double> targetWeights) {
    double m = sources.size();
    double n = targets.size();
    DoubleMatrix similarMatrix = DoubleMatrix.zeros(sources.size(), targets.size());
    double sum1 = 0;
    int i = 0;
    int j = 0;
    for (String w1 : sources) {
        j = 0;
        double max = Double.NEGATIVE_INFINITY;
        for (String w2 : targets) {
            double s = similarMatrix.get(i, j);
            if (Double.compare(s, 0) == 0) {
                s = distance(w1, w2);
                similarMatrix.put(i, j, s);
            }
            max = Math.max(max, s);
            j++;
        }
        Double weight = sourceWeights == null ? null : sourceWeights.get(w1);
        if (weight != null) {
            m += weight - 1;
            max *= weight;
        }
        sum1 += max;
        i++;
    }
    double v1 = sum1 / m;

    double sum2 = 0;
    i = 0;
    j = 0;
    for (String w2 : targets) {
        i = 0;
        double max = Double.NEGATIVE_INFINITY;
        for (String w1 : sources) {
            double s = similarMatrix.get(i, j);
            if (Double.compare(s, 0) == 0) {
                s = distance(w1, w2);
                similarMatrix.put(i, j, s);
            }
            max = Math.max(max, s);
            i++;
        }
        Double weight = targetWeights == null ? null : targetWeights.get(w2);
        if (weight != null) {
            n += weight - 1;
            max *= weight;
        }
        sum2 += max;
        j++;
    }
    double v2 = sum2 / (double) n;
    return (v1 + v2) / 2.D;
}

From source file:org.esa.nest.gpf.geometric.SRGROp.java

/**
 * Get slant range pixel position given pixel index in the ground range image.
 *
 * @param x The pixel index in the ground range image.
 * @return The pixel index in the slant range image
 *//* w  ww.  j a  v a 2  s.  c om*/
private double getSlantRangePixelPosition(double x) {

    if (Double.compare(x, 0.0) == 0) {
        return 0.0;
    }

    final double dg = groundRangeSpacing * x;
    double ds = 0.0;
    for (int j = 0; j < warpPolynomialOrder + 1; j++) {
        ds += FastMath.pow(dg, (double) j) * warpPolynomialCoef[j];
    }
    return ds / slantRangeSpacing;
}

From source file:org.esa.s1tbx.insar.gpf.support.SARGeocoding.java

/**
 * Compute zero Doppler time for given point with the product orbit state vectors using bisection method.
 *
 * @param firstLineUTC     The zero Doppler time for the first range line.
 * @param lineTimeInterval The line time interval.
 * @param wavelength       The radar wavelength.
 * @param earthPoint       The earth point in xyz coordinate.
 * @param orbit            The object holding orbit state vectors.
 * @return The zero Doppler time in days if it is found, NonValidZeroDopplerTime otherwise.
 * @throws OperatorException The operator exception.
 *//*from  w  w  w.j  a  v a 2s.  c  om*/
public static double getZeroDopplerTime(final double firstLineUTC, final double lineTimeInterval,
        final double wavelength, final PosVector earthPoint, final SARGeocoding.Orbit orbit)
        throws OperatorException {

    // loop through all orbit state vectors to find the adjacent two vectors
    final int numOrbitVec = orbit.orbitStateVectors.length;
    final PosVector sensorPosition = new PosVector();
    final PosVector sensorVelocity = new PosVector();
    double firstVecTime = 0.0;
    double secondVecTime = 0.0;
    double firstVecFreq = 0.0;
    double secondVecFreq = 0.0;

    for (int i = 0; i < numOrbitVec; i++) {
        final OrbitStateVector orb = orbit.orbitStateVectors[i];
        sensorPosition.set(orb.x_pos, orb.y_pos, orb.z_pos);
        sensorVelocity.set(orb.x_vel, orb.y_vel, orb.z_vel);

        final double currentFreq = getDopplerFrequency(earthPoint, sensorPosition, sensorVelocity, wavelength);
        if (i == 0 || firstVecFreq * currentFreq > 0) {
            firstVecTime = orb.time_mjd;
            firstVecFreq = currentFreq;
        } else {
            secondVecTime = orb.time_mjd;
            secondVecFreq = currentFreq;
            break;
        }
    }

    if (firstVecFreq * secondVecFreq >= 0.0) {
        return NonValidZeroDopplerTime;
    }

    // find the exact time using Doppler frequency and bisection method
    double lowerBoundTime = firstVecTime;
    double upperBoundTime = secondVecTime;
    double lowerBoundFreq = firstVecFreq;
    double upperBoundFreq = secondVecFreq;
    double midTime = 0.0;
    double midFreq = 0.0;
    double diffTime = Math.abs(upperBoundTime - lowerBoundTime);
    final double absLineTimeInterval = Math.abs(lineTimeInterval);
    final int totalIterations = (int) (diffTime / absLineTimeInterval) + 1;
    int numIterations = 0;
    while (diffTime > absLineTimeInterval && numIterations <= totalIterations) {

        midTime = (upperBoundTime + lowerBoundTime) / 2.0;
        orbit.getPositionVelocity(midTime, sensorPosition, sensorVelocity);
        midFreq = getDopplerFrequency(earthPoint, sensorPosition, sensorVelocity, wavelength);

        if (midFreq * lowerBoundFreq > 0.0) {
            lowerBoundTime = midTime;
            lowerBoundFreq = midFreq;
        } else if (midFreq * upperBoundFreq > 0.0) {
            upperBoundTime = midTime;
            upperBoundFreq = midFreq;
        } else if (Double.compare(midFreq, 0.0) == 0) {
            return midTime;
        }

        diffTime = Math.abs(upperBoundTime - lowerBoundTime);
        numIterations++;
    }

    /*
    midTime = (upperBoundTime + lowerBoundTime) / 2.0;
    orbit.getPositionVelocity(midTime, sensorPosition, sensorVelocity);
    midFreq = getDopplerFrequency(earthPoint, sensorPosition, sensorVelocity, wavelength);
    final double[] freqArray = {lowerBoundFreq, midFreq, upperBoundFreq};
    final double[][] tmp = {{1, -1, 1}, {1,0,0}, {1,1,1}};
    final Matrix A = new Matrix(tmp);
    final double[] c = Maths.polyFit(A, freqArray);
    double t1 = (-c[1] + Math.sqrt(c[1]*c[1] - 4.0*c[0]*c[2]))/ (2.0*c[2]);
    double t2 = (-c[1] - Math.sqrt(c[1]*c[1] - 4.0*c[0]*c[2]))/ (2.0*c[2]);
    if (t1 >= -1 && t1 <= 1) {
    return 0.5*(1 - t1)*lowerBoundTime + 0.5*(1 + t1)*upperBoundTime;//return t1;
    } else {
    return 0.5*(1 - t2)*lowerBoundTime + 0.5*(1 + t2)*upperBoundTime;//return t2;
    }*/

    return lowerBoundTime
            - lowerBoundFreq * (upperBoundTime - lowerBoundTime) / (upperBoundFreq - lowerBoundFreq);
}

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

/**
 * Actually draws the environment on the view.
 * /*ww w. j av a 2  s .c om*/
 * @param g
 *            {@link Graphics2D} object responsible for drawing
 */
protected final void drawEnvOnView(final Graphics2D g) {
    if (wormhole == null || !isVisible() || !isEnabled()) {
        return;
    }
    accessData();
    if (hooked.isPresent()) {
        final Position hcoor = positions.get(hooked.get());
        final Point hp = wormhole.getViewPoint(hcoor);
        if (hp.distance(getCenter()) > FREEDOM_RADIUS) {
            wormhole.setViewPosition(hp);
        }
    }
    /*
     * Compute nodes in sight and their screen position
     */
    final Map<Node<T>, Point> onView = positions.entrySet().parallelStream()
            .map(pair -> new Pair<>(pair.getKey(), wormhole.getViewPoint(pair.getValue())))
            .filter(p -> wormhole.isInsideView(p.getSecond()))
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    g.setColor(Color.BLACK);
    if (obstacles != null) {
        /*
         * TODO: only draw obstacles if on view
         */
        obstacles.parallelStream().map(this::convertObstacle).forEachOrdered(g::fill);
    }
    if (paintLinks) {
        g.setColor(Color.GRAY);
        onView.keySet().parallelStream().map(neighbors::get)
                .flatMap(neigh -> neigh.getNeighbors().parallelStream()
                        .map(node -> node.compareTo(neigh.getCenter()) > 0 ? new Pair<>(neigh.getCenter(), node)
                                : new Pair<>(node, neigh.getCenter())))
                .distinct().map(
                        pair -> mapPair(pair,
                                node -> Optional.ofNullable(onView.get(node))
                                        .orElse(wormhole.getViewPoint(positions.get(node)))))
                .forEachOrdered(line -> {
                    final Point p1 = line.getFirst();
                    final Point p2 = line.getSecond();
                    g.drawLine(p1.x, p1.y, p2.x, p2.y);
                });
    }
    releaseData();
    if (isDraggingMouse && status == ViewStatus.MOVING && originPoint.isPresent() && endingPoint.isPresent()) {
        for (final Node<T> n : selectedNodes) {
            if (onView.containsKey(n)) {
                onView.put(n, new Point(onView.get(n).x + (endingPoint.get().x - originPoint.get().x),
                        onView.get(n).y + (endingPoint.get().y - originPoint.get().y)));
            }
        }
    }
    g.setColor(Color.GREEN);
    if (effectStack != null) {
        effectStack.forEach(effect -> {
            onView.entrySet().forEach(entry -> {
                final Point p = entry.getValue();
                effect.apply(g, entry.getKey(), p.x, p.y);
            });
        });
    }
    if (isCloserNodeMarked()) {
        final Optional<Map.Entry<Node<T>, Point>> closest = onView.entrySet().parallelStream()
                .min((pair1, pair2) -> {
                    final Point p1 = pair1.getValue();
                    final Point p2 = pair2.getValue();
                    final double d1 = Math.hypot(p1.x - mousex, p1.y - mousey);
                    final double d2 = Math.hypot(p2.x - mousex, p2.y - mousey);
                    return Double.compare(d1, d2);
                });
        if (closest.isPresent()) {
            nearest = closest.get().getKey();
            final int nearestx = closest.get().getValue().x;
            final int nearesty = closest.get().getValue().y;
            drawFriedEgg(g, nearestx, nearesty, Color.RED, Color.YELLOW);
        }
    } else {
        nearest = null;
    }
    if (isDraggingMouse && status == ViewStatus.SELECTING && originPoint.isPresent()
            && endingPoint.isPresent()) {
        g.setColor(Color.BLACK);
        final int x = originPoint.get().x < endingPoint.get().x ? originPoint.get().x : endingPoint.get().x;
        final int y = originPoint.get().y < endingPoint.get().y ? originPoint.get().y : endingPoint.get().y;
        final int width = Math.abs(endingPoint.get().x - originPoint.get().x);
        final int height = Math.abs(endingPoint.get().y - originPoint.get().y);
        g.drawRect(x, y, width, height);
        selectedNodes = onView.entrySet().parallelStream()
                .filter(nodes -> isInsideRectangle(nodes.getValue(), x, y, width, height))
                .map(onScreen -> onScreen.getKey()).collect(Collectors.toSet());
    }
    selectedNodes.parallelStream().map(e -> Optional.ofNullable(onView.get(e))).filter(Optional::isPresent)
            .map(Optional::get).forEachOrdered(p -> drawFriedEgg(g, p.x, p.y, Color.BLUE, Color.CYAN));
}

From source file:com.opengamma.analytics.financial.instrument.varianceswap.VarianceSwapDefinition.java

@Override
public boolean equals(final Object obj) {
    if (this == obj) {
        return true;
    }/*from  w  w w . j  av  a2  s.  com*/
    if (!(obj instanceof VarianceSwapDefinition)) {
        return false;
    }
    final VarianceSwapDefinition other = (VarianceSwapDefinition) obj;
    if (Double.compare(_volStrike, other._volStrike) != 0) {
        return false;
    }
    if (Double.compare(_volNotional, other._volNotional) != 0) {
        return false;
    }
    if (Double.compare(_annualizationFactor, other._annualizationFactor) != 0) {
        return false;
    }
    if (!(ObjectUtils.equals(_obsStartDate, other._obsStartDate))) {
        return false;
    }
    if (!(ObjectUtils.equals(_obsEndDate, other._obsEndDate))) {
        return false;
    }
    if (!(ObjectUtils.equals(_settlementDate, other._settlementDate))) {
        return false;
    }
    if (!(ObjectUtils.equals(_currency, other._currency))) {
        return false;
    }
    if (!(ObjectUtils.equals(_calendar, other._calendar))) {
        return false;
    }
    return true;
}