Example usage for java.lang Math floor

List of usage examples for java.lang Math floor

Introduction

In this page you can find the example usage for java.lang Math floor.

Prototype

public static double floor(double a) 

Source Link

Document

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:com.v2soft.misto.Providers.MapnikProvider.java

@Override
public TileInfo getTileInfoByLocation(Location location, int zoom) {
    TileInfo res = new TileInfo();
    res.setHeight(TILE_SIZE);/*from w w  w  .  j  a v  a  2 s .  com*/
    res.setWidth(TILE_SIZE);
    res.setZoom(zoom);
    res.setLatitude((int) Math.floor((1 - Math.log(Math.tan(location.getLatitude() * Math.PI / 180)
            + 1 / Math.cos(location.getLatitude() * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom)));
    double longitude = Math.floor((location.getLongitude() + 180) * worldTilesCount(zoom) / 360);
    res.setLongitude((int) longitude);
    return res;
}

From source file:com.muk.services.facades.impl.DefaultPaymentFacade.java

@Override
public Map<String, Object> startPayment(PaymentRequest paymentRequest, UriComponents redirectComponents) {
    Map<String, Object> response = new HashMap<String, Object>();
    final ObjectNode payload = JsonNodeFactory.instance.objectNode();

    if (ServiceConstants.PaymentMethods.paypalExpress.equals(paymentRequest.getPaymentMethod())) {
        payload.put("intent", "sale");
        final ObjectNode redirectUrls = payload.putObject("redirect_urls");
        redirectUrls.put("return_url", redirectComponents.toUriString() + "/id/redirect");
        redirectUrls.put("cancel_url", redirectComponents.toUriString() + "/id/cancel");
        final ObjectNode payer = payload.putObject("payer");
        payer.put("payment_method", "paypal");
        final ArrayNode transactions = payload.putArray("transactions");
        final ObjectNode transaction = transactions.addObject();
        transaction.put("description", paymentRequest.getService());
        transaction.putObject("amount").put("total", paymentRequest.getPrice()).put("currency", "USD");

        response = paypalPaymentService.startPayment(payload);
    } else if (ServiceConstants.PaymentMethods.stripe.equals(paymentRequest.getPaymentMethod())) {
        payload.put("amount", (long) Math.floor(paymentRequest.getPrice() * 100d));
        payload.put("currency", "usd");
        payload.put("description", paymentRequest.getService());
        payload.put("source", paymentRequest.getInfo());

        if (StringUtils.isNotBlank(paymentRequest.getEmail())) {
            payload.put("receipt_email", paymentRequest.getEmail());
        }//  w ww .  j  a va2  s. c o  m

        if (paymentRequest.getMetadata() != null) {
            final ObjectNode mds = payload.putObject("metadata");

            for (final Pair<String, String> pair : paymentRequest.getMetadata()) {
                mds.put(pair.getLeft(), pair.getRight());
            }
        }

        response = stripePaymentService.startPayment(payload);

    }

    return response;
}

From source file:lu.lippmann.cdb.lab.mds.UniversalMDS.java

/**
 * /*from w  ww .  j  a  v  a  2 s.  com*/
 * @param ds
 */
public UniversalMDS(final Instances ds, final MDSDistancesEnum distEnum, final MDSTypeEnum type) {
    this.ds = ds;
    try {
        this.fMds = ClassicMDS.doMDS(ds, distEnum, 2, 5000, true, false);

        this.distMatrixND = fMds.getCInstances().getDistanceMatrix();
        //Convert to double[][]
        final SimpleMatrix mdsCoords = fMds.getCoordinates();
        final int N = ds.numInstances();
        this.coordinates = new double[N][2];
        for (int i = 0; i < mdsCoords.numRows(); i++) {
            for (int j = 0; j < mdsCoords.numCols(); j++)
                this.coordinates[i][j] = mdsCoords.get(i, j);
        }

        /*
        double epsilon;
        int count = 0;
        do {
           epsilon = computeError(ds,type);
           for(int i = 0 ; i < N ; i++){
              placePoint(i,type,(int)Math.floor(Math.sqrt(count)),ds);
           }
           //System.out.println("Cost(1) : " + (epsilon-computeError(type))+"("+count+")");
           count++;
        }while(epsilon - computeError(ds,type) > THETA);// && count <= 100);
        //}while(Math.abs(epsilon - computeError(ds,type)) > THETA && count <= 100);
         */

        computeDistance2D();

        for (int iter = 1; iter <= 100; iter++) {
            double res = computeError(ds, type);

            for (int i = 0; i < N; i++) {
                for (int it = 1; it <= Math.floor(Math.sqrt(iter)); it++) {
                    double[][] xChap = computeIntersections(i, ds);
                    switch (type) {
                    case CLASSIC:
                        coordinates[i] = fRecenter(xChap, ds);
                        break;
                    case ROBUST:
                        coordinates[i] = rRecenter(i, xChap, ds);
                        break;
                    case SPHERICAL:
                        throw new IllegalStateException("Not implemented !");
                    default:
                        break;
                    }
                    computeDistance2D();
                }
            }

            double cost = (res - computeError(ds, type));
            System.out.println("Cost(2) : " + cost);
            //if(cost<THETA) break;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:nya.miku.wishmaster.http.client.DCP.java

private String getRandom() {
    return Long.toString((long) Math.floor(Math.random() * 1000000000));
}

From source file:org.brunocvcunha.instagram4j.requests.internal.InstagramUploadVideoJobRequest.java

@Override
public StatusResult execute() throws ClientProtocolException, IOException {

    String url = getUrl();//from  w  ww  .  j av  a2s .  co m
    log.info("URL Upload: " + url);

    HttpPost post = new HttpPost(url);
    post.addHeader("X-IG-Capabilities", "3Q4=");
    post.addHeader("X-IG-Connection-Type", "WIFI");
    post.addHeader("Cookie2", "$Version=1");
    post.addHeader("Accept-Language", "en-US");
    post.addHeader("Accept-Encoding", "gzip, deflate");
    post.addHeader("Content-Type", "application/octet-stream");
    post.addHeader("Session-ID", uploadId);
    post.addHeader("Connection", "keep-alive");
    post.addHeader("Content-Disposition", "attachment; filename=\"video.mp4\"");
    post.addHeader("job", uploadJob);
    post.addHeader("Host", "upload.instagram.com");
    post.addHeader("User-Agent", InstagramConstants.USER_AGENT);

    log.info("User-Agent: " + InstagramConstants.USER_AGENT);

    try (FileInputStream is = new FileInputStream(videoFile)) {
        byte[] videoData = MyStreamUtils.readContentBytes(is);

        //TODO: long ranges? need to handle?
        int requestSize = (int) Math.floor(videoData.length / 4.0);
        int lastRequestExtra = (int) (videoData.length - (requestSize * 3));

        for (int i = 0; i < 4; i++) {

            int start = i * requestSize;
            int end;
            if (i == 3) {
                end = i * requestSize + lastRequestExtra;
            } else {
                end = (i + 1) * requestSize;
            }

            int actualLength = (i == 3 ? lastRequestExtra : requestSize);

            String contentRange = String.format("bytes %s-%s/%s", start, end - 1, videoData.length);
            //post.setHeader("Content-Length", String.valueOf(end - start));
            post.setHeader("Content-Range", contentRange);

            byte[] range = Arrays.copyOfRange(videoData, start, start + actualLength);
            log.info("Total is " + videoData.length + ", sending " + actualLength + " (starting from " + start
                    + ") -- " + range.length + " bytes.");

            post.setEntity(EntityBuilder.create().setBinary(range).build());

            try (CloseableHttpResponse response = api.getClient().execute(post)) {
                int resultCode = response.getStatusLine().getStatusCode();
                String content = EntityUtils.toString(response.getEntity());
                log.info("Result of part " + i + ": " + content);

                post.releaseConnection();
                response.close();

                if (resultCode != 200 && resultCode != 201) {
                    throw new IllegalStateException("Failed uploading video (" + resultCode + "): " + content);
                }

            }

        }

        return new StatusResult("ok");
    }
}

From source file:it.units.malelab.ege.benchmark.mapper.MappingPropertiesFitness.java

public MappingPropertiesFitness(int genotypeSize, int n, int maxMappingDepth, Random random,
        List<Problem<String, NumericFitness>> problems, Property... properties) {
    this.maxMappingDepth = maxMappingDepth;
    this.problems = new LinkedHashMap<>();
    for (Problem<String, NumericFitness> problem : problems) {
        this.problems.put(problem, new CachedDistance<>(new LeavesEdit<String>()));
    }//from   w  w w .  j  a  v a  2s  .  c  o  m
    this.properties = properties;
    //build genotypes
    GeneticOperator<BitsGenotype> mutation = new ProbabilisticMutation(0.01d);
    BitsGenotypeFactory factory = new BitsGenotypeFactory(genotypeSize);
    Set<BitsGenotype> set = new LinkedHashSet<>();
    for (int i = 0; i < Math.floor(Math.sqrt(n)); i++) {
        set.addAll(
                consecutiveMutations(factory.build(random), (int) Math.floor(Math.sqrt(n)), mutation, random));
    }
    while (set.size() < n) {
        set.add(factory.build(random));
    }
    genotypes = new ArrayList<>(set);
    //pre compute geno dists
    Distance<Sequence<Boolean>> genotypeDistance = new Hamming<Boolean>();
    genotypeDistances = computeDistances(genotypes, (Distance) genotypeDistance);
}

From source file:com.caseystella.analytics.outlier.batch.rpca.RPCAOutlierAlgorithm.java

public double[][] VectorToMatrix(double[] x, int rows, int cols) {
    double[][] input2DArray = new double[rows][cols];
    for (int n = 0; n < x.length; n++) {
        int i = n % rows;
        int j = (int) Math.floor(n / rows);
        input2DArray[i][j] = x[n];//w w  w .  java2 s.co m
    }
    return input2DArray;
}

From source file:com.sciaps.utils.Util.java

public static Spectrum createAverage(Collection<? extends Spectrum> shots, double sampleRate) {

    Min minWL = new Min();
    Max maxWL = new Max();
    for (Spectrum shot : shots) {
        minWL.increment(shot.getValidRange().getMinimumDouble());
        maxWL.increment(shot.getValidRange().getMaximumDouble());
    }//w w  w.  ja v a 2 s . c  om

    double range = maxWL.getResult() - minWL.getResult();
    int numSamples = (int) Math.floor(range * sampleRate);
    double[][] data = new double[2][numSamples];
    Mean avgy = new Mean();
    for (int i = 0; i < numSamples; i++) {
        double x = minWL.getResult() + i * (1 / sampleRate);
        avgy.clear();
        for (Spectrum shot : shots) {
            if (shot.getValidRange().containsDouble(x)) {
                UnivariateFunction iv = shot.getIntensityFunction();
                double y = iv.value(x);
                avgy.increment(y);
            }
        }

        data[0][i] = x;
        data[1][i] = avgy.getResult();
    }

    RawDataSpectrum newSpectrum = new RawDataSpectrum(data);

    return newSpectrum;
}

From source file:de.codesourcery.planning.swing.DateAxis.java

public BoundingBox render(ITimelineCallback callback, boolean layoutOnly) {
    final Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);/* w  w w .ja v  a 2s . c om*/
    cal.set(Calendar.MILLISECOND, 0);
    Date currentDate = cal.getTime();

    final Date endDate = duration.addTo(startDate);

    BoundingBox lastLabel = null;

    final int labelSpacing = 10;

    final Graphics2D graphics = callback.getGraphics();
    final int fontHeight = graphics.getFontMetrics().getHeight();

    final double scalingFactor = getXScalingFactor(callback.getBoundingBox());
    final BoundingBox box = callback.getBoundingBox();
    double x = callback.getBoundingBox().getX();
    final int tickToLabelSpacing = 2;
    final int tickLength = fontHeight;
    final int axisHeight = fontHeight + tickLength + tickToLabelSpacing;
    final double xIncrement = Math.floor(tickDuration.toSeconds() * scalingFactor);

    final Color oldColor = graphics.getColor();
    //      
    while (currentDate.compareTo(endDate) <= 0) {
        final int currentX = (int) Math.floor(x);
        if (lastLabel == null || lastLabel.getMaxX() < x) {
            final String labelText = callback.getLabelProvider().getTimelineLabel(currentDate);
            if (!StringUtils.isBlank(labelText)) {
                final Rectangle2D stringBounds = callback.getStringBounds(labelText);

                if (!layoutOnly) {
                    graphics.setColor(Color.BLACK);
                    // draw tick
                    final Stroke oldStroke = graphics.getStroke();
                    graphics.setStroke(new BasicStroke(2.0f));
                    graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                            box.getY() + fontHeight + tickToLabelSpacing);
                    graphics.setStroke(oldStroke);

                    // draw label
                    callback.drawString(Color.BLACK, currentX, box.getY(), labelText);
                }

                final BoundingBox labelBox = new BoundingBox(currentX, box.getY(),
                        currentX + (int) stringBounds.getWidth() + labelSpacing,
                        box.getY() + (int) stringBounds.getHeight());

                if (lastLabel == null) {
                    lastLabel = labelBox;
                } else {
                    lastLabel.add(labelBox);
                }

            }
        } else {
            // draw short tick
            if (!layoutOnly) {

                final int halfTickHeight = (int) Math.floor(tickLength / 2.0d);

                graphics.drawLine(currentX, box.getY() + axisHeight, currentX,
                        box.getY() + axisHeight - halfTickHeight);
            }
        }

        // draw part of axis
        if (!layoutOnly) {
            graphics.drawLine((int) x, box.getY() + axisHeight, (int) (x + xIncrement),
                    box.getY() + axisHeight);
        }
        x += xIncrement;
        currentDate = tickDuration.addTo(currentDate);
    }

    callback.getGraphics().setColor(oldColor);
    final BoundingBox result = lastLabel != null ? lastLabel : new BoundingBox(0, 0, 0, 0);
    result.incHeight(axisHeight);
    return result;
}

From source file:com.karus.danktitles.commands.HelpSubcommand.java

@Override
public void execute(CommandSender sender, String[] args) {

    // Methods inheritied from CommandChecker
    if (!checkLength(sender, args, 1, 3))
        return;//  w w  w.j  ava  2s  .  c o m
    if (!checkSender(sender, "danktitles.help"))
        return;

    LinkedHashMap<String, MutablePair<String, String>> parsedCommands;

    // Checks if the list needs to be filtered
    if (args.length == 1 || args[1].equals("all")) {
        parsedCommands = new LinkedHashMap<>(
                commands.entrySet().stream().filter(entry -> sender.hasPermission(entry.getValue().getLeft()))
                        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
    } else {
        parsedCommands = new LinkedHashMap<>(commands.entrySet().stream().filter(
                entry -> entry.getKey().contains(args[1]) && sender.hasPermission(entry.getValue().getLeft()))
                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
    }

    if (parsedCommands.isEmpty()) {
        sender.sendMessage(ChatColor.RED + "No matches found.");
        return;
    }

    if (args.length == 3) {
        try {
            page = Integer.parseInt(args[2]);
        } catch (NumberFormatException e) {
            sender.sendMessage(ChatColor.RED + "Invalid page number!");
            return;
        }
    } else {
        page = 1;
    }

    int totalPages = (int) Math.max(1, Math.floor(parsedCommands.size() / SIZE));

    if (page <= 0 || page > totalPages) {
        sender.sendMessage(ChatColor.RED + "Invalid page number!");
        return;
    }

    sender.sendMessage(ChatColor.GOLD + "[Commands - (" + ChatColor.RED + page + "/" + totalPages
            + ChatColor.GOLD + ") ]");

    ArrayList<String> keys = new ArrayList<>(parsedCommands.keySet());

    IntStream.range(page * SIZE - SIZE, parsedCommands.size()).limit(SIZE)
            .forEach(i -> sender.sendMessage(ChatColor.GOLD + commands.get(keys.get(i)).getRight()));

}