List of usage examples for java.util Arrays binarySearch
public static int binarySearch(Object[] a, Object key)
From source file:Spline2D.java
/** * Returns the first derivation at x./*from w w w. j a va 2 s . c om*/ * @param x * @return the first derivation at x */ public double getDx(double x) { if (xx.length == 0 || xx.length == 1) { return 0; } int index = Arrays.binarySearch(xx, x); if (index < 0) { index = -(index + 1) - 1; } return b[index] + 2 * c[index] * (x - xx[index]) + 3 * d[index] * Math.pow(x - xx[index], 2); }
From source file:com.opengamma.util.timeseries.fast.integer.object.FastArrayIntObjectTimeSeries.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from w ww . ja v a2s . c o m public FastIntObjectTimeSeries<T> subSeriesFast(final int startTime, final int endTime) { if (isEmpty()) { return new FastArrayIntObjectTimeSeries(getEncoding(), new int[0], (T[]) new Object[0]); } // throw new NoSuchElementException("Series is empty") int startPos = Arrays.binarySearch(_times, startTime); int endPos = Arrays.binarySearch(_times, endTime); // if either is -1, make it zero startPos = startPos >= 0 ? startPos : -(startPos + 1); endPos = endPos >= 0 ? endPos : -(endPos + 1); final int length = endPos - startPos; final int[] resultTimes = new int[length]; final T[] resultValues = (T[]) new Object[length]; System.arraycopy(_times, startPos, resultTimes, 0, length); System.arraycopy(_values, startPos, resultValues, 0, length); return new FastArrayIntObjectTimeSeries(getEncoding(), resultTimes, resultValues); }
From source file:geovista.readers.csv.GeogCSVReader.java
public Object[] readFileStreaming(InputStream is, ArrayList<Integer> columns) { BufferedReader in = new BufferedReader(new InputStreamReader(is)); Iterable<CSVRecord> parser = null; try {//from w ww . j av a2s. c o m parser = CSVFormat.DEFAULT.withDelimiter(this.currDelimiter).parse(in); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int count = 0; for (CSVRecord rec : parser) { // eDays.add(rec.get(0)); // type.add(rec.get(10) + " - " + rec.get(8)); System.out.println(rec.get(0)); System.out.println(rec.toString()); count++; } // CSVParser shredder = new CSVParser() // CSVParser shredder = new CSVParser(is); // shredder.setCommentStart("#;!"); // shredder.setEscapes("nrtf", "\n\r\t\f"); String[] headers = null; String[] types = null; int[] dataTypes = null; String[][] fileContent = null; int dataBegin; Object[] data; try { // fileContent = shredder.getAllValues(); } catch (Exception ex) { ex.printStackTrace(); } types = fileContent[0];// first line tells us types dataTypes = new int[types.length]; int len; if (types[0].equalsIgnoreCase("int") || types[0].equalsIgnoreCase("double") || types[0].equalsIgnoreCase("string")) { dataBegin = 2; headers = fileContent[1]; data = new Object[headers.length + 1];// plus one for the headers // themselves len = fileContent.length - dataBegin; for (int i = 0; i < headers.length; i++) { if (types[i].equalsIgnoreCase("int")) { data[i + 1] = new int[len]; dataTypes[i] = GeogCSVReader.DATA_TYPE_INT; } else if (types[i].equalsIgnoreCase("double")) { data[i + 1] = new double[len]; dataTypes[i] = GeogCSVReader.DATA_TYPE_DOUBLE; } else if (types[i].equalsIgnoreCase("string")) { data[i + 1] = new String[len]; dataTypes[i] = GeogCSVReader.DATA_TYPE_STRING; } else { throw new IllegalArgumentException("GeogCSVReader.readFile, unknown type = " + types[i]); } } } else { dataBegin = 1; headers = fileContent[0]; data = new Object[headers.length + 1];// plus one for the headers // themselves len = fileContent.length - dataBegin; for (int i = 0; i < headers.length; i++) { String firstString = fileContent[1][i]; String secondString = fileContent[2][i]; String thirdString = fileContent[3][i]; String lastString = fileContent[fileContent[0].length][i]; if (isNumeric(firstString) && isNumeric(secondString) && isNumeric(thirdString) && isNumeric(lastString)) { if (isInt(fileContent, i) == false) { // if (isDouble(firstString) || isDouble(secondString) // || isDouble(thirdString) || isDouble(lastString)) { data[i + 1] = new double[len]; dataTypes[i] = GeogCSVReader.DATA_TYPE_DOUBLE; } else { data[i + 1] = new int[len]; dataTypes[i] = GeogCSVReader.DATA_TYPE_INT; } } else { data[i + 1] = new String[len]; dataTypes[i] = GeogCSVReader.DATA_TYPE_STRING; } } } data[0] = headers; String[] line = null; for (int row = dataBegin; row < len + dataBegin; row++) { line = fileContent[row]; int[] ints = null; double[] doubles = null; String[] strings = null; for (int column = 0; column < line.length; column++) { String item = line[column]; if (dataTypes[column] == GeogCSVReader.DATA_TYPE_INT) { if (Arrays.binarySearch(GeogCSVReader.NULL_STRINGS, item) >= 0) { ints = (int[]) data[column + 1]; ints[row - dataBegin] = GeogCSVReader.NULL_INT; } else { ints = (int[]) data[column + 1]; try { ints[row - dataBegin] = Integer.parseInt(item); } catch (NumberFormatException nfe) { logger.warning("could not parse " + item + " in column " + column); // nfe.printStackTrace(); ints[row - dataBegin] = GeogCSVReader.NULL_INT; } } } else if (dataTypes[column] == GeogCSVReader.DATA_TYPE_DOUBLE) { if (Arrays.binarySearch(GeogCSVReader.NULL_STRINGS, item) >= 0) { doubles = (double[]) data[column + 1]; doubles[row - dataBegin] = GeogCSVReader.NULL_DOUBLE; } else { doubles = (double[]) data[column + 1]; doubles[row - dataBegin] = parseDouble(item); } } else if (dataTypes[column] == GeogCSVReader.DATA_TYPE_STRING) { strings = (String[]) data[column + 1]; strings[row - dataBegin] = item; } else { throw new IllegalArgumentException("GeogCSVReader.readFile, unknown type = " + types[row]); } // end if } // next column } // next row return data; }
From source file:edu.umn.cs.spatialHadoop.indexing.STRPartitioner.java
@Override public int overlapPartition(Shape shape) { if (shape == null) return -1; Rectangle shapeMBR = shape.getMBR(); if (shapeMBR == null) return -1; // Assign to only one partition Point center = shapeMBR.getCenterPoint(); int col = Arrays.binarySearch(xSplits, center.x); if (col < 0) col = -col - 1;// w w w . ja va 2 s . c om int cell = Arrays.binarySearch(ySplits, col * rows, (col + 1) * rows, center.y); if (cell < 0) cell = -cell - 1; return cell; }
From source file:edu.umn.cs.spatialHadoop.indexing.BTRPartitioner.java
@Override public int overlapPartition(Shape shape) { if (shape == null) return -1; Rectangle shapeMBR = shape.getMBR(); if (shapeMBR == null) return -1; // Assign to only one partition //Point center = shapeMBR.getCenterPoint(); int col = Arrays.binarySearch(xSplits, shapeMBR.x1); if (col < 0) col = -col - 1;//from w ww. j a va 2s .c o m int cell = Arrays.binarySearch(ySplits, col * rows, (col + 1) * rows, shapeMBR.y1); if (cell < 0) cell = -cell - 1; return cell; }
From source file:com.enonic.vertical.userservices.OrderHandlerController.java
protected void handlerCustom(HttpServletRequest request, HttpServletResponse response, HttpSession session, ExtendedMap formItems, UserServicesService userServices, SiteKey siteKey, String operation) throws VerticalUserServicesException, VerticalEngineException, RemoteException { MultiValueMap queryParams = new MultiValueMap(); // NB! Operations must be sorted alphabetically! String[] operations = new String[] { "cart_add", "cart_checkout", "cart_empty", "cart_remove", "cart_update" }; if (operation != null && Arrays.binarySearch(operations, operation) >= 0) { ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingcart"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("shoppingcart", cart); }//w w w .j a v a2s . c om try { if ("cart_add".equals(operation)) { int productId = formItems.getInt("productid"); int count = formItems.getInt("count", 1); if (count > 0) { User user = securityService.getOldUserObject(); String xml = userServices.getContent(user, productId, true, 0, 0, 0); if (xml == null || xml.length() == 0) { String message = "Failed to get product: %0"; VerticalUserServicesLogger.warn(this.getClass(), 0, message, productId, null); redirectToErrorPage(request, response, formItems, ERR_FAILED_TO_GET_PRODUCT, null); return; } Document doc = XMLTool.domparse(xml); Element root = doc.getDocumentElement(); if (XMLTool.getFirstElement(root) == null) { redirectToErrorPage(request, response, formItems, ERR_FAILED_TO_GET_PRODUCT, null); return; } String productNumber = XMLTool.getElementText(doc, "/contents/content/contentdata/number"); String productName = XMLTool.getElementText(doc, "/contents/content/title"); String priceStr = XMLTool.getElementText(doc, "/contents/content/contentdata/price"); double price; if (priceStr != null) { priceStr = priceStr.replace(',', '.'); price = Double.parseDouble(priceStr); } else { price = 0.0D; } String[] keyFilter = new String[] { "count", "handler", "_handler", "op", "_op", "productid", "redirect", "_redirect" }; Map<String, String> customValues = new HashMap<String, String>(); for (Object o : formItems.keySet()) { String key = (String) o; if (Arrays.binarySearch(keyFilter, key) < 0) { customValues.put(key, formItems.get(key).toString()); } } cart.addItem(productId, productNumber, productName, price, count, customValues); } } else if ("cart_remove".equals(operation)) { int productId = formItems.getInt("productid"); cart.removeItem(productId); } else if ("cart_update".equals(operation)) { int productId = formItems.getInt("productid"); int count = formItems.getInt("count", 1); if (count > 0) { cart.updateItem(productId, count); } else { cart.removeItem(productId); } } else if ("cart_checkout".equals(operation)) { if (cart.isEmpty()) { redirectToErrorPage(request, response, formItems, ERR_SHOPPING_CART_EMPTY, null); return; } User user = securityService.getOldUserObject(); String guid = new UID().toString(); formItems.put("_guid", guid); formItems.put("_shoppingcart", cart); // customer name String customerFirstname = formItems.getString("customer_firstname"); String customerSurname = formItems.getString("customer_surname"); StringBuffer customerName = new StringBuffer(customerFirstname); if (customerName.length() > 0) { customerName.append(' '); } customerName.append(customerSurname); String xmlData = buildXML(userServices, user, formItems, siteKey, contentTypeKey, customerName.toString(), false); ContentKey orderKey = storeNewContent(user, null, xmlData); // send mail // mail header String[] shopManagerEmail = formItems.getStringArray("shopmanager_email"); //String shopManagerName = formItems.getString("shopmanager_name"); String sender_email = formItems.getString("mail_sender_email"); String sender_name = formItems.getString("mail_sender_name"); String customerEmail = formItems.getString("customer_email"); String receiver_name = customerFirstname + ' ' + customerSurname; String subject = formItems.getString("mail_subject"); String message = formItems.getString("mail_message"); // order info String orderId = orderKey.toString(); String orderDate = CalendarUtil.formatCurrentDate(); String orderStatus = "Submitted"; String orderReference = formItems.getString("order_reference", ""); String orderUrl = formItems.getString("showorderurl", "") + "page?id=" + formItems.getString("showorderpage", "") + "&key=" + orderKey.toString() + "&guid=" + guid; subject = RegexpUtil.substituteAll("\\%order_id\\%", orderId, subject); message = RegexpUtil.substituteAll("\\%order_id\\%", orderId, message); message = RegexpUtil.substituteAll("\\%order_reference\\%", orderReference, message); message = RegexpUtil.substituteAll("\\%order_date\\%", orderDate, message); message = RegexpUtil.substituteAll("\\%order_status\\%", orderStatus, message); message = RegexpUtil.substituteAll("\\%order_url\\%", orderUrl, message); // customer info String customerRefNo = formItems.getString("customer_refno", ""); String customerCompany = formItems.getString("customer_company", ""); String customerTelephone = formItems.getString("customer_telephone", ""); String customerMobile = formItems.getString("customer_mobile", ""); String customerFax = formItems.getString("customer_fax", ""); message = RegexpUtil.substituteAll("\\%customer_firstname\\%", customerFirstname, message); message = RegexpUtil.substituteAll("\\%customer_surname\\%", customerSurname, message); message = RegexpUtil.substituteAll("\\%customer_email\\%", customerEmail, message); message = RegexpUtil.substituteAll("\\%customer_refno\\%", customerRefNo, message); message = RegexpUtil.substituteAll("\\%customer_company\\%", customerCompany, message); message = RegexpUtil.substituteAll("\\%customer_telephone\\%", customerTelephone, message); message = RegexpUtil.substituteAll("\\%customer_mobile\\%", customerMobile, message); message = RegexpUtil.substituteAll("\\%customer_fax\\%", customerFax, message); // shipping address String shippingPostalAddress = formItems.getString("shipping_postaladdress", ""); String shippingPostalCode = formItems.getString("shipping_postalcode", ""); String shippingLocation = formItems.getString("shipping_location", ""); String shippingCountry = formItems.getString("shipping_country", ""); String shippingState = formItems.getString("shipping_state", ""); message = RegexpUtil.substituteAll("\\%shipping_postaladdress\\%", shippingPostalAddress, message); message = RegexpUtil.substituteAll("\\%shipping_postalcode\\%", shippingPostalCode, message); message = RegexpUtil.substituteAll("\\%shipping_location\\%", shippingLocation, message); message = RegexpUtil.substituteAll("\\%shipping_country\\%", shippingCountry, message); message = RegexpUtil.substituteAll("\\%shipping_state\\%", shippingState, message); // billing address String billingPostalAddress = formItems.getString("billing_postaladdress", ""); String billingPostalCode = formItems.getString("billing_postalcode", ""); String billingLocation = formItems.getString("billing_location", ""); String billingCountry = formItems.getString("billing_country", ""); String billingState = formItems.getString("billing_state", ""); message = RegexpUtil.substituteAll("\\%billing_postaladdress\\%", billingPostalAddress, message); message = RegexpUtil.substituteAll("\\%billing_postalcode\\%", billingPostalCode, message); message = RegexpUtil.substituteAll("\\%billing_location\\%", billingLocation, message); message = RegexpUtil.substituteAll("\\%billing_country\\%", billingCountry, message); message = RegexpUtil.substituteAll("\\%billing_state\\%", billingState, message); String regexp = "\\%details_(comments|shippingoptions)\\%"; String substRegexpStart = "\\%details_"; String substRegexpEnd = "\\%"; Matcher results = RegexpUtil.match(message, regexp); while (results.find()) { String orderDetail = ""; StringBuffer substRegexp = new StringBuffer(substRegexpStart); substRegexp.append(results.group(1)); substRegexp.append(substRegexpEnd); if ("comments".equals(results.group(1))) { if (formItems.containsKey("details_comments")) { orderDetail = (String) formItems.get("details_comments"); } else { orderDetail = ""; } } else if ("shippingoptions".equals(results.group(1))) { if (formItems.containsKey("details_shippingoptions")) { orderDetail = (String) formItems.get("details_shippingoptions"); } else { orderDetail = ""; } } message = RegexpUtil.substituteAll(substRegexp.toString(), orderDetail, message); } String orderItem = formItems.getString("mail_order_item"); message = cart.addItemsToMailMessage(message, orderItem); message = cart.addTotalToMailMessage(message); sendMail(customerEmail, receiver_name, sender_email, sender_name, subject, message); if (shopManagerEmail.length > 0) { for (String aShopManagerEmail : shopManagerEmail) { if (StringUtils.isNotEmpty(aShopManagerEmail)) { sendMail(aShopManagerEmail, null, sender_email, sender_name, subject, message); } } } cart.clear(); String showOrder = formItems.getString("showorderonredirect", null); if ("true".equals(showOrder)) { queryParams.put("key", orderKey.toString()); queryParams.put("guid", guid); } } else if ("cart_empty".equals(operation)) { cart.clear(); } redirectToPage(request, response, formItems, queryParams); } catch (UnsupportedEncodingException uee) { String message = "Un-supported encoding: %t"; VerticalUserServicesLogger.error(this.getClass(), 0, message, uee); redirectToErrorPage(request, response, formItems, ERR_EMAIL_SEND_FAILED, null); } catch (MessagingException me) { String message = "Failed to send order received mail: %t"; VerticalUserServicesLogger.error(this.getClass(), 0, message, operation, me); redirectToErrorPage(request, response, formItems, ERR_EMAIL_SEND_FAILED, null); } } else { String message = "Unknown operation: %0"; VerticalUserServicesLogger.errorUserServices(this.getClass(), 0, message, operation, null); } }
From source file:com.example.app.config.automation.ExampleAppDataConversionVersion1.java
/** * Example data conversion./* w ww. ja v a 2s .com*/ * * @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 = Collections.singletonList( new SQLStatement("CREATE TABLE Example_FOO(id serial, val text, primary key (id))", null)); final List<SQLStatement> postDDL = Collections .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 Collections.singletonList(stmt); } @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 Collections.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.opengamma.util.timeseries.fast.longint.object.FastArrayLongObjectTimeSeries.java
@SuppressWarnings("unchecked") @Override/*from ww w . j av a 2 s .c o m*/ public FastLongObjectTimeSeries<T> subSeriesFast(final long startTime, final long endTime) { if (isEmpty()) { return new FastArrayLongObjectTimeSeries<T>(getEncoding(), new long[0], (T[]) new Object[0]); } // throw new NoSuchElementException("Series is empty") int startPos = Arrays.binarySearch(_times, startTime); int endPos = Arrays.binarySearch(_times, endTime); // if either is -1, make it zero startPos = startPos >= 0 ? startPos : -startPos - 1; endPos = endPos >= 0 ? endPos : -endPos - 1; final int length = endPos - startPos; final long[] resultTimes = new long[length]; final T[] resultValues = (T[]) new Object[length]; System.arraycopy(_times, startPos, resultTimes, 0, length); System.arraycopy(_values, startPos, resultValues, 0, length); return new FastArrayLongObjectTimeSeries<T>(getEncoding(), resultTimes, resultValues); }
From source file:com.opengamma.util.timeseries.fast.longint.FastArrayLongDoubleTimeSeries.java
@Override public FastLongDoubleTimeSeries subSeriesFast(final long startTime, final long endTime) { if (isEmpty()) { return EMPTY_SERIES; }/* www . j a v a 2s . c om*/ // throw new NoSuchElementException("Series is empty") int startPos = Arrays.binarySearch(_times, startTime); int endPos = (endTime == Long.MIN_VALUE) ? _times.length : Arrays.binarySearch(_times, endTime); // if either is -1, make it zero startPos = startPos >= 0 ? startPos : -startPos - 1; endPos = endPos >= 0 ? endPos : -endPos - 1; final int length = endPos - startPos; if (endPos >= _times.length) { endPos--; } final long[] resultTimes = new long[length]; final double[] resultValues = new double[length]; System.arraycopy(_times, startPos, resultTimes, 0, length); System.arraycopy(_values, startPos, resultValues, 0, length); return new FastArrayLongDoubleTimeSeries(getEncoding(), resultTimes, resultValues); }
From source file:org.apache.taverna.activities.wsdl.xmlsplitter.XMLSplitterConfigurationBeanBuilder.java
public static JsonNode buildBeanForOutput(Element element) throws JDOMException, IOException { ObjectNode bean = JSON_NODE_FACTORY.objectNode(); ArrayNode inputDefinitions = bean.arrayNode(); bean.put("inputPorts", inputDefinitions); ArrayNode outputDefinitions = bean.arrayNode(); bean.put("outputPorts", outputDefinitions); TypeDescriptor descriptor = XMLSplitterSerialisationHelper.extensionXMLToTypeDescriptor(element); ObjectNode inBean = inputDefinitions.addObject(); inBean.put("name", "input"); inBean.put("mimeType", "'text/xml'"); inBean.put("depth", 0); if (descriptor instanceof ComplexTypeDescriptor) { List<TypeDescriptor> elements = ((ComplexTypeDescriptor) descriptor).getElements(); String[] names = new String[elements.size()]; Class<?>[] types = new Class<?>[elements.size()]; TypeDescriptor.retrieveSignature(elements, names, types); for (int i = 0; i < names.length; i++) { ObjectNode portBean = outputDefinitions.addObject(); portBean.put("name", names[i]); portBean.put("mimeType", TypeDescriptor.translateJavaType(types[i])); int depth = depthForDescriptor(elements.get(i)); portBean.put("depth", depth); portBean.put("granularDepth", depth); }// w ww . j a v a 2 s .com List<TypeDescriptor> attributes = ((ComplexTypeDescriptor) descriptor).getAttributes(); String[] elementNames = Arrays.copyOf(names, names.length); Arrays.sort(elementNames); String[] attributeNames = new String[attributes.size()]; Class<?>[] attributeTypes = new Class<?>[attributes.size()]; TypeDescriptor.retrieveSignature(attributes, attributeNames, attributeTypes); for (int i = 0; i < attributeNames.length; i++) { ObjectNode portBean = outputDefinitions.addObject(); if (Arrays.binarySearch(elementNames, attributeNames[i]) < 0) { portBean.put("name", attributeNames[i]); } else { portBean.put("name", "1" + attributeNames[i]); } portBean.put("mimeType", TypeDescriptor.translateJavaType(attributeTypes[i])); int depth = depthForDescriptor(attributes.get(i)); portBean.put("depth", depth); portBean.put("granularDepth", depth); } } else if (descriptor instanceof ArrayTypeDescriptor) { ObjectNode portBean = outputDefinitions.addObject(); String name = descriptor.getName(); portBean.put("name", name); portBean.put("depth", 1); portBean.put("granularDepth", 1); if (((ArrayTypeDescriptor) descriptor).getElementType() instanceof BaseTypeDescriptor) { portBean.put("mimeType", "l('text/plain')"); } else { portBean.put("mimeType", "l('text/xml')"); } } String wrappedType = new XMLOutputter().outputString(element); bean.put("wrappedType", wrappedType); return bean; }