List of usage examples for java.lang Math ceil
public static double ceil(double a)
From source file:com.nextbreakpoint.nextfractal.mandelbrot.core.Expression.java
public static double funcCeil(double x) { return Math.ceil(x); }
From source file:me.realized.tm.utilities.profile.UUIDFetcher.java
/** * Makes a request to mojang's servers of a sublist of at most 100 player's * names. Additionally can provide progress outputs * * @param output Whether or not to print output * @param log The {@link Logger} to print to * @param doOutput A {@link Predicate} representing when to output a number * @return A {@link Map} of player names to their {@link UUID}s * @throws IOException If there's a problem sending or receiving the request * @throws ParseException If the request response cannot be read * @throws InterruptedException If the thread is interrupted while sleeping * @version 0.1.0//from www .ja v a 2 s . co m * @since 0.0.1 */ public Map<String, UUID> callWithProgressOutput(boolean output, Logger log, Predicate<? super Integer> doOutput) throws IOException, ParseException, InterruptedException { Map<String, UUID> uuidMap = new HashMap<>(); int totalNames = this.names.size(); int completed = 0; int failed = 0; int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST); for (int i = 0; i < requests; i++) { List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size())); String body = JSONArray.toJSONString(request); HttpURLConnection connection = UUIDFetcher.createConnection(); UUIDFetcher.writeBody(connection, body); if (connection.getResponseCode() == 429 && this.rateLimiting) { String out = "[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion..."; if (log != null) { log.warning(out); } else { Bukkit.getLogger().warning(out); } Thread.sleep(TimeUnit.MINUTES.toMillis(10)); connection = UUIDFetcher.createConnection(); UUIDFetcher.writeBody(connection, body); } JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); completed += array.size(); failed += request.size() - array.size(); for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id")); uuidMap.put((String) jsonProfile.get("name"), uuid); } if (output) { int processed = completed + failed; if (doOutput.apply(processed) || processed == totalNames) { if (log != null) { log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed, totalNames, ((double) processed / totalNames) * 100D, failed)); } } } } return uuidMap; }
From source file:ch.jamiete.hilda.music.commands.MusicQueueCommand.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) { this.reply(message, "There isn't anything playing."); return;//w ww. ja va 2s . c o m } int page = 0; final int pageSize = 15; int queue_code = 0; if (args.length == 1) { if (StringUtils.isNumeric(args[0])) { page = Integer.valueOf(args[0]) - 1; queue_code = page * pageSize; } else { this.usage(message, "[page]", label); return; } } final List<QueueItem> queue = server.getQueue(); if (queue.isEmpty()) { this.reply(message, "There isn't anything queued."); return; } final List<QueueItem> tracks = MusicQueueCommand.getPage(queue, page, pageSize); final MessageBuilder sb = new MessageBuilder(); if (tracks.isEmpty()) { this.reply(message, "That page is empty."); } else { sb.append("There ").append((queue.size() == 1) ? "is" : "are").append(" "); sb.append(queue.size()).append(" ").append((queue.size() == 1) ? "track" : "tracks"); sb.append(" queued for ").append(Util.getFriendlyTime(server.getDuration())); if (tracks.size() != queue.size()) { sb.append("; showing tracks "); if (page == 0) { sb.append("1").append(pageSize); } else { final int first = (page * pageSize) + 1; sb.append(first).append("").append(Math.min((first + pageSize) - 1, queue.size())); } } sb.append(":").append("\n\n"); for (final QueueItem track : tracks) { sb.append("[" + ++queue_code + ']', Formatting.BLOCK).append(" "); sb.append(Util.sanitise(MusicManager.getFriendly(track.getTrack()))); final String time = MusicManager.getFriendlyTime(track.getTrack()); if (!time.trim().isEmpty()) { sb.append(" (").append(time).append(")"); } Member requestor = message.getGuild().getMemberById(track.getUserId()); sb.append(" ").append(requestor == null ? "User left server" : requestor.getEffectiveName(), Formatting.BLOCK); sb.append("\n"); } if (tracks.size() != queue.size()) { sb.append("\n"); sb.append("End of page ").append(page + 1).append("/") .append((int) Math.ceil((double) queue.size() / (double) pageSize)).append("."); } sb.buildAll(SplitPolicy.NEWLINE).forEach(m -> this.reply(message, m)); } }
From source file:com.hortonworks.pso.data.generator.mapreduce.DataGenInputFormat.java
/** * Create the desired number of splits, dividing the number of rows * between the mappers./*w w w. j ava 2 s . c om*/ */ public List<InputSplit> getSplits(JobContext job) { long totalRows = getNumberOfRows(job); int numSplits = job.getConfiguration().getInt(MRJobConfig.NUM_MAPS, 1); LOG.info("Generating " + totalRows + " using " + numSplits); List<InputSplit> splits = new ArrayList<InputSplit>(); long currentRow = 0; for (int split = 0; split < numSplits; ++split) { long goal = (long) Math.ceil(totalRows * (double) (split + 1) / numSplits); splits.add(new DataGenInputSplit(currentRow, goal - currentRow)); currentRow = goal; } return splits; }
From source file:com.intellectualcrafters.plot.commands.Condense.java
@Override public boolean execute(final PlotPlayer plr, final String... args) { if (plr != null) { MainUtil.sendMessage(plr, (C.NOT_CONSOLE)); return false; }//from w w w . j a v a2 s. c o m if ((args.length != 2) && (args.length != 3)) { MainUtil.sendMessage(plr, "/plot condense <world> <start|stop|info> [radius]"); return false; } final String worldname = args[0]; if (!BlockManager.manager.isWorld(worldname) || !PS.get().isPlotWorld(worldname)) { MainUtil.sendMessage(plr, "INVALID WORLD"); return false; } switch (args[1].toLowerCase()) { case "start": { if (args.length == 2) { MainUtil.sendMessage(plr, "/plot condense " + worldname + " start <radius>"); return false; } if (TASK) { MainUtil.sendMessage(plr, "TASK ALREADY STARTED"); return false; } if (args.length == 2) { MainUtil.sendMessage(plr, "/plot condense " + worldname + " start <radius>"); return false; } if (!StringUtils.isNumeric(args[2])) { MainUtil.sendMessage(plr, "INVALID RADIUS"); return false; } final int radius = Integer.parseInt(args[2]); final Collection<Plot> plots = PS.get().getPlots(worldname).values(); final int size = plots.size(); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); if (radius < minimum_radius) { MainUtil.sendMessage(plr, "RADIUS TOO SMALL"); return false; } final List<PlotId> to_move = new ArrayList<>(getPlots(plots, radius)); final List<PlotId> free = new ArrayList<>(); PlotId start = new PlotId(0, 0); while ((start.x <= minimum_radius) && (start.y <= minimum_radius)) { final Plot plot = MainUtil.getPlot(worldname, start); if (!plot.hasOwner()) { free.add(plot.id); } start = Auto.getNextPlot(start, 1); } if (free.size() == 0 || to_move.size() == 0) { MainUtil.sendMessage(plr, "NO PLOTS FOUND"); return false; } MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), new Runnable() { @Override public void run() { if (!TASK) { sendMessage("CONDENSE TASK CANCELLED"); return; } to_move.remove(0); free.remove(0); int index = 0; for (final PlotId id : to_move) { final Plot plot = MainUtil.getPlot(worldname, id); if (plot.hasOwner()) { break; } index++; } for (int i = 0; i < index; i++) { to_move.remove(0); } index = 0; for (final PlotId id : free) { final Plot plot = MainUtil.getPlot(worldname, id); if (!plot.hasOwner()) { break; } index++; } for (int i = 0; i < index; i++) { free.remove(0); } if (to_move.size() == 0) { sendMessage( "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK."); TASK = false; return; } if (free.size() == 0) { sendMessage("TASK FAILED. NO FREE PLOTS FOUND!"); TASK = false; return; } sendMessage("MOVING " + to_move.get(0) + " to " + free.get(0)); MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), this); } }); TASK = true; MainUtil.sendMessage(plr, "TASK STARTED..."); return true; } case "stop": { if (!TASK) { MainUtil.sendMessage(plr, "TASK ALREADY STOPPED"); return false; } TASK = false; MainUtil.sendMessage(plr, "TASK STOPPED"); return true; } case "info": { if (args.length == 2) { MainUtil.sendMessage(plr, "/plot condense " + worldname + " info <radius>"); return false; } if (!StringUtils.isNumeric(args[2])) { MainUtil.sendMessage(plr, "INVALID RADIUS"); return false; } final int radius = Integer.parseInt(args[2]); final Collection<Plot> plots = PS.get().getPlots(worldname).values(); final int size = plots.size(); final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1); if (radius < minimum_radius) { MainUtil.sendMessage(plr, "RADIUS TOO SMALL"); return false; } final int max_move = getPlots(plots, minimum_radius).size(); final int user_move = getPlots(plots, radius).size(); MainUtil.sendMessage(plr, "=== DEFAULT EVAL ==="); MainUtil.sendMessage(plr, "MINIMUM RADIUS: " + minimum_radius); MainUtil.sendMessage(plr, "MAXIMUM MOVES: " + max_move); MainUtil.sendMessage(plr, "=== INPUT EVAL ==="); MainUtil.sendMessage(plr, "INPUT RADIUS: " + radius); MainUtil.sendMessage(plr, "ESTIMATED MOVES: " + user_move); MainUtil.sendMessage(plr, "ESTIMATED TIME: " + "No idea, times will drastically change based on the system performance and load"); MainUtil.sendMessage(plr, "&e - Radius is measured in plot width"); return true; } } MainUtil.sendMessage(plr, "/plot condense " + worldname + " <start|stop|info> [radius]"); return false; }
From source file:dr.app.bss.Utils.java
public static int rMultinom(double[] probabilities) { int range = probabilities.length + 1; double[] distribution = new double[range]; double sumProb = 0; for (double value : probabilities) { sumProb += value;/*from w w w. ja va 2 s.co m*/ } // END: probabilities loop distribution[0] = 0; for (int i = 1; i < range; ++i) { distribution[i] = distribution[i - 1] + (probabilities[i - 1] / sumProb); } // END: i loop distribution[range - 1] = 1.0; double key = random.nextDouble(); int mindex = 1; int maxdex = range - 1; int midpoint = mindex + (maxdex - mindex) / 2; while (mindex <= maxdex) { if (key < distribution[midpoint - 1]) { maxdex = midpoint - 1; } else if (key > distribution[midpoint]) { mindex = midpoint + 1; } else { return midpoint - 1; } midpoint = mindex + (int) Math.ceil((maxdex - mindex) / 2); } //END: mindex loop System.out.println("Error in rMultinom!"); return range - 1; }
From source file:de.biomedical_imaging.ij.nanotrackj.WalkerMethodEstimator.java
/** * /* w ww.j av a 2s.com*/ * @param data Containes the mean squared displacement and the Tracklength for each track. data[i][0] = MSD data[i][1] = Tracklength * @param temp Temperature of the suspension in kelvin * @param visk Viscosity of the suspension * @param framerate * @param maxdiameter The maximum diameter for the estimation. 0 = Maximum Diameter is estimated automatically */ public WalkerMethodEstimator(double[][] data, double temp, double visk, double framerate, int maxdiameter) { this.temp = temp; this.visk = visk; this.framerate = 1.0 / framerate; this.data = data; kMin = Integer.MAX_VALUE; kMax = Integer.MIN_VALUE; msdMin = Double.MAX_VALUE; msdMax = Double.MIN_VALUE; double convFact = Math.pow(10, -10); for (int i = 0; i < data.length; i++) { //10^-10 cm^2 -> cm^2 this.data[i][0] = this.data[i][0] * convFact; //- 4*17.562862475*17.562862475*Math.pow(10, -7)*Math.pow(10, -7); if (this.data[i][0] > msdMax) { msdMax = this.data[i][0]; } if (this.data[i][0] < msdMin) { msdMin = this.data[i][0]; } if (this.data[i][1] > kMax) { kMax = (int) this.data[i][1]; } if (this.data[i][1] < kMin) { kMin = (int) this.data[i][1]; } //IJ.log("MSD " + this.data[i][0]); } logMapK = new double[kMax + 1]; logMapGammaK = new double[kMax + 1]; java.util.Arrays.fill(logMapK, Double.NaN); java.util.Arrays.fill(logMapGammaK, Double.NaN); maxRadiusInNm = maxdiameter / 2.0; if (maxdiameter == 0) { maxRadiusInNm = NanoTrackJ_.getInstance() .diffCoeffToDiameter((msdMin * Math.pow(10, 10)) / 4 * (framerate)); maxRadiusInNm = (maxRadiusInNm + 1) / 2; } binNumber = (int) (maxRadiusInNm / binSizeInnm); histBinNumber = (int) Math.ceil(Math.sqrt(data.length)); deltaB = msdMax / histBinNumber; histogramMSD = new double[histBinNumber]; java.util.Arrays.fill(histogramMSD, 0); Nk = new int[kMax + 1]; java.util.Arrays.fill(Nk, 0); for (int i = 0; i < data.length; i++) { int index = (int) this.data[i][1]; Nk[index]++; int index2 = (int) Math.floor(data[i][0] / deltaB - 0.001); histogramMSD[index2]++; } }
From source file:fingerprints.helper.BloomFilter.java
/** * You must specify the number of bits in the Bloom Filter, and also you should specify the number of items you * expect to add.//from w w w.j a va 2s. c o m * * The latter is used to choose some optimal internal values to minimize the false-positive rate (which can be * estimated with expectedFalsePositiveRate()). * * @param bisetSize The number of bits in the bit array (often called 'm' in the context of bloom filters). * @param expectedPatterns The typical number of items you expect to be added to the SimpleBloomFilter (often called * 'n'). */ public BloomFilter(int bisetSize, int expectedPatterns) { this.bitSetSize = bisetSize; this.expectedPatterns = expectedPatterns; // k = ceil(-log_2(false prob.)) double falsePositiveProbability = (bisetSize / expectedPatterns); this.k = (int) Math.ceil((falsePositiveProbability) * Math.log(2.0)); bitSet = new BitSet(bisetSize); }
From source file:com.framework.demo.web.controller.calendar.CalendarController.java
@RequestMapping(value = "/new", method = RequestMethod.GET) public String showNewForm( @RequestParam(value = "start", required = false) @DateTimeFormat(pattern = dataFormat) Date start, @RequestParam(value = "end", required = false) @DateTimeFormat(pattern = dataFormat) Date end, Model model) {// w w w.ja v a 2 s . c om setColorList(model); PersonalCalendar calendar = new PersonalCalendar(); calendar.setLength(1); if (start != null) { calendar.setStartDate(start); calendar.setLength((int) Math.ceil(1.0 * (end.getTime() - start.getTime()) / oneDayMillis)); if (DateUtils.isSameDay(start, end)) { calendar.setLength(1); } if (!"00:00:00".equals(DateFormatUtils.format(start, "HH:mm:ss"))) { calendar.setStartTime(start); } if (!"00:00:00".equals(DateFormatUtils.format(end, "HH:mm:ss"))) { calendar.setEndTime(end); } } model.addAttribute("model", calendar); return viewName("newForm"); }
From source file:com.esd.ps.ManagerController.java
/** * user list/*from w ww. j a v a2 s. co m*/ * * @param userNameCondition * @param userType * @param page * @param year * @param month * @param taskUpload * @return */ @RequestMapping(value = "/manager", method = RequestMethod.POST) @ResponseBody public Map<String, Object> managerPost(String userNameCondition, int userType, int page, String beginDate, String endDate, int taskUpload, int dateType) { logger.debug("userType:{},page:{},userNameCondition:{},year:{},month:{}", userType, page, userNameCondition, beginDate, endDate); Map<String, Object> map = new HashMap<String, Object>(); // SimpleDateFormat sdf = new // SimpleDateFormat(Constants.DATETIME_FORMAT); int totlePage = Constants.ZERO; List<Map<String, Object>> list = workerService.getLikeRealName(userNameCondition, page, Constants.ROW); map.clear(); int totle = workerService.getCountLikeRealname(userNameCondition); totlePage = (int) Math.ceil((double) totle / (double) Constants.ROW); map.put(Constants.LIST, list); map.put(Constants.TOTLE, totle); map.put(Constants.TOTLE_PAGE, totlePage); return map; }