List of usage examples for java.lang Double valueOf
@HotSpotIntrinsicCandidate public static Double valueOf(double d)
From source file:de.tudarmstadt.ukp.experiments.argumentation.clustering.entropy.MatrixExperiments.java
public static void main(String[] args) throws Exception { File in = new File(args[0]); List<String> lines = IOUtils.readLines(new FileInputStream(in)); int rows = lines.size(); int cols = lines.iterator().next().split("\\s+").length; double[][] matrix = new double[rows][cols]; Map<Integer, Double> clusterEntropy = new HashMap<>(); for (int i = 0; i < rows; i++) { String line = lines.get(i); String[] split = line.split("\\s+"); for (int j = 0; j < split.length; j++) { Double value = Double.valueOf(split[j]); matrix[i][j] = value;/*w w w . j av a 2 s.c o m*/ } // entropy of the cluster Vector v = new DenseVector(matrix[i]); // System.out.print(VectorUtils.entropy(v)); double entropy = VectorUtils.entropy(VectorUtils.normalize(v)); System.out.print(entropy); System.out.print(" "); clusterEntropy.put(i, entropy); } Map<Integer, Double> sorted = sortByValue(clusterEntropy); System.out.println(sorted); HeatChart map = new HeatChart(matrix); // Step 2: Customise the chart. map.setTitle("This is my heat chart title"); map.setXAxisLabel("X Axis"); map.setYAxisLabel("Y Axis"); // Step 3: Output the chart to a file. map.saveToFile(new File("/tmp/java-heat-chart.png")); }
From source file:de.tud.kom.p2psim.impl.overlay.dht.kademlia2.measurement.file.ConfidenceCalculator.java
/** * Calculates the mean, standard deviation and confidence interval for the * given arguments./*w w w. java2 s . c o m*/ * * @param args * a space-separated string containing an arbitrary number of * samples as the first argument. */ public static void main(String[] args) { String[] split = args;// args[0].split(" "); double[] sample = new double[split.length]; double[] result; System.out.print("Input: "); for (int i = 0; i < split.length; i++) { sample[i] = Double.valueOf(split[i]); System.out.print(split[i] + " "); } System.out.println('\n'); result = calc(sample, ALPHA); System.out.println("Mean: " + result[0]); System.out.println("Standard deviation: " + result[1]); System.out.println("Delta: " + result[2]); System.out.println("Interval: " + result[3] + " " + result[4]); }
From source file:FPAdder.java
public static void main(String[] args) { int numArgs = args.length; //this program requires at least two arguments on the command line if (numArgs < 2) { System.out.println("This program requires two command-line arguments."); } else {// w ww . jav a2 s . c o m double sum = 0.0; for (int i = 0; i < numArgs; i++) { sum += Double.valueOf(args[i]).doubleValue(); } //format the sum DecimalFormat myFormatter = new DecimalFormat("###,###.##"); String output = myFormatter.format(sum); //print the sum System.out.println(output); } }
From source file:name.wagners.fssp.Main.java
/** * @param args//w w w . j a v a 2 s. c om * command-line arguments */ public static void main(final String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("gn").withLongOpt("generations") .withDescription("Number of generations [default: 50]").withType(Integer.valueOf(0)).create("g")); options.addOption(OptionBuilder.hasArg().withArgName("mp").withLongOpt("mutation") .withDescription("Mutation propability [default: 0.5]").withType(Double.valueOf(0)).create("m")); options.addOption(OptionBuilder.hasArg().withArgName("ps").withLongOpt("populationsize") .withDescription("Size of population [default: 20]").withType(Integer.valueOf(0)).create("p")); options.addOption(OptionBuilder.hasArg().withArgName("rp").withLongOpt("recombination") .withDescription("Recombination propability [default: 0.8]").withType(Double.valueOf(0)) .create("r")); options.addOption(OptionBuilder.hasArg().withArgName("sp").withLongOpt("selectionpressure") .withDescription("Selection pressure [default: 4]").withType(Integer.valueOf(0)).create("s")); options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h")); options.addOption(OptionBuilder.hasArg().withArgName("filename").isRequired().withLongOpt("file") .withDescription("Problem file [default: \"\"]").withType(String.valueOf("")).create("f")); options.addOptionGroup(new OptionGroup() .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v")) .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q"))); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("print the version information and exit").create("V")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("h")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } } catch (MissingOptionException exp) { log.info("An option was missing:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (MissingArgumentException exp) { log.info("An argument was missing:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (AlreadySelectedException exp) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); } catch (ParseException exp) { log.info("Unexpected exception:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fssp", options); System.exit(1); } // Ausgabe der eingestellten Optionen log.info("Configuration"); // log.info(" Datafile: {}", fname); }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step2FillWithRetrievedResults.java
public static void main(String[] args) throws IOException { // input dir - list of xml query containers File inputDir = new File(args[0]); // retrieved results from Technion // ltr-50queries-100docs.txt File ltr = new File(args[1]); // output dir File outputDir = new File(args[2]); if (!outputDir.exists()) { outputDir.mkdirs();/*from w w w .j a va 2 s. c o m*/ } // load the query containers first (into map: id + container) Map<String, QueryResultContainer> queryResults = new HashMap<>(); for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { System.out.println(f); QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); queryResults.put(queryResultContainer.qID, queryResultContainer); } // iterate over IR results for (String line : FileUtils.readLines(ltr)) { String[] split = line.split("\\s+"); Integer origQueryId = Integer.valueOf(split[0]); String clueWebID = split[2]; Integer rank = Integer.valueOf(split[3]); double score = Double.valueOf(split[4]); String additionalInfo = split[5]; // get the container for this result QueryResultContainer container = queryResults.get(origQueryId.toString()); if (container != null) { // add new result QueryResultContainer.SingleRankedResult result = new QueryResultContainer.SingleRankedResult(); result.clueWebID = clueWebID; result.rank = rank; result.score = score; result.additionalInfo = additionalInfo; if (container.rankedResults == null) { container.rankedResults = new ArrayList<>(); } container.rankedResults.add(result); } } // save all containers to the output dir for (QueryResultContainer queryResultContainer : queryResults.values()) { File outputFile = new File(outputDir, queryResultContainer.qID + ".xml"); FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8"); System.out.println("Finished " + outputFile); } }
From source file:akori.AKORI.java
public static void main(String[] args) throws IOException, InterruptedException { System.out.println("esto es AKORI"); URL = "http://www.mbauchile.cl"; PATH = "E:\\NetBeansProjects\\AKORI\\"; NAME = "mbauchile.png"; // Extrar DOM tree Document doc = Jsoup.connect(URL).timeout(0).get(); // The Firefox driver supports javascript WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println(driver.manage().window().getSize().toString()); System.out.println(driver.manage().window().getPosition().toString()); int xmax = driver.manage().window().getSize().width; int ymax = driver.manage().window().getSize().height; // Go to the URL page driver.get(URL);//from ww w .jav a 2s. c om File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screen, new File(PATH + NAME)); BufferedImage img = ImageIO.read(new File(PATH + NAME)); //Graphics2D graph = img.createGraphics(); BufferedImage img1 = new BufferedImage(xmax, ymax, BufferedImage.TYPE_INT_ARGB); Graphics2D graph1 = img.createGraphics(); double[][] matrix = new double[ymax][xmax]; BufferedReader in = new BufferedReader(new FileReader("et.txt")); String linea; double max = 0; graph1.drawImage(img, 0, 0, null); HashMap<String, Integer> lista = new HashMap<String, Integer>(); int count = 0; for (int i = 0; (linea = in.readLine()) != null && i < 10000; ++i) { String[] datos = linea.split(","); int x = (int) Double.parseDouble(datos[0]); int y = (int) Double.parseDouble(datos[2]); long time = Double.valueOf(datos[4]).longValue(); if (x >= xmax || y >= ymax) continue; if (time < 691215) continue; if (time > 705648) break; if (lista.containsKey(x + "," + y)) lista.put(x + "," + y, lista.get(x + "," + y) + 1); else lista.put(x + "," + y, 1); ++count; } System.out.println(count); in.close(); Iterator iter = lista.entrySet().iterator(); Map.Entry e; for (String key : lista.keySet()) { Integer i = lista.get(key); if (max < i) max = i; } System.out.println(max); max = 0; while (iter.hasNext()) { e = (Map.Entry) iter.next(); String xy = (String) e.getKey(); String[] datos = xy.split(","); int x = Integer.parseInt(datos[0]); int y = Integer.parseInt(datos[1]); matrix[y][x] += (int) e.getValue(); double aux; if ((aux = normalMatrix(matrix, y, x, ((int) e.getValue()) * 4)) > max) { max = aux; } //normalMatrix(matrix,x,y,20); if (matrix[y][x] > max) max = matrix[y][x]; } int A, R, G, B, n; for (int i = 0; i < xmax; ++i) { for (int j = 0; j < ymax; ++j) { if (matrix[j][i] != 0) { n = (int) Math.round(matrix[j][i] * 100 / max); R = Math.round((255 * n) / 100); G = Math.round((255 * (100 - n)) / 100); B = 0; A = Math.round((255 * n) / 100); ; if (R > 255) R = 255; if (R < 0) R = 0; if (G > 255) G = 255; if (G < 0) G = 0; if (R < 50) A = 0; graph1.setColor(new Color(R, G, B, A)); graph1.fillOval(i, j, 1, 1); } } } //graph1.dispose(); ImageIO.write(img, "png", new File("example.png")); System.out.println(max); graph1.setColor(Color.RED); // Extraer elementos Elements e1 = doc.body().getAllElements(); int i = 1; ArrayList<String> tags = new ArrayList<String>(); for (Element temp : e1) { if (tags.indexOf(temp.tagName()) == -1) { tags.add(temp.tagName()); List<WebElement> query = driver.findElements(By.tagName(temp.tagName())); for (WebElement temp1 : query) { Point po = temp1.getLocation(); Dimension d = temp1.getSize(); if (d.width <= 0 || d.height <= 0 || po.x < 0 || po.y < 0) continue; System.out.println(i + " " + temp.nodeName()); System.out.println(" x: " + po.x + " y: " + po.y); System.out.println(" width: " + d.width + " height: " + d.height); graph1.draw(new Rectangle(po.x, po.y, d.width, d.height)); ++i; } } } graph1.dispose(); ImageIO.write(img, "png", new File(PATH + NAME)); driver.quit(); }
From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java
public static void main(final String[] args) throws Exception { // 1. check input directory final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports"); if (!reportdir.isDirectory()) { throw new IllegalArgumentException("Expected directory, got " + args[0]); }//from w w w. ja v a 2 s . c om // 2. read test data from surefire output final File[] xmlReports = reportdir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.endsWith("-output.txt"); } }); final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>(); for (File xmlReport : xmlReports) { final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport)); try { while (reportReader.ready()) { String line = reportReader.readLine(); final String[] parts = line.substring(0, line.indexOf(':')).split("\\."); final String testClass = parts[0]; if (!testData.containsKey(testClass)) { testData.put(testClass, new TreeMap<String, Double>()); } line = reportReader.readLine(); testData.get(testClass).put(parts[1], Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('[')))); } } finally { IOUtils.closeQuietly(reportReader); } } // 3. build XSLX output (from template) final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + XLS)); for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) { final Sheet sheet = workbook.getSheet(entry.getKey()); int rows = 0; for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) { final Row row = sheet.createRow(rows++); Cell cell = row.createCell(0); cell.setCellValue(subentry.getKey()); cell = row.createCell(1); cell.setCellValue(subentry.getValue()); } } final FileOutputStream out = new FileOutputStream( args[0] + File.separator + "target" + File.separator + XLS); try { workbook.write(out); } finally { IOUtils.closeQuietly(out); } }
From source file:com.stratio.decision.executables.DataFlowFromCsvMain.java
public static void main(String[] args) throws IOException, NumberFormatException, InterruptedException { if (args.length < 4) { log.info(//from w w w. j a v a2 s . c o m "Usage: \n param 1 - path to file \n param 2 - stream name to send the data \n param 3 - time in ms to wait to send each data \n param 4 - broker list"); } else { Producer<String, String> producer = new Producer<String, String>(createProducerConfig(args[3])); Gson gson = new Gson(); Reader in = new FileReader(args[0]); CSVParser parser = CSVFormat.DEFAULT.parse(in); List<String> columnNames = new ArrayList<>(); for (CSVRecord csvRecord : parser.getRecords()) { if (columnNames.size() == 0) { Iterator<String> iterator = csvRecord.iterator(); while (iterator.hasNext()) { columnNames.add(iterator.next()); } } else { StratioStreamingMessage message = new StratioStreamingMessage(); message.setOperation(STREAM_OPERATIONS.MANIPULATION.INSERT.toLowerCase()); message.setStreamName(args[1]); message.setTimestamp(System.currentTimeMillis()); message.setSession_id(String.valueOf(System.currentTimeMillis())); message.setRequest_id(String.valueOf(System.currentTimeMillis())); message.setRequest("dummy request"); List<ColumnNameTypeValue> sensorData = new ArrayList<>(); for (int i = 0; i < columnNames.size(); i++) { // Workaround Object value = null; try { value = Double.valueOf(csvRecord.get(i)); } catch (NumberFormatException e) { value = csvRecord.get(i); } sensorData.add(new ColumnNameTypeValue(columnNames.get(i), null, value)); } message.setColumns(sensorData); String json = gson.toJson(message); log.info("Sending data: {}", json); producer.send(new KeyedMessage<String, String>(InternalTopic.TOPIC_DATA.getTopicName(), STREAM_OPERATIONS.MANIPULATION.INSERT, json)); log.info("Sleeping {} ms...", args[2]); Thread.sleep(Long.valueOf(args[2])); } } log.info("Program completed."); } }
From source file:examples.cnn.cifar.Cifar10Classification.java
public static void main(String[] args) { CifarReader.downloadAndExtract();/*from w w w .ja v a2 s . c om*/ int numLabels = 10; SparkConf conf = new SparkConf(); conf.setMaster(String.format("local[%d]", NUM_CORES)); conf.setAppName("Cifar-10 CNN Classification"); conf.set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(true)); try (JavaSparkContext sc = new JavaSparkContext(conf)) { NetworkTrainer trainer = new NetworkTrainer.Builder().model(ModelLibrary.net2) .networkToSparkNetwork(net -> new SparkDl4jMultiLayer(sc, net)).numLabels(numLabels) .cores(NUM_CORES).build(); JavaPairRDD<String, PortableDataStream> files = sc.binaryFiles("data/cifar-10-batches-bin"); JavaRDD<double[]> imagesTrain = files .filter(f -> ArrayUtils.contains(CifarReader.TRAIN_DATA_FILES, extractFileName.apply(f._1))) .flatMap(f -> CifarReader.rawDouble(f._2.open())); JavaRDD<double[]> imagesTest = files .filter(f -> CifarReader.TEST_DATA_FILE.equals(extractFileName.apply(f._1))) .flatMap(f -> CifarReader.rawDouble(f._2.open())); JavaRDD<DataSet> testDataset = imagesTest.map(i -> { INDArray label = FeatureUtil.toOutcomeVector(Double.valueOf(i[0]).intValue(), numLabels); double[] arr = Arrays.stream(ArrayUtils.remove(i, 0)).boxed().map(normalize2) .mapToDouble(Double::doubleValue).toArray(); INDArray features = Nd4j.create(arr, new int[] { 1, arr.length }); return new DataSet(features, label); }).cache(); log.info("Number of test images {}", testDataset.count()); JavaPairRDD<INDArray, double[]> labelsWithDataTrain = imagesTrain.mapToPair(i -> { INDArray label = FeatureUtil.toOutcomeVector(Double.valueOf(i[0]).intValue(), numLabels); double[] arr = Arrays.stream(ArrayUtils.remove(i, 0)).boxed().map(normalize2) .mapToDouble(Double::doubleValue).toArray(); return new Tuple2<>(label, arr); }); JavaRDD<DataSet> flipped = labelsWithDataTrain.map(t -> { double[] arr = t._2; int idx = 0; double[] farr = new double[arr.length]; for (int i = 0; i < arr.length; i += trainer.getWidth()) { double[] temp = Arrays.copyOfRange(arr, i, i + trainer.getWidth()); ArrayUtils.reverse(temp); for (int j = 0; j < trainer.getHeight(); ++j) { farr[idx++] = temp[j]; } } INDArray features = Nd4j.create(farr, new int[] { 1, farr.length }); return new DataSet(features, t._1); }); JavaRDD<DataSet> trainDataset = labelsWithDataTrain.map(t -> { INDArray features = Nd4j.create(t._2, new int[] { 1, t._2.length }); return new DataSet(features, t._1); }).union(flipped).cache(); log.info("Number of train images {}", trainDataset.count()); trainer.train(trainDataset, testDataset); } }
From source file:test.jackson.JacksonNsgiDiscover.java
public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE))); DiscoveryContextAvailabilityRequest dcar = objectMapper.readValue(ngsiRcr, DiscoveryContextAvailabilityRequest.class); // System.out.println(objectMapper.writeValueAsString(dcar)); System.out.println(dcar.getRestriction().getOperationScope().get(1).getScopeValue()); LinkedHashMap shapeHMap = (LinkedHashMap) dcar.getRestriction().getOperationScope().get(1).getScopeValue(); // Association assocObject = objectMapper.convertValue(shapeHMap, Association.class); // System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute()); Shape shape = objectMapper.convertValue(shapeHMap, Shape.class); System.out.println("Deserialized Class: " + shape.getClass().getSimpleName()); System.out.println("VALUE: " + shape.getPolygon().getVertices().get(2).getLatitude()); System.out.println("VALUE: " + shape.getCircle()); if (!(shape.getCircle() == null)) System.out.println("This is null"); Polygon polygon = shape.getPolygon(); int vertexSize = polygon.getVertices().size(); Coordinate[] coords = new Coordinate[vertexSize]; final ArrayList<Coordinate> points = new ArrayList<>(); for (int i = 0; i < vertexSize; i++) { Vertex vertex = polygon.getVertices().get(i); points.add(new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude()))); coords[i] = new Coordinate(Double.valueOf(vertex.getLatitude()), Double.valueOf(vertex.getLongitude())); }//from www .ja v a 2 s. c o m points.add(new Coordinate(Double.valueOf(polygon.getVertices().get(0).getLatitude()), Double.valueOf(polygon.getVertices().get(0).getLongitude()))); final GeometryFactory gf = new GeometryFactory(); final Coordinate target = new Coordinate(49, -0.6); final Point point = gf.createPoint(target); Geometry shapeGm = gf.createPolygon( new LinearRing(new CoordinateArraySequence(points.toArray(new Coordinate[points.size()])), gf), null); // Geometry shapeGm = gf.createPolygon(coords); System.out.println(point.within(shapeGm)); // System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName()); // String assocJson = objectMapper.writeValueAsString(association); // Value assocObject = objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class); // System.out.println(association.values().toString()); // System.out.println(assocJson); }