List of usage examples for java.util Arrays binarySearch
public static int binarySearch(Object[] a, Object key)
From source file:Spline2D.java
/** * Returns an interpolated value. To be used when a long sequence of values * are required in order, but ensure checkValues() is called beforehand to * ensure the boundary checks from getValue() are made * @param x/*from ww w .j a v a 2 s . c om*/ * @return the interpolated value */ public double getFastValue(double x) { // Fast check to see if previous index is still valid if (storageIndex > -1 && storageIndex < xx.length - 1 && x > xx[storageIndex] && x < xx[storageIndex + 1]) { } else { int index = Arrays.binarySearch(xx, x); if (index > 0) { return yy[index]; } index = -(index + 1) - 1; storageIndex = index; } //TODO linear interpolation or extrapolation if (storageIndex < 0) { return yy[0]; } double value = x - xx[storageIndex]; return a[storageIndex] + b[storageIndex] * value + c[storageIndex] * (value * value) + d[storageIndex] * (value * value * value); }
From source file:com.krawler.common.util.SchedulingUtilities.java
public static int CountCmpHolidays(Date stdate, Date enddate, String[] CmpHoliDays) { int NonWorkingDays = 0; Calendar c1 = Calendar.getInstance(); DateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); try {/*ww w .ja v a2 s .co m*/ c1.setTime(stdate); while ((stdate.compareTo(enddate)) < 0) { if (Arrays.binarySearch(CmpHoliDays, sdf1.format(c1.getTime())) >= 0) { NonWorkingDays += 1; } c1.add(Calendar.DATE, 1); stdate = c1.getTime(); } } catch (Exception e) { System.out.print(e.getMessage()); } return NonWorkingDays; }
From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field.java
private void setValuesFromJson(JSONObject obj, String fieldName) { try {//from w w w .j av a 2s .c om this.name = fieldName; setNewResource(obj.getBoolean("newResource")); validators = EditConfiguration.JsonArrayToStringList(obj.getJSONArray("validators")); setOptionsType(obj.getString("optionsType")); predicateUri = obj.getString("predicateUri"); objectClassUri = obj.getString("objectClassUri"); rangeDatatypeUri = obj.getString("rangeDatatypeUri"); if (rangeDatatypeUri != null && rangeDatatypeUri.trim().length() == 0) rangeDatatypeUri = null; rangeLang = obj.getString("rangeLang"); if (rangeLang != null && rangeLang.trim().length() == 0) rangeLang = null; setLiteralOptions(obj.getJSONArray("literalOptions")); setAssertions(EditConfiguration.JsonArrayToStringList(obj.getJSONArray("assertions"))); setEditElement(obj, fieldName); //check for odd parameters JSONArray names = obj.names(); int size = names.length(); for (int i = 0; i < size; i++) { String name = (String) names.optString(i); if (Arrays.binarySearch(parameterNames, name) < 0) log.debug("setValuesFromJson(): the field " + fieldName + " has the unrecognized parameter " + name); } } catch (JSONException ex) { throw new Error(ex); } }
From source file:com.opengamma.financial.convention.daycount.AccruedInterestCalculator.java
/** * Calculates the accrued interest for a {@code LocalDate}. * /*ww w. ja va 2s. c om*/ * @param dayCount the day count convention, not null * @param settlementDate the settlement date, not null * @param nominalDates the nominalDates, not null, no null elements * @param coupon the coupon value * @param paymentsPerYear the number of payments per year, one, two, three, four, six or twelve * @param isEndOfMonthConvention whether to use end of month rules * @param exDividendDays the number of ex-dividend days * @param calendar The working day calendar to be used in calculating ex-dividend dates, not null * @return the accrued interest */ //TODO one where you can pass in array of coupons public static double getAccruedInterest(final DayCount dayCount, final LocalDate settlementDate, final LocalDate[] nominalDates, final double coupon, final double paymentsPerYear, final boolean isEndOfMonthConvention, final int exDividendDays, final Calendar calendar) { Validate.notNull(dayCount, "day-count"); Validate.notNull(settlementDate, "date"); Validate.noNullElements(nominalDates, "nominalDates"); Validate.notNull(calendar, "calendar"); Validate.isTrue(paymentsPerYear > 0); Validate.isTrue(exDividendDays >= 0); final int i = Arrays.binarySearch(nominalDates, settlementDate); if (i > 0) { return 0; } final int index = -i - 2; final int length = nominalDates.length; if (index < 0) { throw new IllegalArgumentException("Settlement date is before first accrual date"); } if (index == length) { throw new IllegalArgumentException("Settlement date is after maturity date"); } final ZonedDateTime previousCouponDate = nominalDates[index].atStartOfDay(ZoneOffset.UTC); final ZonedDateTime date = settlementDate.atStartOfDay(ZoneOffset.UTC); final ZonedDateTime nextCouponDate = nominalDates[index + 1].atStartOfDay(ZoneOffset.UTC); final double accruedInterest = getAccruedInterest(dayCount, index, length, previousCouponDate, date, nextCouponDate, coupon, paymentsPerYear, isEndOfMonthConvention); LocalDate exDividendDate = nominalDates[index + 1]; for (int j = 0; j < exDividendDays; j++) { while (!calendar.isWorkingDay(exDividendDate)) { exDividendDate = exDividendDate.minusDays(1); } exDividendDate = exDividendDate.minusDays(1); } if (exDividendDays != 0 && exDividendDate.isBefore(settlementDate)) { return accruedInterest - coupon; } return accruedInterest; }
From source file:com.example.app.config.automation.demo.DemoDataConversionVersion1.java
/** * Example data conversion.//w w w . j a va 2 s . co m * * @return data conversion. */ @Bean @TaskQualifier(TaskQualifier.Type.data_conversion) public DataConversion example2DataConversion() { final String[] signs = { "ARIES", "TAURUS", "GEMINI", "CANCER", "LEO", "VIRGO", "LIBRA", "SCORPIO", "SAGITTARIUS", "CAPRICORN", "AQUARIUS", "PISCES" }; Arrays.sort(signs); final List<SQLStatement> preDDL = singletonList( new SQLStatement("CREATE TABLE Example_FOO(id serial, val text, primary key (id))", null)); final List<SQLStatement> postDDL = singletonList(new SQLStatement("DROP TABLE Example_FOO;", null)); return new AbstractDataConversion(IDENTIFIER, "Example Numero Dos", 2, true, null, preDDL, postDDL) { @Override @Nonnull public List<TaskArgument> getAdditionalArguments() { List<TaskArgument> args = new ArrayList<>(); args.add(new TaskArgument(WHAT_S_YOUR_ZODIAC_SIGN, "", "Cancer", null)); return args; } @Override public List<? extends SQLStatement> execute(TaskArgument... arguments) throws SQLException, IllegalArgumentException { final SQLStatement stmt = new SQLStatement("INSERT INTO Example_Foo (val) VALUES (?)", "Insert Sign"); final Map<String, TaskArgument> argumentMapping = getArgumentMapping(arguments); stmt.setString(1, argumentMapping.get(WHAT_S_YOUR_ZODIAC_SIGN).getArgument().toString()); return singletonList(stmt); } @NotNull @Override public Map<TaskArgument, String> validateArguments(TaskArgument... arguments) { final Map<TaskArgument, String> validationMap = new HashMap<>(); final String sign = arguments[0].getArgument().toString().toUpperCase(); final int foundIndex = Arrays.binarySearch(signs, sign); if (foundIndex < 0) validationMap.put(arguments[0], "That's not your sign fool."); return validationMap; } @Override public List<? extends SQLStatement> getValidationStatements() { return singletonList(new SQLStatement("SELECT COUNT(*) FROM Example_FOO", null)); } @Override public String validateResult(SQLStatement stmt, int index, ResultSet result) throws SQLException { if (result.next()) { long count = result.getLong(1); return count == 1 ? null : "Received incorrect record count: " + count; } else return "Expecting Results"; } }; }
From source file:com.l2jserver.util.calculator.ComplexCalculator.java
/** * Removes an fuction from this calculator. * //from w w w. j a v a 2s .co m * @param function * the operation */ public void remove(Function<T, V> function) { Function<T, V>[] funcs = getList(function.type()); int index = Arrays.binarySearch(funcs, function); if (index >= 0) { funcs = ArrayUtils.remove(funcs, index); } setList(function.type(), funcs); }
From source file:itdelatrisu.opsu.Utils.java
/** * Cleans a file name.//from ww w . ja v a2s.c o m * @param badFileName the original name string * @param replace the character to replace illegal characters with (or 0 if none) * @return the cleaned file name * @author Sarel Botha (http://stackoverflow.com/a/5626340) */ public static String cleanFileName(String badFileName, char replace) { if (badFileName == null) return null; boolean doReplace = (replace > 0 && Arrays.binarySearch(illegalChars, replace) < 0); StringBuilder cleanName = new StringBuilder(); for (int i = 0, n = badFileName.length(); i < n; i++) { int c = badFileName.charAt(i); if (Arrays.binarySearch(illegalChars, c) < 0) cleanName.append((char) c); else if (doReplace) cleanName.append(replace); } return cleanName.toString(); }
From source file:com.ziaconsulting.zoho.EditorController.java
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { Match match = req.getServiceMatch(); Map<String, String> vars = match.getTemplateVars(); NodeRef theNodeRef = new NodeRef(vars.get("store_type"), vars.get("store_id"), vars.get("id")); String fileName = serviceRegistry.getNodeService().getProperty(theNodeRef, ContentModel.PROP_NAME) .toString();// w w w . j a v a 2 s . c om String protocol = ssl ? "https" : "http"; String extension; if (fileName.lastIndexOf('.') != -1) { extension = fileName.substring(fileName.lastIndexOf('.') + 1); } else { String contentMime = serviceRegistry.getContentService() .getReader(theNodeRef, ContentModel.PROP_CONTENT).getMimetype(); extension = serviceRegistry.getMimetypeService().getExtensionsByMimetype().get(contentMime); // Attach this extension to the filename fileName += "." + extension; log.debug("Extension not found, using mimetype " + contentMime + " to guess the extension file name is now " + fileName); } String zohoUrl = ""; if (Arrays.binarySearch(zohoDocFileExtensions, extension) >= 0) { zohoUrl = writerUrl; } else if (Arrays.binarySearch(zohoXlsFileExtensions, extension) >= 0) { zohoUrl = sheetUrl; } else if (Arrays.binarySearch(zohoPptFileExtensions, extension) >= 0) { zohoUrl = showUrl; } else { log.info("Invalid extension " + extension); return getErrorMap("Invalid extension"); } // Create multipart form for post List<Part> parts = new ArrayList<Part>(); String output = ""; if (vars.get("mode").equals("edit")) { output = "url"; parts.add(new StringPart("mode", "collabedit")); } else if (vars.get("mode").equals("view")) { output = "viewurl"; parts.add(new StringPart("mode", "view")); } String docIdBase = vars.get("store_type") + vars.get("store_id") + vars.get("id"); parts.add(new StringPart("documentid", generateDocumentId(docIdBase))); String id = theNodeRef.toString() + "#" + serviceRegistry.getAuthenticationService().getCurrentTicket(); parts.add(new StringPart("id", id)); parts.add(new StringPart("format", extension)); parts.add(new StringPart("filename", fileName)); parts.add(new StringPart("username", serviceRegistry.getAuthenticationService().getCurrentUserName())); parts.add(new StringPart("skey", skey)); if (useRemoteAgent) { parts.add(new StringPart("agentname", remoteAgentName)); } else { String saveUrl; saveUrl = protocol + "://" + this.saveUrl + "/alfresco/s/zohosave"; parts.add(new StringPart("saveurl", saveUrl)); } ContentReader cr = serviceRegistry.getContentService().getReader(theNodeRef, ContentModel.PROP_CONTENT); if (!(cr instanceof FileContentReader)) { log.error("The content reader was not a FileContentReader"); return getErrorMap("Error"); } PartSource src = null; try { src = new FilePartSource(fileName, ((FileContentReader) cr).getFile()); } catch (FileNotFoundException e) { e.printStackTrace(); log.error("The content did not exist."); return getErrorMap("Error"); } parts.add(new FilePart("content", src, cr.getMimetype(), null)); HttpClient client = new HttpClient(); String zohoFormUrl = protocol + "://" + zohoUrl + "/remotedoc.im?" + "apikey=" + apiKey + "&output=" + output; PostMethod httppost = new PostMethod(zohoFormUrl); httppost.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), httppost.getParams())); Map<String, Object> returnMap = getReturnMap(); String retStr = ""; int zohoStatus = 0; try { zohoStatus = client.executeMethod(httppost); retStr = httppost.getResponseBodyAsString(); } catch (HttpException he) { log.error("Error", he); returnMap = getErrorMap("Error"); } catch (IOException io) { io.printStackTrace(); log.error("Error", io); returnMap = getErrorMap("Error"); } if (zohoStatus == 200) { Map<String, String> parsedResponse = parseResponse(retStr); if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("TRUE")) { returnMap.put("zohourl", parsedResponse.get("URL")); } else if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("FALSE")) { returnMap = getErrorMap(parsedResponse.get("ERROR")); } } else { returnMap = getErrorMap("Remote server did not respond"); } return returnMap; }
From source file:master.utilities.PopulationFunctionFromJSON.java
@Override public double getPopSize(double t) { double tforward = convertTime(t); if (tforward > times[times.length - 1]) return popSizeEndInput.get(); if (tforward < 0) return popSizeStartInput.get(); // Choose which index into integration lattice to use: int tidx = Arrays.binarySearch(times, tforward); if (tidx < 0) tidx = -(tidx + 1) - 1;//from ww w . ja v a 2 s . co m return popSizes[tidx]; }
From source file:net.maizegenetics.analysis.imputation.FILLINImputationAccuracy.java
private boolean generateMAF() { this.MAF = new int[this.unimp.numberOfSites()]; for (GenotypeTable don : this.donor) { for (int site = 0; site < don.numberOfSites(); site++) { int unimpSite = this.unimp.positions().indexOf(don.positions().get(site)); if (unimpSite < 0) { this.MAF[unimpSite] = -1; continue; }//ww w .jav a2 s. com int search = Arrays.binarySearch(this.MAFClass, don.minorAlleleFrequency(site)); this.MAF[unimpSite] = search < 0 ? Math.abs(search) - 1 : search; } } return true; }