Example usage for java.lang Float NEGATIVE_INFINITY

List of usage examples for java.lang Float NEGATIVE_INFINITY

Introduction

In this page you can find the example usage for java.lang Float NEGATIVE_INFINITY.

Prototype

float NEGATIVE_INFINITY

To view the source code for java.lang Float NEGATIVE_INFINITY.

Click Source Link

Document

A constant holding the negative infinity of type float .

Usage

From source file:com.ericsson.deviceaccess.spi.impl.GenericDeviceServiceImplTest.java

@Before
public void setup() throws Exception {
    action = context.mock(GDAction.class);
    eventManager = context.mock(EventManager.class);
    device = context.mock(GenericDeviceImpl.class);
    metadataFloat = context.mock(GDPropertyMetadata.class, "metadataFloat");
    metadataInt = context.mock(GDPropertyMetadata.class, "metadataInt");
    metadataString = context.mock(GDPropertyMetadata.class, "metadataString");
    metadataArr = new ArrayList<>();
    metadataArr.add(metadataFloat);//from   www  .j  a v  a  2s .  co  m
    metadataArr.add(metadataInt);
    metadataArr.add(metadataString);
    ReflectionTestUtil.setField(GDActivator.class, "eventManager", eventManager);

    context.checking(new Expectations() {
        {
            allowing(device).getId();
            will(returnValue("devId"));
            allowing(device).getURN();
            will(returnValue("devUrn"));
            allowing(device).getName();
            will(returnValue("dev"));
            allowing(device).getProtocol();
            will(returnValue("prot"));
            allowing(device).isOnline();
            will(returnValue(true));

            allowing(metadataFloat).getDefaultNumberValue();
            will(returnValue(42.0f));
            allowing(metadataFloat).getDefaultStringValue();
            will(returnValue("42.0"));
            allowing(metadataFloat).getName();
            will(returnValue("fProp"));
            allowing(metadataFloat).getType();
            will(returnValue(Float.class));
            allowing(metadataFloat).getTypeName();
            will(returnValue("Float"));
            allowing(metadataFloat).getValidValues();
            will(returnValue(null));
            allowing(metadataFloat).getMinValue();
            will(returnValue(Float.NEGATIVE_INFINITY));
            allowing(metadataFloat).getMaxValue();
            will(returnValue(Float.POSITIVE_INFINITY));
            allowing(metadataFloat).serialize(Format.JSON);
            will(returnValue("{\"type\":\"float\"}"));

            allowing(metadataInt).getDefaultNumberValue();
            will(returnValue(42));
            allowing(metadataInt).getDefaultStringValue();
            will(returnValue("42"));
            allowing(metadataInt).getName();
            will(returnValue("iProp"));
            allowing(metadataInt).getType();
            will(returnValue(Integer.class));
            allowing(metadataInt).getTypeName();
            will(returnValue("Integer"));
            allowing(metadataInt).getValidValues();
            will(returnValue(null));
            allowing(metadataInt).getMinValue();
            will(returnValue(Integer.MIN_VALUE));
            allowing(metadataInt).getMaxValue();
            will(returnValue(Integer.MAX_VALUE));
            allowing(metadataInt).serialize(Format.JSON);
            will(returnValue("{\"type\":\"int\"}"));

            allowing(metadataString).getDefaultNumberValue();
            will(returnValue(null));
            allowing(metadataString).getDefaultStringValue();
            will(returnValue("Forty-two"));
            allowing(metadataString).getName();
            will(returnValue("sProp"));
            allowing(metadataString).getType();
            will(returnValue(String.class));
            allowing(metadataString).getTypeName();
            will(returnValue("String"));
            allowing(metadataString).getValidValues();
            will(returnValue(null));
            allowing(metadataString).getMinValue();
            will(returnValue(null));
            allowing(metadataString).getMaxValue();
            will(returnValue(null));
            allowing(metadataString).serialize(Format.JSON);
            will(returnValue("{\"type\":\"string\"}"));

            allowing(action).getName();
            will(returnValue("action1"));
            allowing(action).updatePath(with(aNonNull(String.class)));
            allowing(action).getArgumentsMetadata();
            will(returnValue(new HashMap<>()));
            allowing(action).getResultMetadata();
            will(returnValue(new HashMap<>()));
        }
    });

    service = new GDServiceImpl("srv", metadataArr);
    service.setParentDevice(device);
    service.putAction(action);

    props = new GDPropertiesImpl(metadataArr, service);
}

