List of usage examples for java.lang Double toString
public static String toString(double d)
From source file:matrix.CreateTextMatrix.java
public void textMatrix() throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException { CosSim cossim = new CosSim(); JSONParser jParser = new JSONParser(); BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweets.json"), "ISO-8859-9")); JSONArray a = (JSONArray) jParser.parse(in); File fout = new File("/Users/nSabri/Desktop/tweetMatris.csv"); FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { JSONObject tweet1 = (JSONObject) a.get(i); JSONObject tweet2 = (JSONObject) a.get(j); String tweetText1 = tweet1.get("tweets").toString(); String tweetText2 = tweet2.get("tweets").toString(); double CosSimValue = cossim.Cosine_Similarity_Score(tweetText1, tweetText2); CosSimValue = Double.parseDouble(new DecimalFormat("##.###").format(CosSimValue)); bw.write(Double.toString(CosSimValue) + ", "); }/*from w ww. j a va 2 s .c o m*/ bw.newLine(); } bw.close(); }
From source file:alfio.manager.location.DefaultLocationManager.java
@Override @Cacheable//from w w w. j a v a2s .com public Pair<String, String> geocode(String address) { return Optional.ofNullable(GeocodingApi.geocode(getApiContext(), address).awaitIgnoreError()) .filter(r -> r.length > 0).map(r -> r[0].geometry.location) .map(l -> Pair.of(Double.toString(l.lat), Double.toString(l.lng))) .orElseThrow(() -> new LocationNotFound("No location found for address " + address)); }
From source file:io.fabric8.example.variance.http.VarianceProcessorTest.java
@Test public void testProcess() throws Exception { RandomGenerator rg = new JDKRandomGenerator(); double[] array = new double[10]; ObjectMapper objectMapper = new ObjectMapper(); for (int i = 0; i < array.length; i++) { array[i] = rg.nextDouble();/*from w w w. j a v a 2 s. c o m*/ } String body = objectMapper.writeValueAsString(array); String expectedBody = "0.0"; SummaryStatistics summaryStatistics = new SummaryStatistics(); List<Double> list = new ObjectMapper().readValue(body, List.class); for (Double value : list) { summaryStatistics.addValue(value); } String variance = Double.toString(summaryStatistics.getVariance()); resultEndpoint.expectedBodiesReceived(variance); template.sendBody(body); resultEndpoint.assertIsSatisfied(); }
From source file:com.baidubce.services.moladb.model.AttributeValue.java
/** * Constructs a new AttributeValue object and init the value type as Number * //from w w w . j ava 2s. c o m * @param d The initial value of AttributeValue */ public AttributeValue(double d) { attributeType = AttributeValue.ATTRIBUTE_TYPE_NUMBER; attributeValue = Double.toString(d); }
From source file:mzmatch.ipeak.align.CowCoda.java
@SuppressWarnings("unchecked") public static void main(String args[]) { final String lbl_mcq = "mcq"; try {// www . ja v a 2 s .co m Tool.init(); // parse the commandline options final Options options = new Options(); CmdLineParser cmdline = new CmdLineParser(options); // check whether we need to show the help cmdline.parse(args); if (options.help) { Tool.printHeader(System.out, application, version); cmdline.printUsage(System.out, ""); return; } if (options.verbose) { Tool.printHeader(System.out, application, version); cmdline.printOptions(); } // check the command-line parameters int filetype = JFreeChartTools.PDF; { if (options.ppm == -1) { System.err.println("[ERROR]: the ppm-value needs to be set."); System.exit(0); } if (options.order == -1) { System.err.println("[ERROR]: the order for the polynomial fit needs to be set."); System.exit(0); } if (options.maxrt == -1) { System.err.println("[ERROR]: the maximum retention time shift is not set."); System.exit(0); } if (options.image != null) { String extension = options.image.substring(options.image.lastIndexOf('.') + 1); if (extension.toLowerCase().equals("png")) filetype = JFreeChartTools.PNG; else if (extension.toLowerCase().equals("pdf")) filetype = JFreeChartTools.PDF; else { System.err.println( "[ERROR]: file extension of the image file needs to be either PDF or PNG."); System.exit(0); } } // if the output directories do not exist, create them if (options.output != null) Tool.createFilePath(options.output, true); if (options.image != null) Tool.createFilePath(options.image, true); if (options.selection != null) Tool.createFilePath(options.selection, true); } // load the data if (options.verbose) System.out.println("Loading the data"); double maxrt = 0; Vector<ParseResult> data = new Vector<ParseResult>(); Vector<IPeakSet<IPeak>> matchdata = new Vector<IPeakSet<IPeak>>(); for (String file : options.input) { System.out.println("- " + new File(file).getName()); // load the mass chromatogram data ParseResult result = PeakMLParser.parse(new FileInputStream(file), true); data.add(result); // select the best mass chromatograms Vector<IPeak> selection = new Vector<IPeak>(); for (IPeak peak : (IPeakSet<IPeak>) result.measurement) { maxrt = Math.max(maxrt, maxRT(peak)); double mcq = codaDW(peak); peak.addAnnotation(lbl_mcq, Double.toString(mcq), Annotation.ValueType.DOUBLE); if (mcq >= options.codadw) selection.add(peak); } // keep track of the selected mass chromatograms int id = options.input.indexOf(file); IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(selection); peakset.setMeasurementID(id); for (IPeak mc : peakset) mc.setMeasurementID(id); matchdata.add(peakset); } // match the selection together if (options.verbose) System.out.println("Matching the data"); Vector<IPeakSet<IPeak>> matches = IPeak.match((Vector) matchdata, options.ppm, new IPeak.MatchCompare<IPeak>() { public double distance(IPeak peak1, IPeak peak2) { double diff = Math.abs(peak1.getRetentionTime() - peak2.getRetentionTime()); if (diff > options.maxrt) return -1; Signal signal1 = new Signal(peak1.getSignal()); signal1.normalize(); Signal signal2 = new Signal(peak2.getSignal()); signal2.normalize(); double offset = bestOffSet(peak1, peak2, options.maxrt); for (int i = 0; i < signal2.getSize(); ++i) signal2.getX()[i] += offset; double correlation = signal2 .pearsonsCorrelation(signal1)[Statistical.PEARSON_CORRELATION]; if (correlation < 0.5) return -1; // the match-function optimizes toward 0 (it's a distance) return 1 - correlation; } }); // filter out all incomplete sets Vector<IPeakSet<IPeak>> valids = new Vector<IPeakSet<IPeak>>(); for (IPeakSet<IPeak> set : matches) { if (set.size() < options.input.size()) continue; valids.add((IPeakSet) set); } // calculate the alignment factors if (options.verbose) System.out.println("Calculating the alignment factors"); double medians[] = new double[valids.size() + 2]; DataFrame.Double dataframe = new DataFrame.Double(valids.size() + 2, options.input.size()); medians[0] = 0; medians[medians.length - 1] = maxrt; for (int i = 0; i < options.input.size(); ++i) { dataframe.set(0, i, 0.1); dataframe.set(dataframe.getNrRows() - 1, i, 0); } for (int matchid = 0; matchid < valids.size(); ++matchid) { IPeakSet<IPeak> match = valids.get(matchid); // find the most central double offsets[][] = new double[match.size()][match.size()]; for (int i = 0; i < match.size(); ++i) for (int j = i + 1; j < match.size(); ++j) { offsets[i][j] = bestOffSet(match.get(i), match.get(j), options.maxrt); offsets[j][i] = -offsets[i][j]; } int besti = 0; double bestabssum = Double.MAX_VALUE; for (int i = 0; i < match.size(); ++i) { double abssum = 0; for (int j = 0; j < match.size(); ++j) abssum += Math.abs(offsets[i][j]); if (abssum < bestabssum) { besti = i; bestabssum = abssum; } } for (int i = 0; i < match.size(); ++i) dataframe.set(matchid + 1, match.get(i).getMeasurementID(), (i == besti ? 0 : offsets[i][besti])); medians[matchid + 1] = match.get(besti).getRetentionTime(); dataframe.setRowName(matchid, Double.toString(match.get(besti).getRetentionTime())); } double minmedian = Statistical.min(medians); double maxmedian = Statistical.max(medians); // calculate for each profile the correction function PolynomialFunction functions[] = new PolynomialFunction[valids.size()]; for (int i = 0; i < options.input.size(); ++i) functions[i] = PolynomialFunction.fit(options.order, medians, dataframe.getCol(i)); // make a nice plot out of the whole thing if (options.verbose) System.out.println("Writing results"); if (options.image != null) { org.jfree.data.xy.XYSeriesCollection dataset = new org.jfree.data.xy.XYSeriesCollection(); JFreeChart linechart = ChartFactory.createXYLineChart(null, "Retention Time (seconds)", "offset", dataset, PlotOrientation.VERTICAL, true, // legend false, // tooltips false // urls ); // setup the colorkey Colormap colormap = new Colormap(Colormap.EXCEL); // get the structure behind the graph XYPlot plot = (XYPlot) linechart.getPlot(); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); // setup the plot area linechart.setBackgroundPaint(java.awt.Color.WHITE); linechart.setBorderVisible(false); linechart.setAntiAlias(true); plot.setBackgroundPaint(java.awt.Color.WHITE); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); // create the datasets for (int i = 0; i < options.input.size(); ++i) { org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i)); org.jfree.data.xy.XYSeries function = new org.jfree.data.xy.XYSeries( dataframe.getColName(i) + "-function"); dataset.addSeries(series); dataset.addSeries(function); renderer.setSeriesPaint(dataset.getSeriesCount() - 1, new java.awt.Color(colormap.getColor(i))); renderer.setSeriesPaint(dataset.getSeriesCount() - 2, new java.awt.Color(colormap.getColor(i))); renderer.setSeriesLinesVisible(dataset.getSeriesCount() - 2, false); renderer.setSeriesShapesVisible(dataset.getSeriesCount() - 2, true); // add the data-points for (int j = 0; j < valids.size(); ++j) series.add(medians[j], dataframe.get(j, i)); for (double x = minmedian; x < maxmedian; ++x) function.add(x, functions[i].getY(x)); } dataset.removeAllSeries(); for (int i = 0; i < options.input.size(); ++i) { Function function = functions[i]; org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i)); dataset.addSeries(series); renderer.setSeriesPaint(i, new java.awt.Color(colormap.getColor(i))); renderer.setSeriesLinesVisible(i, false); renderer.setSeriesShapesVisible(i, true); // add the data-points for (int j = 0; j < valids.size(); ++j) series.add(medians[j], dataframe.get(j, i) - function.getY(medians[j])); } JFreeChartTools.writeAs(filetype, new FileOutputStream(options.image), linechart, 800, 500); } // save the selected if (options.selection != null) { Header header = new Header(); // set the number of peaks to be stored header.setNrPeaks(valids.size()); // create a set for the measurements SetInfo set = new SetInfo("", SetInfo.SET); header.addSetInfo(set); // create the measurement infos for (int i = 0; i < options.input.size(); ++i) { String file = options.input.get(i); // create the measurement info MeasurementInfo measurement = new MeasurementInfo(i, data.get(i).header.getMeasurementInfo(0)); measurement.addFileInfo(new FileInfo(file, file)); header.addMeasurementInfo(measurement); // add the file to the set set.addChild(new SetInfo(file, SetInfo.SET, i)); } // write the data PeakMLWriter.write(header, (Vector) valids, null, new GZIPOutputStream(new FileOutputStream(options.selection)), null); } // correct the values with the found function and save them for (int i = 0; i < options.input.size(); ++i) { Function function = functions[i]; ParseResult result = data.get(i); IPeakSet<MassChromatogram<Peak>> peakset = (IPeakSet<MassChromatogram<Peak>>) result.measurement; for (IPeak peak : peakset) align(peak, function); File filename = new File(options.input.get(i)); String name = filename.getName(); PeakMLWriter.write(result.header, (Vector) peakset.getPeaks(), null, new GZIPOutputStream(new FileOutputStream(options.output + "/" + name)), null); } } catch (Exception e) { Tool.unexpectedError(e, application); } }
From source file:com.intuit.tank.harness.functions.JexlNumericFunctions.java
/** * Subtracts all values from the first value * /*from w ww .j a v a 2s . c o m*/ * @param values * @return subtraction of values */ public String subtract(Object... values) { double result = FunctionHandler.getDouble(values[0]); for (int i = 1; i < values.length; i++) { result -= FunctionHandler.getDouble(values[i]); } return Double.toString(result); }
From source file:org.openbaton.vnfm.api.RestMonitor.java
/** * Returns the consumed capacity of the requested MediaServer * * @param hostName : hostName of the MediaServer * @return consumed_capacity: Consumed Capacity of the MediaServer *//*from w ww. ja va 2 s .c o m*/ @RequestMapping(value = "CONSUMED_CAPACITY", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public String get(@PathVariable("hostname") String hostName) throws NotFoundException { MediaServer mediaServer = mediaServerManagement.queryByHostName(hostName); if (mediaServer == null) throw new NotFoundException("MediaServer with name " + hostName + " not found."); return Double.toString(mediaServer.getUsedPoints()); }
From source file:com.webnetmobile.tools.GoogleMapRouteHelper.java
public List<LatLng> getDirections() { if ((mPickup != null) || (mDropoff != null)) { HttpClient httpclient = new DefaultHttpClient(); StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append("http://maps.googleapis.com/maps/api/directions/json"); urlBuilder.append("?origin="); urlBuilder.append(Double.toString((double) mPickup.latitude)); urlBuilder.append(","); urlBuilder.append(Double.toString((double) mPickup.longitude)); urlBuilder.append("&destination="); urlBuilder.append(Double.toString((double) mDropoff.latitude)); urlBuilder.append(","); urlBuilder.append(Double.toString((double) mDropoff.longitude)); urlBuilder.append("&sensor=false&units=metric&mode=driving"); HttpPost httppost = new HttpPost(urlBuilder.toString()); HttpResponse response;/*from w ww. j a va2s. c o m*/ try { response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = null; is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); reader.close(); String result = sb.toString(); JSONObject jsonObject = new JSONObject(result); JSONArray routeArray = jsonObject.getJSONArray("routes"); if ((routeArray != null) && (routeArray.length() > 0)) { JSONObject routes = routeArray.getJSONObject(0); JSONObject overviewPolylines = routes.getJSONObject("overview_polyline"); String encodedString = overviewPolylines.getString("points"); mRoutePoints = decodePoly(encodedString); } else { mRoutePoints = null; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return mRoutePoints; } else { throw new NullPointerException("Pickup or Dropoff cannot be null."); } }
From source file:io.fabric8.example.stddev.msg.StdDevProcessor.java
@Override public void process(Exchange exchange) throws Exception { System.err.println("STD DEV GOT EXCHANGE " + exchange); String message = exchange.getIn().getBody(String.class); ObjectMapper objectMapper = new ObjectMapper(); TypeFactory typeFactory = objectMapper.getTypeFactory(); List<Double> values = objectMapper.readValue(message, typeFactory.constructCollectionType(List.class, Double.class)); SummaryStatistics summaryStatistics = new SummaryStatistics(); List<Double> list = new ObjectMapper().readValue(message, List.class); for (Double value : list) { summaryStatistics.addValue(value); }//from ww w .ja v a 2 s. c o m String stdDev = Double.toString(summaryStatistics.getStandardDeviation()); ActiveMQDestination replyTo = exchange.getIn().getHeader("JMSReplyTo", ActiveMQDestination.class); final String messageId = exchange.getIn().getHeader("JMSMessageID", String.class); if (replyTo != null) { Exchange copy = new DefaultExchange(exchange); copy.setPattern(ExchangePattern.InOnly); copy.getIn().setHeader(Variables.CORRELATION_HEADER, messageId); copy.getIn().setBody(stdDev); producerTemplate.send("jms:queue:" + replyTo.getPhysicalName(), copy); } }
From source file:com.github.tddts.jet.service.impl.UserDataServiceImpl.java
@Override public String getWalletsAmountAsString() { double sum = getWalletsAmount(); return sum == 0 ? "" : Double.toString(sum); }