List of usage examples for java.lang Math ceil
public static double ceil(double a)
From source file:bsc.spark.examples.terasort.ehiggs.TeraScheduler.java
void pickBestSplits(Host host) { int tasksToPick = Math.min(slotsPerHost, (int) Math.ceil((double) remainingSplits / hosts.size())); Split[] best = new Split[tasksToPick]; for (Split cur : host.splits) { LOG.debug(" examine: " + cur.filename + " " + cur.locations.size()); int i = 0; while (i < tasksToPick && best[i] != null && best[i].locations.size() <= cur.locations.size()) { i += 1;//from w w w .j a va 2 s . c o m } if (i < tasksToPick) { for (int j = tasksToPick - 1; j > i; --j) { best[j] = best[j - 1]; } best[i] = cur; } } // for the chosen blocks, remove them from the other locations for (int i = 0; i < tasksToPick; ++i) { if (best[i] != null) { LOG.debug(" best: " + best[i].filename); for (Host other : best[i].locations) { other.splits.remove(best[i]); } best[i].locations.clear(); best[i].locations.add(host); best[i].isAssigned = true; remainingSplits -= 1; } } // for the non-chosen blocks, remove this host for (Split cur : host.splits) { if (!cur.isAssigned) { cur.locations.remove(host); } } }
From source file:Implement.Service.TripperServiceImpl.java
@Override public boolean insertBooking(String code, int packageID, String selectedDate, int numberOfChilds, int numberOfAdult, int accountID) throws ParseException { PackageDTO packgeDTO = getPackageForPayment(packageID); List<Double> prices = getPriceOfSelectedDate(selectedDate, packgeDTO); DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date date = new Date(); String bookingDate = dateFormat.format(date); int noOfPackages = 0; if (!packgeDTO.isIsPrivateTour()) { noOfPackages = numberOfAdult + numberOfChilds; } else {// w w w . ja va 2 s . c om noOfPackages = (int) Math .round(Math.ceil((float) (numberOfAdult + numberOfChilds) / packgeDTO.getMinTripper())); } BookingDTO bookingDTO = new BookingDTO(code, bookingDate, selectedDate, numberOfAdult, numberOfChilds, noOfPackages, prices.get(0), prices.get(1), accountID, packgeDTO.getId(), packgeDTO.getProviderID()); return bookingDAO.insertNewBooking(bookingDTO); }
From source file:com.app.inventario.logica.ProveedorLogicaImpl.java
@Transactional(readOnly = true) public jqGridModel obtenerListaTodos(int numeroPagina, int numeroFilas, String ordenarPor, String ordenarAsc) throws Exception { modelo = new jqGridModel<Proveedor>(); int primerResultado = numeroFilas * (numeroPagina - 1); List<Proveedor> proveedores = null; try {/*from ww w . j a va2s .c om*/ proveedores = proveedorDAO.obtenerTodosAGrid(ordenarPor, ordenarAsc); modelo.setPage(numeroPagina); modelo.setTotal((int) Math.ceil((double) proveedores.size() / (double) numeroFilas)); modelo.setRecords(proveedores.size()); modelo.setRows(proveedores.subList(primerResultado, numeroFilas > proveedores.size() ? proveedores.size() : numeroFilas)); return modelo; } catch (HibernateException he) { Logger.getLogger(ProveedorLogicaImpl.class.getName()).log(Level.SEVERE, null, he); throw he; } }
From source file:com.insthub.O2OMobile.Model.ReceivedOrderListModel.java
public void fetchNextUnfinished() { orderlistreceivedRequest request = new orderlistreceivedRequest(); request.sid = SESSION.getInstance().sid; request.uid = SESSION.getInstance().uid; request.count = NUMPERPAGE;//ww w . j a va 2 s . co m request.by_no = (int) Math.ceil(publicUnfinishedOrderList.size() * 1.0 / NUMPERPAGE) + 1; ; request.ver = O2OMobileAppConst.VERSION_CODE; request.taked_order = ENUM_TAKED_ORDER_STATE.TAKED_ORDER_UNDONE.value(); BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>() { @Override public void callback(String url, JSONObject jo, AjaxStatus status) { try { ReceivedOrderListModel.this.callback(this, url, jo, status); if (null != jo) { orderlistreceivedResponse response = new orderlistreceivedResponse(); response.fromJson(jo); if (response.succeed == 1) { publicUnfinishedOrderList.addAll(response.orders); ReceivedOrderListModel.this.OnMessageResponse(url, jo, status); } else { ReceivedOrderListModel.this.callback(url, response.error_code, response.error_desc); } } else { ReceivedOrderListModel.this.OnMessageResponse(url, jo, status); } } catch (JSONException e) { } } }; Map<String, Object> params = new HashMap<String, Object>(); try { JSONObject requestJson = request.toJson(); requestJson.remove("by_id"); params.put("json", requestJson.toString()); } catch (JSONException e) { } if (isSendingMessage(ApiInterface.ORDERLIST_RECEIVED)) { return; } cb.url(ApiInterface.ORDERLIST_RECEIVED).type(JSONObject.class).params(params); ajax(cb); }
From source file:csiro.pidsvc.mappingstore.ManagerJson.java
@SuppressWarnings("unchecked") public JSONObject getMappings(int page, String mappingPath, String type, String creator, int includeDeprecated) throws SQLException { PreparedStatement pst = null; ResultSet rs = null;//from www. ja v a 2s . c om JSONObject ret = new JSONObject(); final int pageSize = 10; final String sourceView = (includeDeprecated == 2 ? "vw_deprecated_mapping" : (includeDeprecated == 1 ? "vw_latest_mapping" : "vw_active_mapping")); try { String query = "mapping_path IS NOT NULL"; if (mappingPath != null && !mappingPath.isEmpty()) query += " AND (title ILIKE ? OR mapping_path ILIKE ?)"; if (type != null && !type.isEmpty()) query += " AND type = ?"; if (creator != null && !creator.isEmpty()) query += " AND creator = ?"; query = "SELECT COUNT(*) FROM " + sourceView + (query.isEmpty() ? "" : " WHERE " + query) + ";\n" + "SELECT mapping_id, mapping_path, title, description, creator, type, to_char(date_start, 'DD/MM/YYYY HH24:MI') AS date_start, to_char(date_end, 'DD/MM/YYYY HH24:MI') AS date_end FROM " + sourceView + (query.isEmpty() ? "" : " WHERE " + query) + " ORDER BY COALESCE(title, mapping_path) LIMIT " + pageSize + " OFFSET " + ((page - 1) * pageSize) + ";"; pst = _connection.prepareStatement(query); // Bind parameters twice to two almost identical queries. for (int i = 1, j = 0; j < 2; ++j) { if (!mappingPath.isEmpty()) { pst.setString(i++, "%" + mappingPath.replace("\\", "\\\\") + "%"); pst.setString(i++, "%" + mappingPath.replace("\\", "\\\\") + "%"); } if (!type.isEmpty()) pst.setString(i++, type); if (!creator.isEmpty()) pst.setString(i++, creator); } if (pst.execute()) { rs = pst.getResultSet(); rs.next(); ret.put("count", rs.getInt(1)); ret.put("page", page); ret.put("pages", (int) Math.ceil(rs.getFloat(1) / pageSize)); JSONArray jsonArr = new JSONArray(); for (pst.getMoreResults(), rs = pst.getResultSet(); rs.next();) { // String dateStart = sdf.format(sdfdb.parse(rs.getString("date_start"))); // String dateEnd = rs.getString("date_end"); // if (dateEnd != null) // dateEnd = sdf.format(sdfdb.parse(dateEnd)); jsonArr.add(JSONObjectHelper.create("mapping_id", rs.getString("mapping_id"), "mapping_path", rs.getString("mapping_path"), "title", rs.getString("title"), "description", rs.getString("description"), "creator", rs.getString("creator"), "type", rs.getString("type"), "date_start", rs.getString("date_start"), "date_end", rs.getString("date_end"), "date", "")); } ret.put("results", jsonArr); } } finally { if (rs != null) rs.close(); if (pst != null) pst.close(); } return ret; }
From source file:io.github.apfelcreme.Guilds.Command.Guild.Command.LevelCommand.java
/** * executes the command//w w w . j a v a 2 s. com * * @param commandSender the sender * @param strings the command args */ public void execute(CommandSender commandSender, String[] strings) { Player sender = (Player) commandSender; if (sender.hasPermission("Guilds.level")) { if (strings.length > 1) { GuildLevel level = null; if (GuildsUtil.isNumeric(strings[1])) { level = plugin.getGuildsConfig().getLevelData(Integer.parseInt(strings[1])); } else { level = plugin.getGuildsConfig().getLevelData(strings[1]); } if (level != null) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.head") .replace("{0}", level.getName())); if (plugin.getGuildsConfig().requireMoneyForUpgrade()) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig() .getText("info.guild.level.cost").replace("{0}", Double.toString(level.getCost()))); } if (plugin.getGuildsConfig().requireExpForUpgrade()) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.expCost").replace("{0}", Integer.toString(level.getExpCost()))); } if (plugin.getGuildsConfig().requireMaterialForUpgrade()) { for (Map.Entry<Material, Integer> entry : level.getMaterialRequirements().entrySet()) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.materialElement") .replace("{0}", WordUtils.capitalize( entry.getKey().name().toLowerCase().replace("_", " "))) .replace("{1}", entry.getValue().toString())); } } plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.head2")); plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.playerLimit").replace("{0}", Integer.toString(level.getPlayerLimit()))); if (plugin.getGuildsConfig().isEnchantmentBonusActivated()) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.enchantmentCost").replace("{0}", Double.toString(level.getEnchantmentCost() * 100))); } if (plugin.getGuildsConfig().isDoubleCraftingBonusActivated()) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.doubleCraftProbability") .replace("{0}", Double.toString(level.getDoubleCraftProbability() * 100))); } if (plugin.getGuildsConfig().isSpecialDropBonusActivated()) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.specialDropChance") .replace("{0}", Double.toString(level.getSpecialDropChance() * 100))); } if (plugin.getGuildsConfig().isMoreFurnaceExpBonusActivated()) { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("info.guild.level.furnaceExpGainRatio").replace( "{0}", Double.toString(Math.ceil((level.getFurnaceExpGainRatio() - 1) * 100)))); } } else { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("error.unknownLevel")); } } else { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("error.wrongUsage.level")); } } else { plugin.getChat().sendMessage(sender, plugin.getGuildsConfig().getText("error.noPermission")); } }
From source file:net.naijatek.myalumni.util.utilities.FileUtil.java
public static long getDirLength_onDisk(final File dir) throws IOException { if (dir.isFile()) { throw new IOException("BadInputException: not a directory."); }//from w w w . jav a 2 s .com long size = 0; File[] files = dir.listFiles(); if (files != null) { for (File file : files) { long length = 0; if (file.isFile()) { length = file.length(); } else { length = getDirLength_onDisk(file); } double mod = Math.ceil((double) length / 512); if (mod == 0) { mod = 1; } length = (long) mod * 512; size += length; } } //if return size; }
From source file:com.netflix.lipstick.warnings.JobWarnings.java
public List<String> findSkewedReducers(List<ReducerDuration> reducerTimes) { if (!(MIN_REDUCERS_FOR_SKEW < reducerTimes.size())) { return Lists.newLinkedList(); }/* w w w . j a va 2 s.co m*/ int numPotentialOutliers = (int) Math.ceil(reducerTimes.size() / 10.0); int inflection = reducerTimes.size() - numPotentialOutliers; List<ReducerDuration> potentialOutliers = reducerTimes.subList(inflection, reducerTimes.size()); List<ReducerDuration> referenceReducers = reducerTimes.subList(0, inflection); /* List of reducer duration values that we will compare the potential outliers to. */ double[] referenceDurations = new double[referenceReducers.size()]; for (int i = 0; i < referenceReducers.size(); i++) { referenceDurations[i] = referenceReducers.get(i).duration; } double refMean = StatUtils.mean(referenceDurations); double refVariance = StatUtils.populationVariance(referenceDurations, refMean); double refStdDev = Math.sqrt(refVariance); /* If the time to complete the task is more than this far from the mean of all task completion times, we consider it skewed */ double distToMeanThreshold = Math.max((refStdDev * 2), (MIN_STDDEV_DELTA_MINUTES * 60)) + refMean; /* Now collect and return any of the outliers whose distance from the mean is great than the computed threshold. */ List<String> skewedReducerIds = Lists.newArrayList(); for (ReducerDuration r : potentialOutliers) { if ((r.duration - refMean) > distToMeanThreshold) { skewedReducerIds.add(r.reducerTaskId); } } return skewedReducerIds; }
From source file:com.irccloud.android.activity.PastebinEditorActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name), cloud, 0xFFF2F7FC));// w w w .j av a 2s . c o m cloud.recycle(); } setContentView(R.layout.activity_pastebineditor); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { if (!getWindow().isFloating()) { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } paste = (EditText) findViewById(R.id.paste); filename = (EditText) findViewById(R.id.filename); message = (EditText) findViewById(R.id.message); messages_count = (TextView) findViewById(R.id.messages_count); if (savedInstanceState != null && savedInstanceState.containsKey("message")) message.setText(savedInstanceState.getString("message")); if (savedInstanceState != null && savedInstanceState.containsKey("paste_id")) pasteID = savedInstanceState.getString("paste_id"); else if (getIntent() != null && getIntent().hasExtra("paste_id")) pasteID = getIntent().getStringExtra("paste_id"); if (savedInstanceState != null && savedInstanceState.containsKey("paste_contents")) pastecontents = savedInstanceState.getString("paste_contents"); else if (getIntent() != null && getIntent().hasExtra("paste_contents")) pastecontents = getIntent().getStringExtra("paste_contents"); paste.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { int count = 0; String lines[] = editable.toString().split("\n"); for (String line : lines) { count += Math.ceil(line.length() / 1080.0f); } messages_count.setText("Text will be sent as " + count + " message" + (count == 1 ? "" : "s")); } }); paste.setText(pastecontents); if (savedInstanceState != null && savedInstanceState.containsKey("filename")) filename.setText(savedInstanceState.getString("filename")); else if (getIntent() != null && getIntent().hasExtra("filename")) filename.setText(getIntent().getStringExtra("filename")); tabHost = (TabLayout) findViewById(android.R.id.tabhost); ViewCompat.setElevation(toolbar, ViewCompat.getElevation(tabHost)); if (pasteID != null) { tabHost.setVisibility(View.GONE); message.setVisibility(View.GONE); findViewById(R.id.message_heading).setVisibility(View.GONE); } else { tabHost.setTabGravity(TabLayout.GRAVITY_FILL); tabHost.setTabMode(TabLayout.MODE_FIXED); tabHost.addTab(tabHost.newTab().setText("Pastebin")); tabHost.addTab(tabHost.newTab().setText("Messages")); tabHost.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { current_tab = tab.getPosition(); if (current_tab == 0) { filename.setVisibility(View.VISIBLE); message.setVisibility(View.VISIBLE); messages_count.setVisibility(View.GONE); findViewById(R.id.filename_heading).setVisibility(View.VISIBLE); findViewById(R.id.message_heading).setVisibility(View.VISIBLE); } else { filename.setVisibility(View.GONE); message.setVisibility(View.GONE); messages_count.setVisibility(View.VISIBLE); findViewById(R.id.filename_heading).setVisibility(View.GONE); findViewById(R.id.message_heading).setVisibility(View.GONE); } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); if (savedInstanceState != null && savedInstanceState.containsKey("tab")) tabHost.getTabAt(savedInstanceState.getInt("tab")).select(); } NetworkConnection.getInstance().addHandler(this); if (pasteID != null && (pastecontents == null || pastecontents.length() == 0)) { new FetchPastebinTask().execute((Void) null); } if (pasteID != null) { setTitle(R.string.title_activity_pastebin_editor_edit); toolbar.setBackgroundResource(R.drawable.actionbar); } else { setTitle(R.string.title_activity_pastebin_editor); } supportInvalidateOptionsMenu(); result(RESULT_CANCELED); }
From source file:ca.uqac.info.buffertannen.message.BitSequence.java
/** * Outputs the sequence of bits as an array of bytes. * The last byte is padded with zeros if the number of bits * in the array is not a multiple of 8./* ww w . java 2 s. c o m*/ * * @return The array of bytes */ public byte[] toByteArray() { int byte_size = (int) Math.ceil(((float) this.size()) / 8f); byte[] out = new byte[byte_size]; int byte_pos = 0; for (int i = 0; i < this.size(); i += 8) { byte b = 0; for (byte j = 0; j < 8 && i + j < this.size(); j++) { if (this.elementAt(i + j) == true) { b |= 1 << (7 - j); } } out[byte_pos] = b; byte_pos++; } return out; }