From source file:uk.co.modularaudio.mads.base.stereo_compressor.ui.SourceSignalAmpMeter.java

private void refillMeterImage() {
    //      log.debug("Repainting it.");

    if (outBufferedImageGraphics != null) {
        outBufferedImageGraphics.setColor(Color.BLACK);
        outBufferedImageGraphics.fillRect(0, 0, componentWidth, componentHeight);

        final int meterWidth = PREFERRED_METER_WIDTH;
        final int totalMeterHeight = componentHeight - 2;

        final int meterHeight = (showClipBox ? totalMeterHeight - meterWidth : totalMeterHeight);
        final int meterHeightOffset = (showClipBox ? meterWidth : 0);

        underThresholdLevel = dbToLevelComputer.toNormalisedSliderLevelFromDb(currentThresholdValueDb);

        final int yReverser = meterHeight + 1;

        // Draw the two little marks indicating where the current threshold is
        int thresholdHeightInPixels = (int) (underThresholdLevel * meterHeight);
        thresholdHeightInPixels = (thresholdHeightInPixels > (meterHeight) ? (meterHeight)
                : (thresholdHeightInPixels < 0 ? 0 : thresholdHeightInPixels));
        final int thresholdStartY = yReverser - thresholdHeightInPixels + meterHeightOffset;
        outBufferedImageGraphics.setColor(MARK_THRESHOLD_COLOR);
        outBufferedImageGraphics.drawLine(0, thresholdStartY, meterWidth + 2, thresholdStartY);

        float levelValue = 0.0f;
        if (currentMeterValueDb != Float.NEGATIVE_INFINITY) {
            levelValue = dbToLevelComputer.toNormalisedSliderLevelFromDb(currentMeterValueDb);
        }/*w  w  w . ja v a 2s. co  m*/

        outBufferedImageGraphics.setColor(UNDER_THRESHOLD_COLOR);
        final float underVal = (levelValue >= underThresholdLevel ? underThresholdLevel : levelValue);
        int underBarHeightInPixels = (int) (underVal * meterHeight);
        underBarHeightInPixels = (underBarHeightInPixels > (meterHeight) ? (meterHeight)
                : (underBarHeightInPixels < 0 ? 0 : underBarHeightInPixels));
        final int underStartY = meterHeight - underBarHeightInPixels + 1 + meterHeightOffset;
        outBufferedImageGraphics.fillRect(3, underStartY, meterWidth - 4, underBarHeightInPixels);

        if (currentMeterValueDb > currentThresholdValueDb) {
            outBufferedImageGraphics.setColor(OVER_THRESHOLD_COLOR);
            final float overVal = levelValue;
            int overBarHeightInPixels = (int) (overVal * meterHeight);
            overBarHeightInPixels = (overBarHeightInPixels > (meterHeight) ? (meterHeight)
                    : (overBarHeightInPixels < 0 ? 0 : overBarHeightInPixels));
            overBarHeightInPixels = overBarHeightInPixels - underBarHeightInPixels;
            final int overStartY = underStartY - overBarHeightInPixels;
            outBufferedImageGraphics.fillRect(3, overStartY, meterWidth - 4, overBarHeightInPixels);
        }

        float maxLevelValue = 0.0f;
        final Color maxDbColor = getColorForDb(currentMaxValueDb);
        if (currentMaxValueDb != Float.NEGATIVE_INFINITY) {
            maxLevelValue = dbToLevelComputer.toNormalisedSliderLevelFromDb(currentMaxValueDb);
        }
        outBufferedImageGraphics.setColor(maxDbColor);

        int maxValueHeightInPixels = (int) (maxLevelValue * meterHeight);
        maxValueHeightInPixels = (maxValueHeightInPixels > (meterHeight) ? (meterHeight)
                : (maxValueHeightInPixels < 0 ? 0 : maxValueHeightInPixels));
        final int maxStartY = yReverser - maxValueHeightInPixels + meterHeightOffset;
        outBufferedImageGraphics.drawLine(1, maxStartY, meterWidth, maxStartY);

        if (showClipBox) {
            if (currentMaxValueDb >= 1.0f) {
                // Should already be the right colour
                //            g.setColor( getColorForDb( 0.0f ) );
                outBufferedImageGraphics.fillRect(1, 1, meterWidth, meterWidth - 1);
            }
        } else {
        }
    }
}

