List of usage examples for java.lang Math floor
public static double floor(double a)
From source file:com.garyclayburg.UserRestSmokeTest.java
@Ignore @Test/*from w ww . j a v a 2 s . co m*/ public void testPlain() throws Exception { RestTemplate rest = new RestTemplate(); SimpleUser user1 = new SimpleUser(); user1.setFirstname("Tommy"); user1.setLastname("Deleteme"); user1.setId("112" + (int) (Math.floor(Math.random() * 10000))); ResponseEntity<SimpleUser> userResponseEntity = rest .postForEntity("http://" + endpoint + "/audited-users/auditedsave", user1, SimpleUser.class); log.info("got a response"); MatcherAssertionErrors.assertThat(userResponseEntity.getStatusCode(), Matchers.equalTo(HttpStatus.OK)); }
From source file:au.org.ala.delta.intkey.directives.invocation.DifferencesDirectiveInvocation.java
@Override public File doRunInBackground(IntkeyContext context) throws IntkeyDirectiveInvocationException { int numberOfTaxa = _taxa.size(); if (_includeSpecimen) { numberOfTaxa++;//ww w. j a v a 2s . c o m } if (numberOfTaxa < 2) { throw new IntkeyDirectiveInvocationException("TwoTaxaRequiredForComparison.error"); } if (_useGlobalMatchValues) { _matchType = context.getMatchType(); _matchUnknowns = context.getMatchUnknowns(); _matchInapplicables = context.getMatchInapplicables(); } _characterFormatter = new CharacterFormatter(context.displayNumbering(), CommentStrippingMode.RETAIN_SURROUNDING_STRIP_INNER, AngleBracketHandlingMode.REMOVE, false, true); _taxonFormatter = new ItemFormatter(context.displayNumbering(), CommentStrippingMode.STRIP_ALL, AngleBracketHandlingMode.RETAIN, false, false, false); _attributeFormatter = new AttributeFormatter(context.displayNumbering(), false, CommentStrippingMode.RETAIN_SURROUNDING_STRIP_INNER, AngleBracketHandlingMode.RETAIN, false, context.getDataset().getOrWord()); Specimen specimen = null; if (_includeSpecimen) { specimen = context.getSpecimen(); } progress(UIUtils.getResourceString("DifferencesDirective.Progress.Calculating")); List<au.org.ala.delta.model.Character> differences = DiffUtils.determineDifferingCharactersForTaxa( context.getDataset(), _characters, _taxa, specimen, _matchUnknowns, _matchInapplicables, _matchType, _omitTextCharacters); // Differences output can be very large so write it to a temporary file. try { File tempFile = File.createTempFile("IntkeyDifferences", null); tempFile.deleteOnExit(); FileWriter fw = new FileWriter(tempFile); RTFWriter rtfWriter = new RTFWriter(fw); rtfWriter.startDocument(); for (int i = 0; i < differences.size(); i++) { au.org.ala.delta.model.Character ch = differences.get(i); List<Attribute> attrs = context.getDataset().getAllAttributesForCharacter(ch.getCharacterId()); // Display difference in bold if differing values do not overlap boolean differencesOverlap = DiffUtils.compareForTaxa(context.getDataset(), ch, _taxa, specimen, true, true, MatchType.OVERLAP); String charDescription = _characterFormatter.formatCharacterDescription(ch); if (!differencesOverlap) { charDescription = RTFUtils.formatTextBold(charDescription); } rtfWriter.writeText(charDescription); rtfWriter.increaseIndent(); if (_includeSpecimen) { rtfWriter.writeText(UIUtils.getResourceString("DifferencesDirective.Specimen")); Attribute attr = specimen.getAttributeForCharacter(ch); rtfWriter.increaseIndent(); String formattedAttributeDescription = _attributeFormatter.formatAttribute(attr); if (!differencesOverlap) { formattedAttributeDescription = RTFUtils.formatTextBold(formattedAttributeDescription); } rtfWriter.writeText(formattedAttributeDescription); rtfWriter.decreaseIndent(); } for (Item taxon : _taxa) { Attribute taxonAttr = attrs.get(taxon.getItemNumber() - 1); String taxonDescription = _taxonFormatter.formatItemDescription(taxon); rtfWriter.writeText(taxonDescription); rtfWriter.increaseIndent(); String formattedAttributeDescription = _attributeFormatter.formatAttribute(taxonAttr); if (!differencesOverlap) { formattedAttributeDescription = RTFUtils.formatTextBold(formattedAttributeDescription); } rtfWriter.writeText(formattedAttributeDescription); rtfWriter.decreaseIndent(); } rtfWriter.decreaseIndent(); rtfWriter.writeText(""); int progressPercent = (int) Math.floor((((double) i + 1) / differences.size()) * 100); progress(UIUtils.getResourceString("DifferencesDirective.Progress.Generating", progressPercent)); } rtfWriter.setTextColor(Color.RED); rtfWriter.setFont(1); if (differences.size() == 0) { rtfWriter.writeText(UIUtils.getResourceString("DifferencesDirective.NoDifferences")); } else if (differences.size() == 1) { rtfWriter.writeText(UIUtils.getResourceString("DifferencesDirective.OneDifference")); } else { rtfWriter.writeText( UIUtils.getResourceString("DifferencesDirective.ManyDifferences", differences.size())); } rtfWriter.endDocument(); return tempFile; } catch (IOException ex) { throw new IntkeyDirectiveInvocationException(ex, "DifferencesDirectives.ReportGeneration.error", ex.getMessage()); } }
From source file:eu.supersede.gr.utility.PointsLogic.java
private void computePoints() { List<HAHPGamePlayerPoint> gamesPlayersPoints = gamesPlayersPointsRepository.findAll(); // cycle on every gamesPlayersPoints for (int i = 0; i < gamesPlayersPoints.size(); i++) { HAHPGame g = gamesRepository.findOne(gamesPlayersPoints.get(i).getGame().getGameId()); // set currentPlayer that is used for other methods g.setCurrentPlayer(gamesPlayersPoints.get(i).getUser()); List<HAHPCriteriasMatrixData> criteriasMatrixDataList = criteriaMatricesRepository.findByGame(g); // calculate the agreementIndex for every gamesPlayersPoints of a game and a specific user Map<String, Double> resultTotal = AHPRest.CalculateAHP(g.getCriterias(), g.getRequirements(), criteriasMatrixDataList, g.getRequirementsMatrixData()); Map<String, Double> resultPersonal = AHPRest.CalculatePersonalAHP( gamesPlayersPoints.get(i).getUser().getUserId(), g.getCriterias(), g.getRequirements(), criteriasMatrixDataList, g.getRequirementsMatrixData()); List<Requirement> gameRequirements = g.getRequirements(); Double sum = 0.0;//from w w w . ja va2 s . c om for (int j = 0; j < resultTotal.size(); j++) { Double requirementValueTotal = resultTotal .get(gameRequirements.get(j).getRequirementId().toString()); Double requirementValuePersonal = resultPersonal .get(gameRequirements.get(j).getRequirementId().toString()); sum = sum + (Math.abs(requirementValueTotal - requirementValuePersonal) * (1.0 - requirementValueTotal)); } Double agreementIndex = M - (M * sum); gamesPlayersPoints.get(i).setAgreementIndex(agreementIndex.longValue()); // calculate the positionInVoting for every gamesPlayersPoints of a game and a specific user List<User> players = g.getPlayers(); List<HAHPRequirementsMatrixData> lrmd = requirementsMatricesRepository.findByGame(g); Map<User, Float> gamePlayerVotes = new HashMap<>(); for (User player : players) { Integer total = 0; Integer voted = 0; if (lrmd != null) { for (HAHPRequirementsMatrixData data : lrmd) { for (HAHPPlayerMove pm : data.getPlayerMoves()) { if (pm.getPlayer().getUserId().equals(player.getUserId())) { total++; if (pm.getPlayed() == true && pm.getValue() != null && !pm.getValue().equals(-1l)) { voted++; } } } } } gamePlayerVotes.put(player, total.equals(0) ? 0f : ((new Float(voted) / new Float(total)) * 100)); } LinkedHashMap<User, Float> orderedList = sortHashMapByValues(gamePlayerVotes); List<User> indexes = new ArrayList<>(orderedList.keySet()); Integer index = indexes.indexOf(gamesPlayersPoints.get(i).getUser()); Double positionInVoting = (orderedList.size() - (new Double(index) + 1.0)) + 1.0; gamesPlayersPoints.get(i).setPositionInVoting(positionInVoting.longValue()); // calculate the virtualPosition of a user base on his/her points in a particular game HAHPGamePlayerPoint gpp = gamesPlayersPointsRepository .findByUserAndGame(gamesPlayersPoints.get(i).getUser(), g); List<HAHPGamePlayerPoint> specificGamePlayersPoints = gamesPlayersPointsRepository.findByGame(g); Collections.sort(specificGamePlayersPoints, new CustomComparator()); Long virtualPosition = specificGamePlayersPoints.indexOf(gpp) + 1l; gamesPlayersPoints.get(i).setVirtualPosition(virtualPosition); Long movesPoints = 0l; Long gameProgressPoints = 0l; Long positionInVotingPoints = 0l; Long gameStatusPoints = 0l; Long agreementIndexPoints = 0l; Long totalPoints = 0l; // set the movesPoints movesPoints = g.getMovesDone().longValue(); // setGameProgressPoints gameProgressPoints = (long) Math.floor(g.getPlayerProgress() / 10); // setPositionInVotingPoints if (positionInVoting == 1) { positionInVotingPoints = 5l; } else if (positionInVoting == 2) { positionInVotingPoints = 3l; } else if (positionInVoting == 3) { positionInVotingPoints = 2l; } // setGameStatusPoints if (g.getPlayerProgress() != 100) { gameStatusPoints = -20l; } else { gameStatusPoints = 0l; } // set AgreementIndexPoints agreementIndexPoints = agreementIndex.longValue(); totalPoints = movesPoints.longValue() + gameProgressPoints + positionInVotingPoints + gameStatusPoints + agreementIndexPoints; // set totalPoints 0 if the totalPoints are negative if (totalPoints < 0) { totalPoints = 0l; } gamesPlayersPoints.get(i).setPoints(totalPoints); gamesPlayersPointsRepository.save(gamesPlayersPoints.get(i)); } System.out.println("Finished computing votes"); }
From source file:edu.oregonstate.eecs.mcplan.domains.racegrid.RacegridDynamics.java
/** * Computes all grid cells that a line intersects. * //from w ww . j a v a2 s. co m * Based on an implementation of the DDA algorithm from: * http://tomasjanecek.cz/en/clanky/post/trivial-dda-and-bresenham-algorithm-for-a-line-in-java * * Note that the above implementation doesn't handle rounding errors well * and doesn't return the grid cells in traversal order. * * @param ix1 * @param iy1 * @param ix2 * @param iy2 * @return */ private static Iterable<Point> lineCover(final int ix1, final int iy1, final int ix2, final int iy2) { final ArrayList<Point> points = new ArrayList<Point>(); if (ix1 == ix2 && iy1 == iy2) { points.add(new Point(ix2, iy2)); return points; } // The grid coordinates actually represent the middle of a grid cell final int x1 = 2 * ix1 + 1; final int y1 = 2 * iy1 + 1; final int x2 = 2 * ix2 + 1; final int y2 = 2 * iy2 + 1; final double dx = x2 - x1; final double dy = y2 - y1; points.add(new Point(ix1, iy1)); if (Math.abs(y2 - y1) <= Math.abs(x2 - x1)) { // |m| <= 1 // Because of the slope constraint, the y coordinate cannot change // in only half of a grid cell in the x direction. The idea of // the algorithm is: // 1. Do the second half of the origin cell. // 2. Do the entire width of middle cells. See if y changes. If it // does, add both top and bottom cells in that x coordinate // 3. Do the first half of the destionation cell // FIXME: You need to reverse the sign of 'm' also. See the // implementation from the ROB599 HW1. // Reverse x traversal if x is decreasing final int stride = (x2 < x1 ? -1 : 1); final double m = dy / dx; double y = y1; // We've already added the origin point int x = x1; x += stride; y += m; while (x + stride != x2) { final int old_floor_y = (int) Math.floor(y / 2.0); y += 2 * m; final int new_floor_y = (int) Math.floor(y / 2.0); x += stride; points.add(new Point((x - 1) / 2, old_floor_y)); if (old_floor_y != new_floor_y) { // We increased the y coordinate in this x coordinate points.add(new Point((x - 1) / 2, new_floor_y)); } x += stride; } // Last point will be added below } else { // |m| > 1 final int stride = (y2 < y1 ? -1 : 1); final double m = dx / dy; double x = x1; // We've already added the origin point int y = y1; y += stride; x += m; while (y + stride != y2) { final int old_floor_x = (int) Math.floor(x / 2.0); x += 2 * m; final int new_floor_x = (int) Math.floor(x / 2.0); y += stride; points.add(new Point(old_floor_x, (y - 1) / 2)); if (old_floor_x != new_floor_x) { // We increased the x coordinate in this y coordinate points.add(new Point(new_floor_x, (y - 1) / 2)); } y += stride; } // Last point will be added below } points.add(new Point(ix2, iy2)); return points; }
From source file:com.diozero.devices.ADXL345.java
private void setOffset(int register, float offset) { if (offset < 0 || offset > OFFSET_RANGE) { throw new IllegalArgumentException("Illegal offset value (" + offset + "), must be 0.." + OFFSET_RANGE); }/* w w w .j a v a 2 s. c om*/ device.writeByte(register, (byte) (Math.floor(offset / OFFSET_LSB))); }
From source file:net.sf.jasperreports.functions.standard.MathFunctions.java
/** * 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. *//*from w w w. j a v a 2s.c om*/ @Function("FLOOR") @FunctionParameters({ @FunctionParameter("number") }) public static Double FLOOR(Number number) { if (number == null) { logNullArgument(); return null; } return Math.floor(number.doubleValue()); }
From source file:org.kuali.mobility.push.service.CXFSenderService.java
/** * Creates and returns an alphanumeric key of length specified. Checks key for uniqueness before returning. * @return String/* w w w .ja v a 2 s . c o m*/ */ @GET @Path("/key") public String getKey() { int keyLength = Integer.valueOf(getKmeProperties().getProperty("push.sender.default.key.length", "20")); String possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; String text = ""; do { text = ""; for (int i = 0; i < keyLength; i++) { int j = (int) Math.floor(Math.random() * possible.length()); text += possible.charAt(j); } } while (this.getSenderService().isValidSenderKey(text)); return text; }
From source file:de.tudarmstadt.lt.ltbot.postprocessor.DecesiveValuePrioritizer.java
int getPrecedenceCost(double val) { // cost needs to be in [1,255], lower values are better, try to squash values into this range if (val == Double.NaN) return 255; // highest possible value // [A, B] --> [a, b] // newval = (val - A)*(b-a)/(B-A) + a // A,a = 0 // newval = val * (b/B) double B = Math.min(Integer.MAX_VALUE, Double.valueOf(getMaxvalue())); // use maxvalue as maximum if specified and below Integer.maxvalue double b = 253; // reserve 255 for everything that is greater than B if (val >= B) return 255; int precedence_cost = (int) Math.floor(val * (b / B)) + 1; return precedence_cost; }
From source file:main.java.utils.Utility.java
public static int rightPadding(int id, int value) { return ((int) Math.pow(10, Math.floor(Math.log10(value)) + 1) * id + value); }
From source file:org.openmeetings.app.data.flvrecord.converter.FlvRecorderConverter.java
public void stripAudioFromFLVs(FlvRecording flvRecording) { List<HashMap<String, String>> returnLog = new LinkedList<HashMap<String, String>>(); List<String> listOfFullWaveFiles = new LinkedList<String>(); String streamFolderName = getStreamFolderName(flvRecording); try {/*from w w w .j a v a 2 s.c om*/ stripAudioFirstPass(flvRecording, returnLog, listOfFullWaveFiles, streamFolderName); // Merge Wave to Full Length String streamFolderGeneralName = getStreamFolderName(); FlvRecordingMetaData flvRecordingMetaDataOfScreen = this.flvRecordingMetaDataDaoImpl .getFlvRecordingMetaDataScreenFlvByRecording(flvRecording.getFlvRecordingId()); if (flvRecordingMetaDataOfScreen == null) { throw new Exception( "flvRecordingMetaDataOfScreen is Null FlvRecordingId " + flvRecording.getFlvRecordingId()); } if (flvRecordingMetaDataOfScreen.getStreamReaderThreadComplete() == null) { throw new Exception("StreamReaderThreadComplete Bit is NULL, error in recording"); } if (!flvRecordingMetaDataOfScreen.getStreamReaderThreadComplete()) { log.debug("### meta ScreenStream not yet written to disk" + flvRecordingMetaDataOfScreen.getFlvRecordingMetaDataId()); boolean doStop = true; while (doStop) { log.debug("### Stream not yet written Thread Sleep - " + flvRecordingMetaDataOfScreen.getFlvRecordingMetaDataId()); Thread.sleep(100L); flvRecordingMetaDataOfScreen = flvRecordingMetaDataDaoImpl .getFlvRecordingMetaDataById(flvRecordingMetaDataOfScreen.getFlvRecordingMetaDataId()); if (flvRecordingMetaDataOfScreen.getStreamReaderThreadComplete()) { log.debug("### Screen Stream now written Thread continue - "); doStop = false; } } } String hashFileFullName = flvRecordingMetaDataOfScreen.getStreamName() + "_FINAL_WAVE.wav"; String outputFullWav = streamFolderName + hashFileFullName; if (listOfFullWaveFiles.size() == 1) { outputFullWav = listOfFullWaveFiles.get(0); flvRecordingMetaDataOfScreen.setFullWavAudioData(hashFileFullName); } else if (listOfFullWaveFiles.size() > 0) { String[] argv_full_sox = mergeAudioToWaves(listOfFullWaveFiles, outputFullWav); log.debug("START mergeAudioToWaves ################# "); log.debug(argv_full_sox.toString()); String iString = ""; for (int i = 0; i < argv_full_sox.length; i++) { iString += argv_full_sox[i] + " "; } log.debug(iString); log.debug("END mergeAudioToWaves ################# "); flvRecordingMetaDataOfScreen.setFullWavAudioData(hashFileFullName); this.flvRecordingMetaDataDaoImpl.updateFlvRecordingMetaData(flvRecordingMetaDataOfScreen); returnLog.add(ProcessHelper.executeScript("mergeWave", argv_full_sox)); } else { // create default Audio to merge it. // strip to content length String outputWav = streamFolderGeneralName + "one_second.wav"; // Calculate delta at beginning Long deltaTimeMilliSeconds = flvRecording.getRecordEnd().getTime() - flvRecording.getRecordStart().getTime(); Float deltaPadding = (Float.parseFloat(deltaTimeMilliSeconds.toString()) / 1000) - 1; String[] argv_full_sox = new String[] { this.getPathToSoX(), outputWav, outputFullWav, "pad", "0", deltaPadding.toString() }; log.debug("START generateSampleAudio ################# "); String tString = ""; for (int i = 0; i < argv_full_sox.length; i++) { tString += argv_full_sox[i] + " "; } log.debug(tString); log.debug("END generateSampleAudio ################# "); flvRecordingMetaDataOfScreen.setFullWavAudioData(hashFileFullName); this.flvRecordingMetaDataDaoImpl.updateFlvRecordingMetaData(flvRecordingMetaDataOfScreen); returnLog.add(ProcessHelper.executeScript("mergeWave", argv_full_sox)); } // Merge Audio with Video / Calculate resulting FLV String inputScreenFullFlv = streamFolderName + flvRecordingMetaDataOfScreen.getStreamName() + ".flv"; String hashFileFullNameFlv = "flvRecording_" + flvRecording.getFlvRecordingId() + ".flv"; String outputFullFlv = streamFolderGeneralName + hashFileFullNameFlv; // ffmpeg -vcodec flv -qscale 9.5 -r 25 -ar 22050 -ab 32k -s 320x240 // -i // 65318fb5c54b1bc1b1bca077b493a914_28_12_2009_23_38_17_FINAL_WAVE.wav // -i 65318fb5c54b1bc1b1bca077b493a914_28_12_2009_23_38_17.flv // final1.flv int flvWidth = flvRecording.getWidth(); int flvHeight = flvRecording.getHeight(); log.debug("flvWidth -1- " + flvWidth); log.debug("flvHeight -1- " + flvHeight); flvWidth = Double.valueOf((Math.floor(flvWidth / 16)) * 16).intValue(); flvHeight = Double.valueOf((Math.floor(flvHeight / 16)) * 16).intValue(); log.debug("flvWidth -2- " + flvWidth); log.debug("flvHeight -2- " + flvHeight); flvRecording.setFlvWidth(flvWidth); flvRecording.setFlvHeight(flvHeight); String[] argv_fullFLV = new String[] { this.getPathToFFMPEG(), // "-i", inputScreenFullFlv, "-i", outputFullWav, "-ar", "22050", // "-acodec", "libmp3lame", // "-ab", "32k", // "-s", flvWidth + "x" + flvHeight, // "-vcodec", "flashsv", // "-map", "0" + FFMPEG_MAP_PARAM + "0", // "-map", "1" + FFMPEG_MAP_PARAM + "0", // outputFullFlv }; log.debug("START generateFullFLV ################# "); String tString = ""; for (int i = 0; i < argv_fullFLV.length; i++) { tString += argv_fullFLV[i] + " "; // log.debug(" i " + i + " argv-i " + argv_fullFLV[i]); } log.debug(tString); log.debug("END generateFullFLV ################# "); returnLog.add(ProcessHelper.executeScript("generateFullFLV", argv_fullFLV)); flvRecording.setFileHash(hashFileFullNameFlv); // Extract first Image for preview purpose // ffmpeg -i movie.flv -vcodec mjpeg -vframes 1 -an -f rawvideo -s // 320x240 movie.jpg String hashFileFullNameJPEG = "flvRecording_" + flvRecording.getFlvRecordingId() + ".jpg"; String outPutJpeg = streamFolderGeneralName + hashFileFullNameJPEG; flvRecording.setPreviewImage(hashFileFullNameJPEG); String[] argv_previewFLV = new String[] { // this.getPathToFFMPEG(), // "-i", outputFullFlv, // "-vcodec", "mjpeg", // "-vframes", "1", "-an", // "-f", "rawvideo", // "-s", flvWidth + "x" + flvHeight, // outPutJpeg }; log.debug("START previewFullFLV ################# "); log.debug(argv_previewFLV.toString()); String kString = ""; for (int i = 0; i < argv_previewFLV.length; i++) { kString += argv_previewFLV[i] + " "; } log.debug(kString); log.debug("END previewFullFLV ################# "); returnLog.add(ProcessHelper.executeScript("generateFullFLV", argv_previewFLV)); String alternateDownloadName = "flvRecording_" + flvRecording.getFlvRecordingId() + ".avi"; String alternateDownloadFullName = streamFolderGeneralName + alternateDownloadName; String[] argv_alternateDownload = new String[] { this.getPathToFFMPEG(), "-i", outputFullFlv, "-vcodec", "copy", alternateDownloadFullName }; log.debug("START alternateDownLoad ################# "); log.debug(argv_previewFLV.toString()); String sString = ""; for (int i = 0; i < argv_alternateDownload.length; i++) { sString += argv_alternateDownload[i] + " "; } log.debug(sString); log.debug("END alternateDownLoad ################# "); returnLog.add(ProcessHelper.executeScript("alternateDownload", argv_alternateDownload)); flvRecording.setAlternateDownload(alternateDownloadName); this.flvRecordingDaoImpl.updateFlvRecording(flvRecording); for (HashMap<String, String> returnMap : returnLog) { this.flvRecordingLogDaoImpl.addFLVRecordingLog("generateFFMPEG", flvRecording, returnMap); } // Delete Wave Files for (String fileName : listOfFullWaveFiles) { File audio = new File(fileName); if (audio.exists()) { audio.delete(); } } } catch (Exception err) { log.error("[stripAudioFromFLVs]", err); } }