Example usage for java.lang Math ceil

List of usage examples for java.lang Math ceil

Introduction

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

Prototype

public static double ceil(double a) 

Source Link

Document

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:feedme.controller.HomePageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from  w w w .j ava 2 s. c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    HashMap<String, Integer> category = new HashMap<>();
    List<Restaurant> restaurants;

    DbHPOnLoad dbPageOnLoad = new DbHPOnLoad();//creating a DbHPOnLoad object

    List<Restaurant> allResturent = new DbAdminManagmentTools().getAllRestaurants();

    int page = 1;
    int recordsPerPage = 6;

    if (request.getParameter("page") != null) {
        page = Integer.parseInt(request.getParameter("page"));
    }

    int noOfRecords = allResturent.size();
    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);

    category = dbPageOnLoad.getCategories();//getting a categories
    restaurants = new DbRestaurantsManagement()
            .getNextRecentRestaurantsByCatAndCity((page - 1) * recordsPerPage, recordsPerPage, 0, "Asd");//get the last 6 new restaurants

    if (isAjaxRequest(request)) {
        try {
            JSONObject restObj = new JSONObject();
            JSONArray restArray = new JSONArray();
            for (Restaurant rest : restaurants) {
                restArray.put(new JSONObject().put("resturent", rest.toJson()));
            }
            restObj.put("resturent", restArray);
            restObj.put("noOfPages", noOfPages);
            restObj.put("currentPage", page);
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.print(restObj);
            response.getWriter().flush();
            return;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    List<String> cities = dbPageOnLoad.getCities();
    if (request.getSession().getAttribute("shoppingCart") == null) {
        request.getSession().setAttribute("shoppingCart", new Order());//crete a new shopping cart
    }

    List<RestaurantRanking> rankings = dbPageOnLoad.getRestRandomComments(5);//getting a random rankings from DB

    for (RestaurantRanking re : rankings) {//looping over the rankings
        re.setResturent(new DbRestaurantsManagement().getRestaurantById(re.getRestId()));
    }

    request.setAttribute("noOfPages", noOfPages);
    request.setAttribute("currentPage", page);
    request.setAttribute("category", category);//send the categories
    request.setAttribute("cities", cities);//send the cities
    request.setAttribute("restaurants", restaurants);//send the restaurants
    request.setAttribute("rankings", rankings);//send the rankings

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/index.jsp");//send a ajsp file
    dispatcher.forward(request, response);
    return;
}

From source file:com.wuliu.biz.orderdetail.engine.impl.OrderDetailMergeEngineImpl.java

@Override
public List<WuliuMergedOrderDetailModel> mergeOrderDetail(List<WuliuOrderDetailModel> wuliuOrderDetailModels,
        Long weightPrice, Long volumnPrice) {
    List<WuliuMergedOrderDetailModel> ret = new ArrayList<WuliuMergedOrderDetailModel>();

    if (CollectionUtils.isEmpty(wuliuOrderDetailModels)) {
        return ret;
    }//from ww w  .  j av  a 2s.  c o m

    WuliuMergedOrderDetailModel weightModel = null;
    WuliuMergedOrderDetailModel volumnModel = null;

    for (WuliuOrderDetailModel item : wuliuOrderDetailModels) {
        Long weightCost = getWeightCost(item, weightPrice);
        Long volumnCost = getVolumnCost(item, volumnPrice);
        if (weightCost * 1000000 > volumnCost) {
            if (weightModel == null) {
                weightModel = new WuliuMergedOrderDetailModel();
                weightModel.setType(WuliuMergedOrderDetailConst.TYPE_WEIGHT);
            }

            add(weightModel, item.getWeight(), 0L, weightCost, item.getCount());
        } else {
            if (volumnModel == null) {
                volumnModel = new WuliuMergedOrderDetailModel();
                volumnModel.setType(WuliuMergedOrderDetailConst.TYPE_VOLUMN);
            }

            add(volumnModel, 0, getVolumn(item), volumnCost, item.getCount());
        }
    }

    if (weightModel != null) {
        if (weightModel.getCost() % 100000L == 0) {
            weightModel.setCost(weightModel.getCost() / 100000);
        } else {
            weightModel.setCost((long) Math.ceil(weightModel.getCost() / 100000.0));
        }

        DecimalFormat df = new DecimalFormat("0.#");
        if (weightModel.getWeight() > 0) {
            weightModel.setWeightForDisplay(df.format(weightModel.getWeight() / 1000.0));
        }

        ret.add(weightModel);
    }

    if (volumnModel != null) {
        if (volumnModel.getCost() % 100000000000L == 0) {
            volumnModel.setCost(volumnModel.getCost() / 100000000000L);
        } else {
            volumnModel.setCost((long) Math.ceil(volumnModel.getCost() / 100000000000.0f));
        }
        ret.add(volumnModel);

        DecimalFormat df = new DecimalFormat("0.###");
        if (volumnModel.getVolumn() > 0) {
            volumnModel.setVolumnForDisplay(df.format(Math.ceil(volumnModel.getVolumn() / 1000000.0) / 1000.0));
        }
    }

    return ret;
}

From source file:com.l2jfree.L2Config.java

/**
 * Returns application lifetime in a short string.
 * // w  w w. j av  a 2 s .  co m
 * @return time since launch
 */
public static String getShortUptime() {
    final long uptimeInSec = (long) Math.ceil(ManagementFactory.getRuntimeMXBean().getUptime() / 1000.0);

    final long s = uptimeInSec / 1 % 60;
    final long m = uptimeInSec / 60 % 60;
    final long h = uptimeInSec / 3600 % 24;
    final long d = uptimeInSec / 86400;

    final L2TextBuilder tb = new L2TextBuilder();

    if (d > 0)
        tb.append(d + "d");

    if (h > 0 || tb.length() != 0)
        tb.append(h + "h");

    if (m > 0 || tb.length() != 0)
        tb.append(m + "m");

    if (s > 0 || tb.length() != 0)
        tb.append(s + "s");

    return tb.moveToString();
}

From source file:ch.jamiete.hilda.music.commands.MusicNowPlayingCommand.java

@Override
public final void execute(final Message message, final String[] args, final String label) {
    final MusicServer server = this.manager.getServer(message.getGuild());

    if ((server == null) || (server.getPlaying() == null)) {
        this.reply(message, "There isn't anything playing.");
        return;//from w  w w .j  a  v a  2 s  .c o m
    }

    final MessageBuilder mb = new MessageBuilder();
    final QueueItem playing = server.getPlaying();

    mb.append("Now playing ").append(Util.sanitise(MusicManager.getFriendly(playing.getTrack()))).append("\n");

    if (playing.getTrack().getInfo().length != 0L) {
        mb.append("\n").append("Time: ", Formatting.BOLD);
        mb.append(DurationFormatUtils.formatDuration(playing.getTrack().getPosition(), "HH:mm:ss", true));
        mb.append("/");
        mb.append(DurationFormatUtils.formatDuration(playing.getTrack().getDuration(), "HH:mm:ss", true));
    }

    mb.append("\n");
    mb.append("Requestor: ", Formatting.BOLD)
            .append(message.getGuild().getMemberById(playing.getUserId()).getEffectiveName());

    mb.append("\n");
    mb.append("Skip votes: ", Formatting.BOLD);
    final int needed = (int) Math.ceil((double) server.getUsers() / 2);
    mb.append(server.getSkips()).append("/").append(needed);

    this.reply(message, mb.build());
}

From source file:web.UsersController.java

/**
 *
 * @param pageid//from  w w w. ja  v a  2s.  c  o m
 * @param request
 * @return
 */
@RequestMapping("/user/viewuser/{pageid}")
public ModelAndView viewusers(@PathVariable int pageid, HttpServletRequest request) {
    int total = 10;
    int start = 1;

    if (pageid != 1) {
        start = (pageid - 1) * total + 1;
    }

    List<Users> list = dao.getUsersByPage(start, total);

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("list", list);

    int count = dao.getUsersCount();
    context.put("pages", Math.ceil((float) count / (float) total));

    context.put("page", pageid);

    Message msg = (Message) request.getSession().getAttribute("message");

    if (msg != null) {
        context.put("message", msg);
        request.getSession().removeAttribute("message");
    }

    return new ModelAndView("viewusers", context);
}

From source file:gobblin.ingestion.google.webmaster.TrieBasedProducerJob.java

/**
 * The implementation here will first partition the job by pages, and then by dates.
 * @return//from   www .  jav  a  2s  . c o m
 */
@Override
public List<? extends ProducerJob> partitionJobs() {
    UrlTrieNode root = _jobNode.getRight();
    if (isOperatorEquals() || root.getSize() == 1) {
        //Either at an Equals-Node or a Leaf-Node, both of which actually has actual size 1.
        return super.partitionJobs();
    } else {
        if (_groupSize <= 1) {
            throw new RuntimeException("This is impossible. When group size is 1, the operator must be equals");
        }

        UrlTrie trie = new UrlTrie(getPage(), root);
        int gs = Math.min(root.getSize(), _groupSize);

        UrlTriePrefixGrouper grouper = new UrlTriePrefixGrouper(trie, (int) Math.ceil(gs / 2.0));

        List<TrieBasedProducerJob> jobs = new ArrayList<>();
        while (grouper.hasNext()) {
            jobs.add(new TrieBasedProducerJob(_startDate, _endDate, grouper.next(), grouper.getGroupSize()));
        }
        return jobs;
    }
}

From source file:org.whispersystems.textsecuregcm.limits.RateLimiter.java

private void setBucket(String key, LeakyBucket bucket) {
    try (Jedis jedis = cacheClient.getResource()) {
        String serialized = bucket.serialize(mapper);
        jedis.setex(getBucketName(key), (int) Math.ceil((bucketSize / leakRatePerMillis) / 1000), serialized);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException(e);
    }//ww  w  . j  a  v  a  2 s .  c o m
}

From source file:com.linkedin.kmf.common.Utils.java

/**
 * Create the topic that the monitor uses to monitor the cluster.  This method attempts to create a topic so that all
 * the brokers in the cluster will have partitionToBrokerRatio partitions.  If the topic exists, but has different parameters
 * then this does nothing to update the parameters.
 *
 * TODO: Do we care about rack aware mode?  I would think no because we want to spread the topic over all brokers.
 * @param zkUrl zookeeper connection url
 * @param topic topic name/*from w w w  .  j ava  2 s  .  com*/
 * @param replicationFactor the replication factor for the topic
 * @param partitionToBrokerRatio This is multiplied by the number brokers to compute the number of partitions in the topic.
 * @param topicConfig additional parameters for the topic for example min.insync.replicas
 * @return the number of partitions created
 */
public static int createMonitoringTopicIfNotExists(String zkUrl, String topic, int replicationFactor,
        double partitionToBrokerRatio, Properties topicConfig) {
    ZkUtils zkUtils = ZkUtils.apply(zkUrl, ZK_SESSION_TIMEOUT_MS, ZK_CONNECTION_TIMEOUT_MS,
            JaasUtils.isZkSecurityEnabled());
    try {
        if (AdminUtils.topicExists(zkUtils, topic)) {
            LOG.info("Monitoring topic \"" + topic + "\" already exists.");
            return getPartitionNumForTopic(zkUrl, topic);
        }

        int brokerCount = zkUtils.getAllBrokersInCluster().size();

        int partitionCount = (int) Math.ceil(brokerCount * partitionToBrokerRatio);

        int defaultMinIsr = Math.max(replicationFactor - 1, 1);
        if (!topicConfig.containsKey(KafkaConfig.MinInSyncReplicasProp())) {
            topicConfig.setProperty(KafkaConfig.MinInSyncReplicasProp(), Integer.toString(defaultMinIsr));
        }

        try {
            AdminUtils.createTopic(zkUtils, topic, partitionCount, replicationFactor, topicConfig,
                    RackAwareMode.Enforced$.MODULE$);
        } catch (TopicExistsException tee) {
            //There is a race condition with the consumer.
            LOG.info("Monitoring topic \"" + topic + "\" already exists (caught exception).");
            return getPartitionNumForTopic(zkUrl, topic);
        }
        LOG.info("Created monitoring topic \"" + topic + "\" with " + partitionCount
                + " partitions, min ISR of " + topicConfig.get(KafkaConfig.MinInSyncReplicasProp())
                + " and replication factor of " + replicationFactor + ".");

        return partitionCount;
    } finally {
        zkUtils.close();
    }
}

From source file:com.trenako.web.tags.CategoriesListTags.java

@Override
protected int writeTagContent(JspWriter jspWriter, String contextPath) throws JspException {

    Assert.notNull(getBrand(), "Brand is required");

    this.contextPath = contextPath;
    try {//from w w  w. jav a2s.c  o  m

        if (getBrand().getScales() == null || getBrand().getScales().size() == 0) {
            jspWriter.write(snippet(div().cssClass("row-fluid")).build());
            return SKIP_BODY;
        }

        List<HtmlTag> rows = new ArrayList<HtmlTag>();

        int numOfScales = getBrand().getScales().size();
        int numOfRows = (int) Math.ceil(numOfScales / (double) getColumns());

        String[] scales = (String[]) getBrand().getScales().toArray(new String[numOfScales]);

        for (int row = 0; row < numOfRows; row++) {
            HtmlTag[] cols = new HtmlTag[getColumns()];

            for (int col = 0; col < getColumns(); col++) {
                int n = col + (getColumns() * row);
                if (scales.length > n) {
                    String slug = scales[n];

                    Scale scale = service.findBySlug(slug);
                    if (scale == null) {
                        continue;
                    }

                    cols[col] = div(buildScale(scale)).cssClass(spanClass());
                }
                // pad the rows with empty columns
                else {
                    cols[col] = div().cssClass(spanClass());
                }
            }

            rows.add(div(cols).cssClass("row-fluid"));
        }

        jspWriter.write(snippet(tags(rows)).build());

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

    return SKIP_BODY;
}

From source file:edu.asu.ca.kaushik.algorithms.randomized.lll.TwoStageSimpleMT.java

@Override
public CA generateCA(int t, int k, int v) {
    assert (k >= 2 * t);
    this.N = this.twoStageSimpleBound(t, k, v);
    int numMinUncovInt = (int) Math.ceil(Helper.expectNumUncovInt(t, k, v, this.N));
    LLLCA partialCa = new LLLCA(t, k, v, this.N);
    ColGrIterator clGrIt = new ColGrIterator2(t, k);
    List<Interaction> uncovInts;
    int uncovIntNum;
    int colGrNum;
    boolean enoughCovered;

    int iteration = 0;
    do {/*from   www .j  av  a 2s  .  c o m*/
        System.out.println("Iteration: " + iteration);
        colGrNum = 0;

        uncovInts = new ArrayList<Interaction>();
        uncovIntNum = 0;
        clGrIt.rewind();
        enoughCovered = true;
        while (clGrIt.hasNext()) {
            ColGroup cols = clGrIt.next();
            partialCa.resetCovered();
            List<Interaction> notCovered = partialCa.notCovered(cols);
            if (!notCovered.isEmpty()) {
                uncovIntNum = uncovIntNum + notCovered.size();
                uncovInts.addAll(notCovered);
            }
            if (uncovIntNum > numMinUncovInt) {
                //partialCa.reSample(cols);
                this.reSampleCols(partialCa, uncovInts);
                enoughCovered = false;
                System.out.println("uncovered interaction in coloumn group: " + colGrNum);
                break;
            }
            colGrNum++;
        }
        iteration++;
    } while (!enoughCovered && iteration < maxIteration);

    if (!enoughCovered) {
        System.out.println("output is not a covering array");
        //System.exit(1);
    }

    System.out.println("First phase over.");

    ListCAExt remCA = new ListCAExt(t, k, v);
    this.makeRemCA(remCA, uncovInts);
    ListCA fullCA = new ListCAExt(t, k, v);
    fullCA.join(partialCa);
    fullCA.join(remCA);

    ((ListCAExt) fullCA).copyInfo(remCA);

    /*LLLCA testCA = new LLLCA(fullCA);
    ColGroup cols = new ColGroup(new int[0]);
    System.out.println("This is " + (testCA.isCompleteCA(cols) ? "is a CA" 
    : "is not a CA"));*/

    return fullCA;
}