From source file:net.minecraftforge.common.model.animation.AnimationStateMachine.java

public Pair<IModelState, Iterable<Event>> apply(float time) {
    if (lastPollTime == Float.NEGATIVE_INFINITY) {
        lastPollTime = time;//w w  w  .j a  v  a 2s .co  m
    }
    Pair<IModelState, Iterable<Event>> pair = clipCache
            .getUnchecked(Triple.of(currentState, lastPollTime, time));
    lastPollTime = time;
    boolean shouldFilter = false;
    if (shouldHandleSpecialEvents) {
        for (Event event : ImmutableList.copyOf(pair.getRight()).reverse()) {
            if (event.event().startsWith("!")) {
                shouldFilter = true;
                if (event.event().startsWith("!transition:")) {
                    String newState = event.event().substring("!transition:".length());
                    transition(newState);
                } else {
                    System.out.println("Unknown special event \"" + event.event() + "\", ignoring");
                }
            }
        }
    }
    if (!shouldFilter) {
        return pair;
    }
    return Pair.of(pair.getLeft(), Iterables.filter(pair.getRight(), new Predicate<Event>() {
        public boolean apply(Event event) {
            return !event.event().startsWith("!");
        }
    }));
}

From source file:org.apache.hadoop.util.Progress.java

/** Called during execution on a leaf node to set its progress. */
public synchronized void set(float progress) {
    if (Float.isNaN(progress)) {
        progress = 0;/*from www .j a  va2 s.com*/
        LOG.debug("Illegal progress value found, progress is Float.NaN. " + "Progress will be changed to 0");
    } else if (progress == Float.NEGATIVE_INFINITY) {
        progress = 0;
        LOG.debug("Illegal progress value found, progress is "
                + "Float.NEGATIVE_INFINITY. Progress will be changed to 0");
    } else if (progress < 0) {
        progress = 0;
        LOG.debug("Illegal progress value found, progress is less than 0." + " Progress will be changed to 0");
    } else if (progress > 1) {
        progress = 1;
        LOG.debug(
                "Illegal progress value found, progress is larger than 1." + " Progress will be changed to 1");
    } else if (progress == Float.POSITIVE_INFINITY) {
        progress = 1;
        LOG.debug("Illegal progress value found, progress is "
                + "Float.POSITIVE_INFINITY. Progress will be changed to 1");
    }
    this.progress = progress;
}

From source file:net.iponweb.hadoop.streaming.avro.IOWJsonDecoder.java

@Override
public float readFloat() throws IOException {
    advance(Symbol.FLOAT);//from   www. j  a  va 2 s.co m
    if (in.getCurrentToken().isNumeric()) {
        float result = in.getFloatValue();
        in.nextToken();
        return result;
    } else {
        try {
            String s = in.getText();
            in.nextToken();
            if (s.equals("NaN")) {
                return Float.NaN;
            } else if (s.equals("-Inf")) {
                return Float.NEGATIVE_INFINITY;
            } else if (s.equals("+Inf")) {
                return Float.POSITIVE_INFINITY;
            } else {
                return Float.parseFloat(s);
            }
        } catch (Exception e) {
            throw error("float (" + e.getMessage() + ")");
        }
    }
}

From source file:com.orthancserver.DicomDecoder.java

private String[] SortSlicesBy3D(OrthancConnection c, JSONArray instances) throws IOException {
    ArrayList<Slice> slices = new ArrayList<Slice>();
    float normal[] = null;

    float minDistance = Float.POSITIVE_INFINITY;
    float maxDistance = Float.NEGATIVE_INFINITY;

    for (int i = 0; i < instances.size(); i++) {
        String uuid = (String) instances.get(i);
        JSONObject instance = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags?simplify");
        if (!instance.containsKey("ImageOrientationPatient") || !instance.containsKey("ImagePositionPatient")) {
            return null;
        }/*from  w  w  w  .  ja  v a 2 s . co  m*/

        if (i == 0) {
            String[] tokens = ((String) instance.get("ImageOrientationPatient")).split("\\\\");
            if (tokens.length != 6) {
                return null;
            }

            float cosines[] = new float[6];
            for (int j = 0; j < 6; j++) {
                cosines[j] = Float.parseFloat(tokens[j]);
            }

            normal = new float[] { cosines[1] * cosines[5] - cosines[2] * cosines[4],
                    cosines[2] * cosines[3] - cosines[0] * cosines[5],
                    cosines[0] * cosines[4] - cosines[1] * cosines[3] };
        }

        String[] tokens = ((String) instance.get("ImagePositionPatient")).split("\\\\");
        if (tokens.length != 3) {
            return null;
        }

        float distance = 0;
        for (int j = 0; j < 3; j++) {
            distance += normal[j] * Float.parseFloat(tokens[j]);
        }

        minDistance = Math.min(minDistance, distance);
        maxDistance = Math.max(minDistance, distance);
        slices.add(new Slice(distance, uuid));
    }

    if (maxDistance - minDistance < 0.001) {
        return null;
    }

    return SortSlices(slices);
}

From source file:org.deeplearning4j.optimize.solvers.BackTrackLineSearch.java

/**
 * @param parameters      the parameters to optimize
 * @param gradients       the line/rate of change
 * @param searchDirection the point for the line search to go in
 * @return the next step size/*from  w w w . j a v a  2  s  .com*/
 * @throws InvalidStepException
 */
@Override
public double optimize(INDArray parameters, INDArray gradients, INDArray searchDirection)
        throws InvalidStepException {
    double test, stepMin, step, step2, oldStep, tmpStep;
    double rhs1, rhs2, a, b, disc, score, scoreAtStart, score2;
    minObjectiveFunction = (stepFunction instanceof NegativeDefaultStepFunction
            || stepFunction instanceof NegativeGradientStepFunction);

    Level1 l1Blas = Nd4j.getBlasWrapper().level1();

    double sum = l1Blas.nrm2(searchDirection);
    double slope = -1f * Nd4j.getBlasWrapper().dot(searchDirection, gradients);

    log.debug("slope = {}", slope);

    INDArray maxOldParams = abs(parameters);
    Nd4j.getExecutioner().exec(new ScalarSetValue(maxOldParams, 1));
    INDArray testMatrix = abs(gradients).divi(maxOldParams);
    test = testMatrix.max(Integer.MAX_VALUE).getDouble(0);

    step = 1.0; // initially, step = 1.0, i.e. take full Newton step
    stepMin = relTolx / test; // relative convergence tolerance
    oldStep = 0.0;
    step2 = 0.0;

    score = score2 = scoreAtStart = layer.score();
    double bestScore = score;
    double bestStepSize = 1.0;

    if (log.isTraceEnabled()) {
        double norm1 = l1Blas.asum(searchDirection);
        int infNormIdx = l1Blas.iamax(searchDirection);
        double infNorm = FastMath.max(Float.NEGATIVE_INFINITY, searchDirection.getDouble(infNormIdx));
        log.trace("ENTERING BACKTRACK\n");
        log.trace("Entering BackTrackLineSearch, value = " + scoreAtStart + ",\ndirection.oneNorm:" + norm1
                + "  direction.infNorm:" + infNorm);
    }
    if (sum > stepMax) {
        log.warn("Attempted step too big. scaling: sum= {}, stepMax= {}", sum, stepMax);
        searchDirection.muli(stepMax / sum);
    }

    //        if (slope >= 0.0) {
    //            throw new InvalidStepException("Slope " + slope + " is >= 0.0. Expect slope < 0.0 when minimizing objective function");
    //        }

    // find maximum lambda
    // converge when (delta x) / x < REL_TOLX for all coordinates.
    // the largest step size that triggers this threshold is precomputed and saved in stepMin
    // look for step size in direction given by "line"
    INDArray candidateParameters = null;
    for (int iteration = 0; iteration < maxIterations; iteration++) {
        if (log.isTraceEnabled()) {
            log.trace("BackTrack loop iteration {} : step={}, oldStep={}", iteration, step, oldStep);
            log.trace("before step, x.1norm: {} \nstep: {} \noldStep: {}", parameters.norm1(Integer.MAX_VALUE),
                    step, oldStep);
        }

        if (step == oldStep)
            throw new IllegalArgumentException("Current step == oldStep");

        // step
        candidateParameters = parameters.dup('f');
        stepFunction.step(candidateParameters, searchDirection, step);
        oldStep = step;

        if (log.isTraceEnabled()) {
            double norm1 = l1Blas.asum(candidateParameters);
            log.trace("after step, x.1norm: " + norm1);
        }

        // check for convergence on delta x
        if ((step < stepMin) || Nd4j.getExecutioner()
                .execAndReturn(new Eps(parameters, candidateParameters,
                        Shape.toOffsetZeroCopy(candidateParameters, 'f'), candidateParameters.length()))
                .sum(Integer.MAX_VALUE).getDouble(0) == candidateParameters.length()) {
            score = setScoreFor(parameters);
            log.debug(
                    "EXITING BACKTRACK: Jump too small (stepMin = {}). Exiting and using original params. Score = {}",
                    stepMin, score);
            return 0.0;
        }

        score = setScoreFor(candidateParameters);
        log.debug("Model score after step = {}", score);

        //Score best step size for use if we terminate on maxIterations
        if ((minObjectiveFunction && score < bestScore) || (!minObjectiveFunction && score > bestScore)) {
            bestScore = score;
            bestStepSize = step;
        }

        //Sufficient decrease in cost/loss function (Wolfe condition / Armijo condition)
        if (minObjectiveFunction && score <= scoreAtStart + ALF * step * slope) {
            log.debug(
                    "Sufficient decrease (Wolfe cond.), exiting backtrack on iter {}: score={}, scoreAtStart={}",
                    iteration, score, scoreAtStart);
            if (score > scoreAtStart)
                throw new IllegalStateException(
                        "Function did not decrease: score = " + score + " > " + scoreAtStart + " = oldScore");
            return step;
        }

        //Sufficient increase in cost/loss function (Wolfe condition / Armijo condition)
        if (!minObjectiveFunction && score >= scoreAtStart + ALF * step * slope) {
            log.debug("Sufficient increase (Wolfe cond.), exiting backtrack on iter {}: score={}, bestScore={}",
                    iteration, score, scoreAtStart);
            if (score < scoreAtStart)
                throw new IllegalStateException("Function did not increase: score = " + score + " < "
                        + scoreAtStart + " = scoreAtStart");
            return step;
        }

        // if value is infinite, i.e. we've jumped to unstable territory, then scale down jump
        else if (Double.isInfinite(score) || Double.isInfinite(score2) || Double.isNaN(score)
                || Double.isNaN(score2)) {
            log.warn("Value is infinite after jump. oldStep={}. score={}, score2={}. Scaling back step size...",
                    oldStep, score, score2);
            tmpStep = .2 * step;
            if (step < stepMin) { //convergence on delta x
                score = setScoreFor(parameters);
                log.warn(
                        "EXITING BACKTRACK: Jump too small (step={} < stepMin={}). Exiting and using previous parameters. Value={}",
                        step, stepMin, score);
                return 0.0;
            }
        }

        // backtrack

        else if (minObjectiveFunction) {
            if (step == 1.0) // first time through
                tmpStep = -slope / (2.0 * (score - scoreAtStart - slope));
            else {
                rhs1 = score - scoreAtStart - step * slope;
                rhs2 = score2 - scoreAtStart - step2 * slope;
                if (step == step2)
                    throw new IllegalStateException(
                            "FAILURE: dividing by step-step2 which equals 0. step=" + step);
                double stepSquared = step * step;
                double step2Squared = step2 * step2;
                a = (rhs1 / stepSquared - rhs2 / step2Squared) / (step - step2);
                b = (-step2 * rhs1 / stepSquared + step * rhs2 / step2Squared) / (step - step2);
                if (a == 0.0)
                    tmpStep = -slope / (2.0 * b);
                else {
                    disc = b * b - 3.0 * a * slope;
                    if (disc < 0.0) {
                        tmpStep = 0.5 * step;
                    } else if (b <= 0.0)
                        tmpStep = (-b + FastMath.sqrt(disc)) / (3.0 * a);
                    else
                        tmpStep = -slope / (b + FastMath.sqrt(disc));
                }
                if (tmpStep > 0.5 * step)
                    tmpStep = 0.5 * step; // lambda <= 0.5 lambda_1
            }
        } else {
            if (step == 1.0) // first time through
                tmpStep = -slope / (2.0 * (scoreAtStart - score - slope));
            else {
                rhs1 = scoreAtStart - score - step * slope;
                rhs2 = scoreAtStart - score2 - step2 * slope;
                if (step == step2)
                    throw new IllegalStateException(
                            "FAILURE: dividing by step-step2 which equals 0. step=" + step);
                double stepSquared = step * step;
                double step2Squared = step2 * step2;
                a = (rhs1 / stepSquared - rhs2 / step2Squared) / (step - step2);
                b = (-step2 * rhs1 / stepSquared + step * rhs2 / step2Squared) / (step - step2);
                if (a == 0.0)
                    tmpStep = -slope / (2.0 * b);
                else {
                    disc = b * b - 3.0 * a * slope;
                    if (disc < 0.0) {
                        tmpStep = 0.5 * step;
                    } else if (b <= 0.0)
                        tmpStep = (-b + FastMath.sqrt(disc)) / (3.0 * a);
                    else
                        tmpStep = -slope / (b + FastMath.sqrt(disc));
                }
                if (tmpStep > 0.5 * step)
                    tmpStep = 0.5 * step; // lambda <= 0.5 lambda_1
            }

        }

        step2 = step;
        score2 = score;
        log.debug("tmpStep: {}", tmpStep);
        step = Math.max(tmpStep, .1f * step); // lambda >= .1*Lambda_1
    }

    if (minObjectiveFunction && bestScore < scoreAtStart) {
        //Return best step size
        log.debug(
                "Exited line search after maxIterations termination condition; bestStepSize={}, bestScore={}, scoreAtStart={}",
                bestStepSize, bestScore, scoreAtStart);
        return bestStepSize;
    } else if (!minObjectiveFunction && bestScore > scoreAtStart) {
        //Return best step size
        log.debug(
                "Exited line search after maxIterations termination condition; bestStepSize={}, bestScore={}, scoreAtStart={}",
                bestStepSize, bestScore, scoreAtStart);
        return bestStepSize;
    } else {
        log.debug(
                "Exited line search after maxIterations termination condition; score did not improve (bestScore={}, scoreAtStart={}). Resetting parameters",
                bestScore, scoreAtStart);
        setScoreFor(parameters);
        return 0.0;
    }
}

From source file:com.yahoo.egads.models.adm.AdaptiveKernelDensityChangePointDetector.java

public ArrayList<Integer> detectChangePoints(float[] residuals, int preWindowSize, int postWindowSize,
        float confidence) {
    int n = residuals.length;
    score = new float[n];
    level = new float[n];
    ArrayList<Integer> changePoints = new ArrayList<Integer>();

    float maxScore = Float.NEGATIVE_INFINITY;
    int maxIndex = -1;
    float delta = 0.00000001F;
    int counter = 0;

    for (int i = 0; i < n; ++i, ++counter) {
        float[] temp = computeKLScore(residuals[i], preWindowSize, postWindowSize, confidence);
        score[i] = temp[0];//from  w ww .  j a  va2s.  c  o m
        level[i] = temp[1];
        if (score[i] > delta) {
            if (score[i] > maxScore) {
                maxScore = score[i];
                maxIndex = i;
            }
        } else if (score[i] < -delta) {
            if (maxIndex >= 0) {
                if (counter - i + maxIndex > postWindowSize) {
                    changePoints.add(maxIndex - postWindowSize + 1);
                    counter = i - maxIndex;
                }
                maxScore = Float.NEGATIVE_INFINITY;
                maxIndex = -1;
            }
        }
    }

    if (maxIndex >= 0) {
        changePoints.add(maxIndex - postWindowSize + 1);
    }

    return changePoints;
}

From source file:org.shaman.terrain.polygonal.GraphToHeightmap.java

private void addPerlinNoise() {
    float[] perlinFactors = new float[NOISE_OCTAVES];
    Noise[] noiseGenerators = new Noise[NOISE_OCTAVES];
    for (int i = 0; i < NOISE_OCTAVES; ++i) {
        noiseGenerators[i] = new Noise(rand.nextLong());
        perlinFactors[i] = (float) (BASE_FREQUENCY * Math.pow(NOISE_OCTAVE_FACTOR, i));
    }//from  w  ww. java 2  s.c  om
    Heightmap values = new Heightmap(size);
    float min = Float.POSITIVE_INFINITY;
    float max = Float.NEGATIVE_INFINITY;
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            float roughness = noise[x][y][1];
            //multi-fractal perlin noise
            double perlin = 0;
            for (int i = 0; i < NOISE_OCTAVES; ++i) {
                perlin += noiseGenerators[i].noise(perlinFactors[i] * x, perlinFactors[i] * y)
                        / Math.pow(NOISE_OCTAVE_FACTOR, i * (1 - roughness));
            }
            values.setHeightAt(x, y, (float) perlin);
            min = (float) Math.min(perlin, min);
            max = (float) Math.max(perlin, max);
        }
    }
    float factor = 1f / (max - min);
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            float amplitude = noise[x][y][0];
            float perlin = (values.getHeightAt(x, y) - min) * factor;
            perlin *= amplitude * PERLIN_NOISE_SCALE;
            heightmap.adjustHeightAt(x, y, perlin);
        }
    }
    LOG.info("perlin noise added");
}

From source file:com.uphyca.stetho_realm.Database.java

private List<Object> flattenRows(Table table, int limit, boolean addRowIndex) {
    Util.throwIfNot(limit >= 0);
    final List<Object> flatList = new ArrayList<>();
    long numColumns = table.getColumnCount();

    final RowFetcher rowFetcher = RowFetcher.getInstance();
    for (long row = 0; row < limit && row < table.size(); row++) {
        final RowWrapper rowData = RowWrapper.wrap(rowFetcher.getRow(table, row));
        if (addRowIndex) {
            flatList.add(rowData.getIndex());
        }//from   w w  w  .j a  v  a 2 s  .c  om
        for (int column = 0; column < numColumns; column++) {
            switch (rowData.getColumnType(column)) {
            case INTEGER:
                flatList.add(rowData.getLong(column));
                break;
            case BOOLEAN:
                flatList.add(rowData.getBoolean(column));
                break;
            case STRING:
                flatList.add(rowData.getString(column));
                break;
            case BINARY:
                flatList.add(rowData.getBinaryByteArray(column));
                break;
            case FLOAT:
                final float aFloat = rowData.getFloat(column);
                if (Float.isNaN(aFloat)) {
                    flatList.add("NaN");
                } else if (aFloat == Float.POSITIVE_INFINITY) {
                    flatList.add("Infinity");
                } else if (aFloat == Float.NEGATIVE_INFINITY) {
                    flatList.add("-Infinity");
                } else {
                    flatList.add(aFloat);
                }
                break;
            case DOUBLE:
                final double aDouble = rowData.getDouble(column);
                if (Double.isNaN(aDouble)) {
                    flatList.add("NaN");
                } else if (aDouble == Double.POSITIVE_INFINITY) {
                    flatList.add("Infinity");
                } else if (aDouble == Double.NEGATIVE_INFINITY) {
                    flatList.add("-Infinity");
                } else {
                    flatList.add(aDouble);
                }
                break;
            case DATE:
                flatList.add(rowData.getDate(column));
                break;
            case LINK:
                flatList.add(rowData.getLink(column));
                break;
            case LINK_LIST:
                flatList.add(rowData.getLinkList(column));
                break;
            default:
                flatList.add("unknown column type: " + rowData.getColumnType(column));
                break;
            }
        }
    }

    if (limit < table.size()) {
        for (int column = 0; column < numColumns; column++) {
            flatList.add("{truncated}");
        }
    }

    return flatList;
}