List of usage examples for java.text DecimalFormat DecimalFormat
public DecimalFormat(String pattern)
From source file:hyperheuristics.main.comparisons.ComputeIndicators.java
public static void main(String[] args) throws IOException, InterruptedException { int[] numberOfObjectivesArray = new int[] { 2, 4 }; String[] problems = new String[] { "OO_MyBatis", "OA_AJHsqldb", "OA_AJHotDraw", "OO_BCEL", "OO_JHotDraw", "OA_HealthWatcher", // "OA_TollSystems", "OO_JBoss" }; String[] heuristicFunctions = new String[] { LowLevelHeuristic.CHOICE_FUNCTION, LowLevelHeuristic.MULTI_ARMED_BANDIT, LowLevelHeuristic.RANDOM }; String[] algorithms = new String[] { "NSGA-II", // "SPEA2" };/*from w ww .ja va 2 s. c o m*/ MetricsUtil metricsUtil = new MetricsUtil(); DecimalFormat decimalFormatter = new DecimalFormat("0.00E0"); Mean mean = new Mean(); StandardDeviation standardDeviation = new StandardDeviation(); InvertedGenerationalDistance igd = new InvertedGenerationalDistance(); GenerationalDistance gd = new GenerationalDistance(); Spread spread = new Spread(); Coverage coverage = new Coverage(); for (int objectives : numberOfObjectivesArray) { try (FileWriter IGDWriter = new FileWriter("experiment/IGD_" + objectives + ".tex"); FileWriter spreadWriter = new FileWriter("experiment/SPREAD_" + objectives + ".tex"); FileWriter GDWriter = new FileWriter("experiment/GD_" + objectives + ".tex"); FileWriter coverageWriter = new FileWriter("experiment/COVERAGE_" + objectives + ".tex")) { StringBuilder latexTableBuilder = new StringBuilder(); latexTableBuilder.append("\\documentclass{paper}\n").append("\n") .append("\\usepackage[T1]{fontenc}\n").append("\\usepackage[latin1]{inputenc}\n") .append("\\usepackage[hidelinks]{hyperref}\n").append("\\usepackage{tabulary}\n") .append("\\usepackage{booktabs}\n").append("\\usepackage{multirow}\n") .append("\\usepackage{amsmath}\n").append("\\usepackage{mathtools}\n") .append("\\usepackage{graphicx}\n").append("\\usepackage{array}\n") .append("\\usepackage[linesnumbered,ruled,inoutnumbered]{algorithm2e}\n") .append("\\usepackage{subfigure}\n").append("\\usepackage[hypcap]{caption}\n") .append("\\usepackage{pdflscape}\n").append("\n").append("\\begin{document}\n").append("\n") .append("\\begin{landscape}\n").append("\n"); pfKnown: { latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n") .append("\t\\def\\arraystretch{1.5}\n") // .append("\t\\setlength{\\tabcolsep}{10pt}\n") // .append("\t\\fontsize{8pt}{10pt}\\selectfont\n") .append("\t\\caption{INDICATOR found for $PF_{known}$ for ").append(objectives) .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives) .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c"); for (String algorithm : algorithms) { latexTableBuilder.append("c"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append("c"); } } latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}"); for (String algorithm : algorithms) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-") .append(heuristicFunction).append("}"); } } latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n"); for (String problem : problems) { NonDominatedSolutionList trueFront = new NonDominatedSolutionList(); pfTrueComposing: { for (String algorithm : algorithms) { SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet( "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); trueFront.addAll(mecbaFront); for (String hyperHeuristic : heuristicFunctions) { SolutionSet front = metricsUtil.readNonDominatedSolutionSet( "experiment/" + algorithm + "/" + objectives + "objectives/" + hyperHeuristic + "/" + problem + "/FUN.txt"); trueFront.addAll(front); } } } double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix(); HashMap<String, Double> igdMap = new HashMap<>(); HashMap<String, Double> gdMap = new HashMap<>(); HashMap<String, Double> spreadMap = new HashMap<>(); HashMap<String, Double> coverageMap = new HashMap<>(); for (String algorithm : algorithms) { double[][] mecbaFront = metricsUtil .readFront("resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); igdMap.put(algorithm, igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix, objectives)); gdMap.put(algorithm, gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives)); spreadMap.put(algorithm, spread.spread(mecbaFront, trueFrontMatrix, objectives)); coverageMap.put(algorithm, coverage.coverage(mecbaFront, trueFrontMatrix)); for (String heuristic : heuristicFunctions) { double[][] heuristicFront = metricsUtil.readFront("experiment/" + algorithm + "/" + objectives + "objectives/" + heuristic + "/" + problem + "/FUN.txt"); igdMap.put(algorithm + "-" + heuristic, igd .invertedGenerationalDistance(heuristicFront, trueFrontMatrix, objectives)); gdMap.put(algorithm + "-" + heuristic, gd.generationalDistance(heuristicFront, trueFrontMatrix, objectives)); spreadMap.put(algorithm + "-" + heuristic, spread.spread(heuristicFront, trueFrontMatrix, objectives)); coverageMap.put(algorithm + "-" + heuristic, coverage.coverage(heuristicFront, trueFrontMatrix)); } } latexTableBuilder.append("\t\t").append(problem); String latexTable = latexTableBuilder.toString(); latexTableBuilder = new StringBuilder(); latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF") .replaceAll("MultiArmedBandit", "MAB"); IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD")); spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread")); GDWriter.write(latexTable.replaceAll("INDICATOR", "GD")); coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage")); String bestHeuristicIGD = "NULL"; String bestHeuristicGD = "NULL"; String bestHeuristicSpread = "NULL"; String bestHeuristicCoverage = "NULL"; getBest: { double bestMeanIGD = Double.POSITIVE_INFINITY; double bestMeanGD = Double.POSITIVE_INFINITY; double bestMeanSpread = Double.NEGATIVE_INFINITY; double bestMeanCoverage = Double.NEGATIVE_INFINITY; for (String heuristic : igdMap.keySet()) { double heuristicIGD = igdMap.get(heuristic); double heuristicGD = gdMap.get(heuristic); double heuristicSpread = spreadMap.get(heuristic); double heuristicCoverage = coverageMap.get(heuristic); if (heuristicIGD < bestMeanIGD) { bestMeanIGD = heuristicIGD; bestHeuristicIGD = heuristic; } if (heuristicGD < bestMeanGD) { bestMeanGD = heuristicGD; bestHeuristicGD = heuristic; } if (heuristicSpread > bestMeanSpread) { bestMeanSpread = heuristicSpread; bestHeuristicSpread = heuristic; } if (heuristicCoverage > bestMeanCoverage) { bestMeanCoverage = heuristicCoverage; bestHeuristicCoverage = heuristic; } } } StringBuilder igdBuilder = new StringBuilder(); StringBuilder gdBuilder = new StringBuilder(); StringBuilder spreadBuilder = new StringBuilder(); StringBuilder coverageBuilder = new StringBuilder(); String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length + algorithms.length]; fulfillNewHeuristics: { int i = 0; for (String algorithm : algorithms) { newHeuristicFunctions[i++] = algorithm; for (String heuristicFunction : heuristicFunctions) { newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction; } } } for (String heuristic : newHeuristicFunctions) { igdBuilder.append(" & "); boolean bold = heuristic.equals(bestHeuristicIGD) || igdMap.get(heuristic).equals(igdMap.get(bestHeuristicIGD)); if (bold) { igdBuilder.append("\\textbf{"); } igdBuilder.append(decimalFormatter.format(igdMap.get(heuristic))); if (bold) { igdBuilder.append("}"); } gdBuilder.append(" & "); bold = heuristic.equals(bestHeuristicGD) || gdMap.get(heuristic).equals(gdMap.get(bestHeuristicGD)); if (bold) { gdBuilder.append("\\textbf{"); } gdBuilder.append(decimalFormatter.format(gdMap.get(heuristic))); if (bold) { gdBuilder.append("}"); } spreadBuilder.append(" & "); bold = heuristic.equals(bestHeuristicSpread) || spreadMap.get(heuristic).equals(spreadMap.get(bestHeuristicSpread)); if (bold) { spreadBuilder.append("\\textbf{"); } spreadBuilder.append(decimalFormatter.format(spreadMap.get(heuristic))); if (bold) { spreadBuilder.append("}"); } coverageBuilder.append(" & "); bold = heuristic.equals(bestHeuristicCoverage) || coverageMap.get(heuristic).equals(coverageMap.get(bestHeuristicCoverage)); if (bold) { coverageBuilder.append("\\textbf{"); } coverageBuilder.append(decimalFormatter.format(coverageMap.get(heuristic))); if (bold) { coverageBuilder.append("}"); } } IGDWriter.write(igdBuilder + "\\\\\n"); spreadWriter.write(spreadBuilder + "\\\\\n"); GDWriter.write(gdBuilder + "\\\\\n"); coverageWriter.write(coverageBuilder + "\\\\\n"); } latexTableBuilder = new StringBuilder(); latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n") .append("\\end{table}\n\n"); } averages: { latexTableBuilder.append("\\begin{table}[!htb]\n").append("\t\\centering\n") .append("\t\\def\\arraystretch{1.5}\n") // .append("\t\\setlength{\\tabcolsep}{10pt}\n") // .append("\t\\fontsize{8pt}{10pt}\\selectfont\n") .append("\t\\caption{INDICATOR averages found for ").append(objectives) .append(" objectives}\n").append("\t\\label{tab:INDICATOR ").append(objectives) .append(" objectives}\n").append("\t\\begin{tabulary}{\\linewidth}{c"); for (String algorithm : algorithms) { latexTableBuilder.append("c"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append("c"); } } latexTableBuilder.append("}\n").append("\t\t\\toprule\n").append("\t\t\\textbf{System}"); for (String algorithm : algorithms) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("}"); for (String heuristicFunction : heuristicFunctions) { latexTableBuilder.append(" & \\textbf{").append(algorithm).append("-") .append(heuristicFunction).append("}"); } } latexTableBuilder.append("\\\\\n").append("\t\t\\midrule\n"); for (String problem : problems) { NonDominatedSolutionList trueFront = new NonDominatedSolutionList(); pfTrueComposing: { for (String algorithm : algorithms) { SolutionSet mecbaFront = metricsUtil.readNonDominatedSolutionSet( "resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/All_FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem); trueFront.addAll(mecbaFront); for (String hyperHeuristic : heuristicFunctions) { SolutionSet front = metricsUtil.readNonDominatedSolutionSet( "experiment/" + algorithm + "/" + objectives + "objectives/" + hyperHeuristic + "/" + problem + "/FUN.txt"); trueFront.addAll(front); } } } double[][] trueFrontMatrix = trueFront.writeObjectivesToMatrix(); HashMap<String, double[]> igdMap = new HashMap<>(); HashMap<String, double[]> gdMap = new HashMap<>(); HashMap<String, double[]> spreadMap = new HashMap<>(); HashMap<String, double[]> coverageMap = new HashMap<>(); mocaito: { for (String algorithm : algorithms) { double[] mecbaIGDs = new double[EXECUTIONS]; double[] mecbaGDs = new double[EXECUTIONS]; double[] mecbaSpreads = new double[EXECUTIONS]; double[] mecbaCoverages = new double[EXECUTIONS]; for (int i = 0; i < EXECUTIONS; i++) { double[][] mecbaFront = metricsUtil.readFront("resultado/" + algorithm.toLowerCase().replaceAll("-", "") + "/" + problem + "_Comb_" + objectives + "obj/FUN_" + algorithm.toLowerCase().replaceAll("-", "") + "-" + problem + "-" + i + ".NaoDominadas"); mecbaIGDs[i] = igd.invertedGenerationalDistance(mecbaFront, trueFrontMatrix, objectives); mecbaGDs[i] = gd.generationalDistance(mecbaFront, trueFrontMatrix, objectives); mecbaSpreads[i] = spread.spread(mecbaFront, trueFrontMatrix, objectives); mecbaCoverages[i] = coverage.coverage(mecbaFront, trueFrontMatrix); } igdMap.put(algorithm, mecbaIGDs); gdMap.put(algorithm, mecbaGDs); spreadMap.put(algorithm, mecbaSpreads); coverageMap.put(algorithm, mecbaCoverages); } } for (String algorithm : algorithms) { for (String heuristic : heuristicFunctions) { double[] hhIGDs = new double[EXECUTIONS]; double[] hhGDs = new double[EXECUTIONS]; double[] hhSpreads = new double[EXECUTIONS]; double[] hhCoverages = new double[EXECUTIONS]; for (int i = 0; i < EXECUTIONS; i++) { double[][] hhFront = metricsUtil .readFront("experiment/" + algorithm + "/" + objectives + "objectives/" + heuristic + "/" + problem + "/EXECUTION_" + i + "/FUN.txt"); hhIGDs[i] = igd.invertedGenerationalDistance(hhFront, trueFrontMatrix, objectives); hhGDs[i] = gd.generationalDistance(hhFront, trueFrontMatrix, objectives); hhSpreads[i] = spread.spread(hhFront, trueFrontMatrix, objectives); hhCoverages[i] = coverage.coverage(hhFront, trueFrontMatrix); } igdMap.put(algorithm + "-" + heuristic, hhIGDs); gdMap.put(algorithm + "-" + heuristic, hhGDs); spreadMap.put(algorithm + "-" + heuristic, hhSpreads); coverageMap.put(algorithm + "-" + heuristic, hhCoverages); } } HashMap<String, HashMap<String, Boolean>> igdResult = KruskalWallisTest.test(igdMap); HashMap<String, HashMap<String, Boolean>> gdResult = KruskalWallisTest.test(gdMap); HashMap<String, HashMap<String, Boolean>> spreadResult = KruskalWallisTest.test(spreadMap); HashMap<String, HashMap<String, Boolean>> coverageResult = KruskalWallisTest .test(coverageMap); latexTableBuilder.append("\t\t").append(problem); String latexTable = latexTableBuilder.toString(); latexTable = latexTable.replaceAll("O[OA]\\_", "").replaceAll("ChoiceFunction", "CF") .replaceAll("MultiArmedBandit", "MAB"); IGDWriter.write(latexTable.replaceAll("INDICATOR", "IGD")); spreadWriter.write(latexTable.replaceAll("INDICATOR", "Spread")); GDWriter.write(latexTable.replaceAll("INDICATOR", "GD")); coverageWriter.write(latexTable.replaceAll("INDICATOR", "Coverage")); latexTableBuilder = new StringBuilder(); String bestHeuristicIGD = "NULL"; String bestHeuristicGD = "NULL"; String bestHeuristicSpread = "NULL"; String bestHeuristicCoverage = "NULL"; getBest: { double bestMeanIGD = Double.POSITIVE_INFINITY; double bestMeanGD = Double.POSITIVE_INFINITY; double bestMeanSpread = Double.NEGATIVE_INFINITY; double bestMeanCoverage = Double.NEGATIVE_INFINITY; for (String heuristic : igdMap.keySet()) { double heuristicMeanIGD = mean.evaluate(igdMap.get(heuristic)); double heuristicMeanGD = mean.evaluate(gdMap.get(heuristic)); double heuristicMeanSpread = mean.evaluate(spreadMap.get(heuristic)); double heuristicMeanCoverage = mean.evaluate(coverageMap.get(heuristic)); if (heuristicMeanIGD < bestMeanIGD) { bestMeanIGD = heuristicMeanIGD; bestHeuristicIGD = heuristic; } if (heuristicMeanGD < bestMeanGD) { bestMeanGD = heuristicMeanGD; bestHeuristicGD = heuristic; } if (heuristicMeanSpread > bestMeanSpread) { bestMeanSpread = heuristicMeanSpread; bestHeuristicSpread = heuristic; } if (heuristicMeanCoverage > bestMeanCoverage) { bestMeanCoverage = heuristicMeanCoverage; bestHeuristicCoverage = heuristic; } } } StringBuilder igdBuilder = new StringBuilder(); StringBuilder gdBuilder = new StringBuilder(); StringBuilder spreadBuilder = new StringBuilder(); StringBuilder coverageBuilder = new StringBuilder(); String[] newHeuristicFunctions = new String[heuristicFunctions.length * algorithms.length + algorithms.length]; fulfillNewHeuristics: { int i = 0; for (String algorithm : algorithms) { newHeuristicFunctions[i++] = algorithm; for (String heuristicFunction : heuristicFunctions) { newHeuristicFunctions[i++] = algorithm + "-" + heuristicFunction; } } } for (String heuristic : newHeuristicFunctions) { igdBuilder.append(" & "); boolean bold = heuristic.equals(bestHeuristicIGD) || !igdResult.get(heuristic).get(bestHeuristicIGD); if (bold) { igdBuilder.append("\\textbf{"); } igdBuilder.append(decimalFormatter.format(mean.evaluate(igdMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(igdMap.get(heuristic))) + ")"); if (bold) { igdBuilder.append("}"); } gdBuilder.append(" & "); bold = heuristic.equals(bestHeuristicGD) || !gdResult.get(heuristic).get(bestHeuristicGD); if (bold) { gdBuilder.append("\\textbf{"); } gdBuilder.append(decimalFormatter.format(mean.evaluate(gdMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(gdMap.get(heuristic))) + ")"); if (bold) { gdBuilder.append("}"); } spreadBuilder.append(" & "); bold = heuristic.equals(bestHeuristicSpread) || !spreadResult.get(heuristic).get(bestHeuristicSpread); if (bold) { spreadBuilder.append("\\textbf{"); } spreadBuilder.append(decimalFormatter.format(mean.evaluate(spreadMap.get(heuristic))) + " (" + decimalFormatter.format(standardDeviation.evaluate(spreadMap.get(heuristic))) + ")"); if (bold) { spreadBuilder.append("}"); } coverageBuilder.append(" & "); bold = heuristic.equals(bestHeuristicCoverage) || !coverageResult.get(heuristic).get(bestHeuristicCoverage); if (bold) { coverageBuilder.append("\\textbf{"); } coverageBuilder .append(decimalFormatter.format(mean.evaluate(coverageMap.get(heuristic)))) .append(" (") .append(decimalFormatter .format(standardDeviation.evaluate(coverageMap.get(heuristic)))) .append(")"); if (bold) { coverageBuilder.append("}"); } } IGDWriter.write(igdBuilder + "\\\\\n"); spreadWriter.write(spreadBuilder + "\\\\\n"); GDWriter.write(gdBuilder + "\\\\\n"); coverageWriter.write(coverageBuilder + "\\\\\n"); } latexTableBuilder.append("\t\t\\bottomrule\n").append("\t\\end{tabulary}\n") .append("\\end{table}\n\n"); } latexTableBuilder.append("\\end{landscape}\n\n").append("\\end{document}"); String latexTable = latexTableBuilder.toString(); IGDWriter.write(latexTable); spreadWriter.write(latexTable); GDWriter.write(latexTable); coverageWriter.write(latexTable); } } }
From source file:es.upm.oeg.tools.rdfshapes.utils.CadinalityResultGenerator.java
public static void main(String[] args) throws Exception { String endpoint = "http://3cixty.eurecom.fr/sparql"; List<String> classList = Files.readAllLines(Paths.get(classListPath), Charset.defaultCharset()); String classPropertyQueryString = readFile(classPropertyQueryPath, Charset.defaultCharset()); String propertyCardinalityQueryString = readFile(propertyCardinalityQueryPath, Charset.defaultCharset()); String individualCountQueryString = readFile(individualCountQueryPath, Charset.defaultCharset()); DecimalFormat df = new DecimalFormat("0.0000"); //Create the Excel workbook and sheet XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("Cardinality"); int currentExcelRow = 0; int classStartRow = 0; for (String clazz : classList) { Map<String, String> litMap = new HashMap<>(); Map<String, String> iriMap = ImmutableMap.of("class", clazz); String queryString = bindQueryString(individualCountQueryString, ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap)); int individualCount; List<RDFNode> c = executeQueryForList(queryString, endpoint, "c"); if (c.size() == 1) { individualCount = c.get(0).asLiteral().getInt(); } else {/* w ww .j a v a 2 s . c o m*/ continue; } // If there are zero individuals, continue if (individualCount == 0) { throw new IllegalStateException("Check whether " + classListPath + " and " + endpoint + " match."); } // System.out.println("***"); // System.out.println("### **" + clazz + "** (" + individualCount + ")"); // System.out.println("***"); // System.out.println(); classStartRow = currentExcelRow; XSSFRow row = sheet.createRow(currentExcelRow); XSSFCell cell = row.createCell(0); cell.setCellValue(clazz); cell.getCellStyle().setAlignment(CellStyle.ALIGN_CENTER); queryString = bindQueryString(classPropertyQueryString, ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap)); List<RDFNode> nodeList = executeQueryForList(queryString, endpoint, "p"); for (RDFNode property : nodeList) { if (property.isURIResource()) { DescriptiveStatistics stats = new DescriptiveStatistics(); String propertyURI = property.asResource().getURI(); // System.out.println("* " + propertyURI); // System.out.println(); XSSFRow propertyRow = sheet.getRow(currentExcelRow); if (propertyRow == null) { propertyRow = sheet.createRow(currentExcelRow); } currentExcelRow++; XSSFCell propertyCell = propertyRow.createCell(1); propertyCell.setCellValue(propertyURI); Map<String, String> litMap2 = new HashMap<>(); Map<String, String> iriMap2 = ImmutableMap.of("class", clazz, "p", propertyURI); queryString = bindQueryString(propertyCardinalityQueryString, ImmutableMap.of(IRI_BINDINGS, iriMap2, LITERAL_BINDINGS, litMap2)); List<Map<String, RDFNode>> solnMaps = executeQueryForList(queryString, endpoint, ImmutableSet.of("card", "count")); int sum = 0; List<CardinalityCount> cardinalityList = new ArrayList<>(); if (solnMaps.size() > 0) { for (Map<String, RDFNode> soln : solnMaps) { int count = soln.get("count").asLiteral().getInt(); int card = soln.get("card").asLiteral().getInt(); for (int i = 0; i < count; i++) { stats.addValue(card); } CardinalityCount cardinalityCount = new CardinalityCount(card, count, (((double) count) / individualCount) * 100); cardinalityList.add(cardinalityCount); sum += count; } // Check for zero cardinality instances int count = individualCount - sum; if (count > 0) { for (int i = 0; i < count; i++) { stats.addValue(0); } CardinalityCount cardinalityCount = new CardinalityCount(0, count, (((double) count) / individualCount) * 100); cardinalityList.add(cardinalityCount); } } Map<Integer, Double> cardMap = new HashMap<>(); for (CardinalityCount count : cardinalityList) { cardMap.put(count.getCardinality(), count.getPrecentage()); } XSSFCell instanceCountCell = propertyRow.createCell(2); instanceCountCell.setCellValue(individualCount); XSSFCell minCell = propertyRow.createCell(3); minCell.setCellValue(stats.getMin()); XSSFCell maxCell = propertyRow.createCell(4); maxCell.setCellValue(stats.getMax()); XSSFCell p1 = propertyRow.createCell(5); p1.setCellValue(stats.getPercentile(1)); XSSFCell p99 = propertyRow.createCell(6); p99.setCellValue(stats.getPercentile(99)); XSSFCell mean = propertyRow.createCell(7); mean.setCellValue(df.format(stats.getMean())); for (int i = 0; i < 21; i++) { XSSFCell dataCell = propertyRow.createCell(8 + i); Double percentage = cardMap.get(i); if (percentage != null) { dataCell.setCellValue(df.format(percentage)); } else { dataCell.setCellValue(0); } } // System.out.println("| Min Card. |Max Card. |"); // System.out.println("|---|---|"); // System.out.println("| ? | ? |"); // System.out.println(); } } //System.out.println("class start: " + classStartRow + ", class end: " + (currentExcelRow -1)); //We have finished writting properties of one class, now it's time to merge the cells int classEndRow = currentExcelRow - 1; if (classStartRow < classEndRow) { sheet.addMergedRegion(new CellRangeAddress(classStartRow, classEndRow, 0, 0)); } } String filename = "3cixty.xls"; FileOutputStream fileOut = new FileOutputStream(filename); wb.write(fileOut); fileOut.close(); }
From source file:NumericTextField.java
public static void main(String[] args) { try {/* ww w . j av a 2s . c o m*/ UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception evt) { } DecimalFormat format = new DecimalFormat("#,###.###"); format.setGroupingUsed(true); format.setGroupingSize(3); format.setParseIntegerOnly(false); JFrame f = new JFrame("Numeric Text Field Example"); final NumericTextField tf = new NumericTextField(10, format); tf.setValue((double) 123456.789); JLabel lbl = new JLabel("Type a number: "); f.getContentPane().add(tf, "East"); f.getContentPane().add(lbl, "West"); tf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { tf.normalize(); Long l = tf.getLongValue(); System.out.println("Value is (Long)" + l); } catch (ParseException e1) { try { Double d = tf.getDoubleValue(); System.out.println("Value is (Double)" + d); } catch (ParseException e2) { System.out.println(e2); } } } }); f.pack(); f.setVisible(true); }
From source file:eu.fbk.utils.lsa.util.Anvur.java
public static void main(String[] args) throws Exception { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "log-config.txt"; }//from w ww. j a v a 2 s . c o m PropertyConfigurator.configure(logConfig); /* if (args.length != 2) { log.println("Usage: java -mx512M eu.fbk.utils.lsa.util.Anvur in-file out-dir"); System.exit(1); } File l = new File(args[1]); if (!l.exists()) { l.mkdir(); } List<String[]> list = readText(new File(args[0])); String oldCategory = ""; for (int i=0;i<list.size();i++) { String[] s = list.get(i); if (!oldCategory.equals(s[0])) { File f = new File(args[1] + File.separator + s[0]); boolean b = f.mkdir(); logger.debug(f + " created " + b); } File g = new File(args[1] + File.separator + s[0] + File.separator + s[1] + ".txt"); logger.debug("writing " + g + "..."); PrintWriter pw = new PrintWriter(new FileWriter(g)); //pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2])); if (s.length == 5) { pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2] + " " + s[4].replace('_', ' '))); } else { pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2])); } pw.flush(); pw.close(); } // end for i */ if (args.length != 7) { System.out.println(args.length); System.out.println( "Usage: java -mx2G eu.fbk.utils.lsa.util.Anvur input threshold size dim idf in-file-csv fields\n\n"); System.exit(1); } // DecimalFormat dec = new DecimalFormat("#.00"); File Ut = new File(args[0] + "-Ut"); File Sk = new File(args[0] + "-S"); File r = new File(args[0] + "-row"); File c = new File(args[0] + "-col"); File df = new File(args[0] + "-df"); double threshold = Double.parseDouble(args[1]); int size = Integer.parseInt(args[2]); int dim = Integer.parseInt(args[3]); boolean rescaleIdf = Boolean.parseBoolean(args[4]); //"author_check"0, "authors"1, "title"2, "year"3, "pubtype"4, "publisher"5, "journal"6, "volume"7, "number"8, "pages"9, "abstract"10, "nauthors", "citedby" String[] labels = { "author_check", "authors", "title", "year", "pubtype", "publisher", "journal", "volume", "number", "pages", "abstract", "nauthors", "citedby" //author_id authors title year pubtype publisher journal volume number pages abstract nauthors citedby }; String name = buildName(labels, args[6]); File bwf = new File(args[5] + name + "-bow.txt"); PrintWriter bw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bwf), "UTF-8"))); File bdf = new File(args[5] + name + "-bow.csv"); PrintWriter bd = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bdf), "UTF-8"))); File lwf = new File(args[5] + name + "-ls.txt"); PrintWriter lw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(lwf), "UTF-8"))); File ldf = new File(args[5] + name + "-ls.csv"); PrintWriter ld = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ldf), "UTF-8"))); File blwf = new File(args[5] + name + "-bow+ls.txt"); PrintWriter blw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(blwf), "UTF-8"))); File bldf = new File(args[5] + name + "-bow+ls.csv"); PrintWriter bld = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bldf), "UTF-8"))); File logf = new File(args[5] + name + ".log"); PrintWriter log = new PrintWriter( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logf), "UTF-8"))); //System.exit(0); LSM lsm = new LSM(Ut, Sk, r, c, df, dim, rescaleIdf); LSSimilarity lss = new LSSimilarity(lsm, size); List<String[]> list = readText(new File(args[5])); // author_check authors title year pubtype publisher journal volume number pages abstract nauthors citedby //header for (int i = 0; i < list.size(); i++) { String[] s1 = list.get(i); String t1 = s1[0].toLowerCase(); bw.print("\t"); lw.print("\t"); blw.print("\t"); bw.print(i + "(" + s1[0] + ")"); lw.print(i + "(" + s1[0] + ")"); blw.print(i + "(" + s1[0] + ")"); } // end for i bw.print("\n"); lw.print("\n"); blw.print("\n"); for (int i = 0; i < list.size(); i++) { logger.info(i + "\t"); String[] s1 = list.get(i); String t1 = buildText(s1, args[6]); BOW bow1 = new BOW(t1); logger.info(bow1); Vector d1 = lsm.mapDocument(bow1); d1.normalize(); log.println("d1:" + d1); Vector pd1 = lsm.mapPseudoDocument(d1); pd1.normalize(); log.println("pd1:" + pd1); Vector m1 = merge(pd1, d1); log.println("m1:" + m1); // write the orginal line for (int j = 0; j < s1.length; j++) { bd.print(s1[j]); bd.print("\t"); ld.print(s1[j]); ld.print("\t"); bld.print(s1[j]); bld.print("\t"); } // write the bow, ls, and bow+ls vectors bd.println(d1); ld.println(pd1); bld.println(m1); bw.print(i + "(" + s1[0] + ")"); lw.print(i + "(" + s1[0] + ")"); blw.print(i + "(" + s1[0] + ")"); for (int j = 0; j < i + 1; j++) { bw.print("\t"); lw.print("\t"); blw.print("\t"); } // end for j for (int j = i + 1; j < list.size(); j++) { logger.info(i + "\t" + j); String[] s2 = list.get(j); String t2 = buildText(s2, args[6]); BOW bow2 = new BOW(t2); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t1:" + t1); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t2:" + t2); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow1:" + bow1); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow2:" + bow2); Vector d2 = lsm.mapDocument(bow2); d2.normalize(); log.println("d2:" + d2); Vector pd2 = lsm.mapPseudoDocument(d2); pd2.normalize(); log.println("pd2:" + pd2); Vector m2 = merge(pd2, d2); log.println("m2:" + m2); float cosVSM = d1.dotProduct(d2) / (float) Math.sqrt(d1.dotProduct(d1) * d2.dotProduct(d2)); float cosLSM = pd1.dotProduct(pd2) / (float) Math.sqrt(pd1.dotProduct(pd1) * pd2.dotProduct(pd2)); float cosBOWLSM = m1.dotProduct(m2) / (float) Math.sqrt(m1.dotProduct(m1) * m2.dotProduct(m2)); bw.print("\t"); bw.print(dec.format(cosVSM)); lw.print("\t"); lw.print(dec.format(cosLSM)); blw.print("\t"); blw.print(dec.format(cosBOWLSM)); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow\t" + cosVSM); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") ls:\t" + cosLSM); log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow+ls:\t" + cosBOWLSM); } bw.print("\n"); lw.print("\n"); blw.print("\n"); } // end for i logger.info("wrote " + bwf); logger.info("wrote " + bwf); logger.info("wrote " + bdf); logger.info("wrote " + lwf); logger.info("wrote " + ldf); logger.info("wrote " + blwf); logger.info("wrote " + bldf); logger.info("wrote " + logf); ld.close(); bd.close(); bld.close(); bw.close(); lw.close(); blw.close(); log.close(); }
From source file:com.mycompany.myelasticsearch.MainClass.java
/** * @param args the command line arguments *//*from ww w .j a va 2s .c o m*/ public static void main(String[] args) { // TODO code application logic here Tika tika = new Tika(); String fileEntry = "C:\\Contract\\Contract1.pdf"; String filetype = tika.detect(fileEntry); System.out.println("FileType " + filetype); BodyContentHandler handler = new BodyContentHandler(-1); String text = ""; Metadata metadata = new Metadata(); FileInputStream inputstream = null; try { inputstream = new FileInputStream(fileEntry); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } ParseContext pcontext = new ParseContext(); //parsing the document using PDF parser PDFParser pdfparser = new PDFParser(); try { pdfparser.parse(inputstream, handler, metadata, pcontext); } catch (IOException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (TikaException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } String docText = ""; String outputArray[]; String out[]; //getting the content of the document docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", ""); // PhraseDetection.getPhrases(docText); try { Node node = nodeBuilder().node(); Client client = node.client(); DocumentReader.parseString(docText, client); //"Borrowing should be replaced by the user input key" Elastic.getDefinedTerm(client, "definedterms", "term", "1", "Borrowing"); node.close(); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } Stanford.getSentence(docText); int definedTermsEnd = docText.indexOf("SCHEDULES"); String toc = docText.substring(0, definedTermsEnd); String c = docText.substring(definedTermsEnd); System.out.println("Table of content" + toc); System.out.println("--------------------------------"); System.out.println("content" + c); out = toc.split("Article|article|ARTICLE"); int count = 0; String outputArrayString = ""; int s = 0; StringBuffer tocOutput = new StringBuffer(); for (String o : out) { if (count != 0) { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { tocOutput.append(o); tocOutput.append("JigarAnkitNeeraj"); System.out.println(s); } } outputArrayString += "Count" + count + o; count++; System.out.println(); } System.out.println("---------------------------------------------------Content---------"); count = 1; StringBuffer contentOutput = new StringBuffer(); String splitContent[] = c.split("ARTICLE|Article"); Node node = nodeBuilder().node(); Client client = node.client(); for (String o : splitContent) { o = o.replaceAll("[^a-zA-Z0-9.,\\/#!$%\\^&\\*;:{}=\\-_`~()?\\s]+", ""); o = o.replaceAll("\n", " "); char input = o.charAt(1); if (input >= '0' && input <= '9') { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { //System.out.println(s); JSONObject articleJSONObject = new JSONObject(); contentOutput.append(" \n MyArticlesSeparated \n "); articleJSONObject.put("Article" + count, o.toString()); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "article", String.valueOf(count)) .setSource(articleJSONObject.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(s); count++; } //outputArrayString += "Count" + count + o; contentOutput.append(o); } } Elastic.getDocument(client, "contract", "article", "1"); Elastic.searchDocument(client, "contract", "article", "Lenders"); Elastic.searchDocument(client, "contract", "article", "Negative Covenants"); Elastic.searchDocument(client, "contract", "article", "Change in Law"); String tableOfContent[]; tableOfContent = tocOutput.toString().split("JigarAnkitNeeraj"); String splitContectsAccordingToArticles[]; splitContectsAccordingToArticles = contentOutput.toString().split("MyArticlesSeparated"); int numberOfArticle = splitContectsAccordingToArticles.length; int countArticle = 1; Double toBeTruncated = new Double("" + countArticle + ".00"); String section = "Section"; toBeTruncated += 0.01; System.out.println(toBeTruncated); String sectionEnd; StringBuffer sectionOutput = new StringBuffer(); int skipFirstArtcile = 0; JSONObject obj = new JSONObject(); for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "section", String.valueOf(count)) .setSource(obj.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); } catch (Exception e) { //What if Article has No Sections String numberOnly = article.replaceAll("[^0-9]", "").substring(0, 1); String sectionArticle = "ARTICLE " + numberOnly; sectionOutput.append(" \n Value:" + article); obj.put(sectionArticle, article); System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); System.out.println(sectionOutput); String patternStr = "\\n\\n+[(]"; String paragraphSubstringArray[] = article.substring(start, end).split(patternStr); JSONObject paragraphObject = new JSONObject(); int counter = 0; for (String paragraphSubstring : paragraphSubstringArray) { counter++; paragraphObject.put("Paragraph " + counter, paragraphSubstring); } obj.put(sectionStart, paragraphObject); } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end)); PhraseDetection.getPhrases(docText); } catch (Exception e) { //What if Article has No Sections String sectionArticle = "ARTICLE"; System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } Elastic.getDocument(client, "contract", "section", "1"); Elastic.searchDocument(client, "contract", "section", "Lenders"); Elastic.searchDocument(client, "contract", "section", "Negative Covenants"); try { FileWriter file = new FileWriter("TableOfIndex.txt"); file.write(tocOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract3_JSONFile.txt"); file.write(obj.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract1_KeyValueSections.txt"); file.write(sectionOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java
public static void main(String args[]) { int numberEvents = 10000; //int brake = 1000; String server = "ags104"; int in_port = 5565; int out_port = 5575; int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("s", true, "Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("o", true, "Output TCP Port"); opts.addOption("r", true, "Range"); opts.addOption("h", false, "Help"); try {//from www.ja v a2s . c o m CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("s")) { server = cmd.getOptionValue("s"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { in_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("o")) { String val = cmd.getOptionValue("o"); try { out_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for o. Must be integer.\n"; } } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new ParseException("Rate must be three comma seperated values or a single value"); } } catch (ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new ParseException(cmdInputErrorMsg); } DecimalFormat df = new DecimalFormat("##0"); RunTcpInTcpOutTest t = new RunTcpInTcpOutTest(); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, server, in_port, out_port, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); //for (int rate: rates) { for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, server, in_port, out_port, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumEvents -s Server -i InputPort -o OutputPort -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java
public static void main(String args[]) { // Example Command line args //-n 10000 -g w12ags104a.jennings.home -i 5565 -m https://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0 -f D:\github\performance-test-harness-for-geoevent\app\simulations\faa-stream.csv -r 1000,3000,1000 int numberEvents = 10000; // Number of Events String gisServer = "w12ags104a.jennings.home"; // GIS Server int inputTcpPort = 5565; // TCP Input Port String msLayerUrl = "http://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0"; String EventsInputFile = "D:\\github\\performance-test-harness-for-geoevent\\app\\simulations\\faa-stream.csv"; // Events input File int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("g", true, "GIS Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("m", true, "Map Service Layer URL"); opts.addOption("f", true, "File with GeoEvents to Send"); opts.addOption("r", true, "Rates to test Start,End,Step"); opts.addOption("h", false, "Help"); try {//from w ww. j ava 2 s .c om CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (org.apache.commons.cli.ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new org.apache.commons.cli.ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("g")) { gisServer = cmd.getOptionValue("g"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { inputTcpPort = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("m")) { msLayerUrl = cmd.getOptionValue("m"); } if (cmd.hasOption("f")) { EventsInputFile = cmd.getOptionValue("f"); } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new org.apache.commons.cli.ParseException( "Rate must be three comma seperated values or a single value"); } } catch (org.apache.commons.cli.ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new org.apache.commons.cli.ParseException(cmdInputErrorMsg); } // Assuming the ES port is 9220 RunTcpInBdsOutTest t = new RunTcpInBdsOutTest(); DecimalFormat df = new DecimalFormat("##0"); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); Thread.sleep(3 * 1000); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumberOfEvents -g GISServer -i InputTCPPort -m MapServerLayerURL -f FileWithEvents -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:driver.ieSystem2.java
public static void main(String[] args) throws SQLException { Scanner sc = new Scanner(System.in); boolean login = false; int check = 0; int id = 0;/* w w w . j a v a 2s . c om*/ String user = ""; String pass = ""; Person person = null; Date day = null; JOptionPane.showMessageDialog(null, "WELCOME TO SYSTEM", "Starting Project", JOptionPane.INFORMATION_MESSAGE); do { System.out.println("What do you want?"); System.out.println("press 1 : Login"); System.out.println("press 2 : Create New User"); System.out.println("Press 3 : Exit "); System.out.println(""); do { try { System.out.print("Enter: "); check = sc.nextInt(); } catch (InputMismatchException e) { JOptionPane.showMessageDialog(null, "Invalid Input", "Message", JOptionPane.WARNING_MESSAGE); sc.next(); } } while (check <= 1 && check >= 3); // EXIT if (check == 3) { System.out.println("Close Application"); System.exit(0); } // CREATE USER if (check == 2) { System.out.println("-----------------------------------------"); System.out.println("Create New User"); System.out.println("-----------------------------------------"); System.out.print("Account ID: "); id = sc.nextInt(); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); try { Person.createUser(id, user, pass, 0, 0, 0, 0, 0); System.out.println("-----------------------------------------"); System.out.println("Create Complete"); System.out.println("-----------------------------------------"); } catch (Exception e) { System.out.println("-----------------------------------------"); System.out.println("Error, Try again"); System.out.println("-----------------------------------------"); } } else if (check == 1) { // LOGIN do { System.out.println("-----------------------------------------"); System.out.println("LOGIN "); System.out.print("Username: "); user = sc.next(); System.out.print("Password: "); pass = sc.next(); if (Person.checkUser(user, pass)) { System.out.println("-----------------------------------------"); System.out.println("Login Complete"); } else { System.out.println("-----------------------------------------"); System.out.println("Invalid Username / Password"); } } while (!Person.checkUser(user, pass)); } } while (check != 1); login = true; person = new Person(user); do { System.out.println("-----------------------------------------"); System.out.println("Hi " + person.getPerName()); System.out.println("Press 1 : Add Income"); System.out.println("Press 2 : Add Expense"); System.out.println("Press 3 : Add Save"); System.out.println("Press 4 : History"); System.out.println("Press 5 : Search"); System.out.println("Press 6 : Analytics"); System.out.println("Press 7 : Total"); System.out.println("Press 8 : All Summary"); System.out.println("Press 9 : Sign Out"); do { try { System.out.print("Enter : "); check = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Invalid Input"); sc.next(); } } while (check <= 1 && check >= 5); // Add Income if (check == 1) { double Income; String catalog = ""; double IncomeTotal = 0; catalog = JOptionPane.showInputDialog("What is your income : "); Income = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addIncome(person.getPerId(), day, catalog, Income); person.update(); } //Add Expense else if (check == 2) { double Expense; String catalog = ""; catalog = JOptionPane.showInputDialog("What is your expense :"); Expense = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); person.addExpense(person.getPerId(), day, catalog, Expense); person.update(); } //Add Save else if (check == 3) { double Saving; double SavingTotal = 0; String catalog = ""; Saving = Integer.parseInt(JOptionPane.showInputDialog("How much is it ")); SavingTotal += Saving; person.addSave(person.getPerId(), day, catalog, Saving); person.update(); } //History else if (check == 4) { String x; do { System.out.println("-----------------------------------------"); System.out.println("YOUR HISTORY"); System.out.println("Date Type Amount"); System.out.println("-----------------------------------------"); List<History> history = person.getHistory(); if (history != null) { int count = 1; for (History h : history) { if (count++ <= 1) { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } else { System.out.println(h.getHistoryDateTime() + " " + h.getHistoryDescription() + " " + h.getAmount()); } } } System.out.println("-----------------------------------------"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //Searh else if (check == 5) { try { Connection conn = ConnectionDB.getConnection(); long a = person.getPerId(); String NAME = "Salary"; PreparedStatement ps = conn.prepareStatement( "SELECT * FROM INCOME WHERE PERID = " + a + " and CATALOG LIKE '%" + NAME + "%' "); ResultSet rec = ps.executeQuery(); while ((rec != null) && (rec.next())) { System.out.print(rec.getDate("Days")); System.out.print(" - "); System.out.print(rec.getString("CATALOG")); System.out.print(" - "); System.out.print(rec.getDouble("AMOUNT")); System.out.print(" - "); } ps.close(); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //Analy else if (check == 6) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); System.out.println("-----------------------------------------"); System.out.println("Income : " + df.format((in / sum) * 100) + "%"); System.out.println("Expense : " + df.format((ex / sum) * 100) + "%"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //TOTAL else if (check == 7) { String x; do { System.out.println("-----------------------------------------"); System.out.println("TOTALSAVE TOTAL"); System.out.println( person.getTotalSave() + " Baht" + " " + person.getTotal() + " Baht"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //ALL Summy else if (check == 8) { String x; do { DecimalFormat df = new DecimalFormat("##.##"); double in = person.getIncome(); double ex = person.getExpense(); double sum = person.getSumin_ex(); double a = ((in / sum) * 100); double b = ((ex / sum) * 100); System.out.println("-----------------------------------------"); System.out.println("ALL SUMMARY"); System.out.println("Account: " + person.getPerName()); System.out.println(""); System.out.println("Total Save ------------- Total"); System.out .println(person.getTotalSave() + " Baht " + person.getTotal() + " Baht"); System.out.println(""); System.out.println("INCOME --------------- EXPENSE"); System.out.println(df.format(a) + "%" + " " + df.format(b) + "%"); System.out.println("-----------------------------------------"); System.out.println("\n\n"); System.out.print("Back to menu (0 or back) : "); x = sc.next(); } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0")); } //LOG OUT else { System.out.println("See ya.\n"); login = false; break; } } while (true); }
From source file:main.java.RMDupper.java
public static void main(String[] args) throws IOException { System.err.println("DeDup v" + VERSION); // the command line parameters Options helpOptions = new Options(); helpOptions.addOption("h", "help", false, "show this help page"); Options options = new Options(); options.addOption("h", "help", false, "show this help page"); options.addOption("i", "input", true, "the input file if this option is not specified,\nthe input is expected to be piped in"); options.addOption("o", "output", true, "the output folder. Has to be specified if input is set."); options.addOption("m", "merged", false, "the input only contains merged reads.\n If this option is specified read names are not examined for prefixes.\n Both the start and end of the aligment are considered for all reads."); options.addOption("v", "version", false, "the version of DeDup."); HelpFormatter helpformatter = new HelpFormatter(); CommandLineParser parser = new BasicParser(); try {/* www . j av a 2 s . c o m*/ CommandLine cmd = parser.parse(helpOptions, args); if (cmd.hasOption('h')) { helpformatter.printHelp(CLASS_NAME, options); System.exit(0); } } catch (ParseException e1) { } String input = ""; String outputpath = ""; Boolean merged = Boolean.FALSE; try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('i')) { input = cmd.getOptionValue('i'); piped = false; } if (cmd.hasOption('o')) { outputpath = cmd.getOptionValue('o'); } if (cmd.hasOption('m')) { merged = Boolean.TRUE; } if (cmd.hasOption('v')) { System.out.println("DeDup v" + VERSION); System.exit(0); } } catch (ParseException e) { helpformatter.printHelp(CLASS_NAME, options); System.err.println(e.getMessage()); System.exit(0); } DecimalFormat df = new DecimalFormat("##.##"); if (piped) { RMDupper rmdup = new RMDupper(System.in, System.out, merged); rmdup.readSAMFile(); System.err.println("We are in piping mode!"); System.err.println("Total reads: " + rmdup.dupStats.total + "\n"); System.err.println("Reverse removed: " + rmdup.dupStats.removed_reverse + "\n"); System.err.println("Forward removed: " + rmdup.dupStats.removed_forward + "\n"); System.err.println("Merged removed: " + rmdup.dupStats.removed_merged + "\n"); System.err.println("Total removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse) + "\n"); if (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_forward + rmdup.dupStats.removed_reverse == 0) { System.err.println("Duplication Rate: " + df.format(0.00)); } else { System.err.println("Duplication Rate: " + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total)); } } else { if (outputpath.length() == 0) { System.err.println("The output folder has to be specified"); helpformatter.printHelp(CLASS_NAME, options); System.exit(0); } //Check whether we have a directory as output path, else produce error message and quit! File f = new File(outputpath); if (!f.isDirectory()) { System.err.println("The output folder should be a folder and not a file!"); System.exit(0); } File inputFile = new File(input); File outputFile = new File( outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + "_rmdup.bam"); File outputlog = new File( outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + ".log"); File outputhist = new File( outputpath + "/" + Files.getNameWithoutExtension(inputFile.getAbsolutePath()) + ".hist"); try { FileWriter fw = new FileWriter(outputlog); FileWriter histfw = new FileWriter(outputhist); BufferedWriter bfw = new BufferedWriter(fw); BufferedWriter histbfw = new BufferedWriter(histfw); RMDupper rmdup = new RMDupper(inputFile, outputFile, merged); rmdup.readSAMFile(); rmdup.inputSam.close(); rmdup.outputSam.close(); bfw.write("Total reads: " + rmdup.dupStats.total + "\n"); bfw.write("Reverse removed: " + rmdup.dupStats.removed_reverse + "\n"); bfw.write("Forward removed: " + rmdup.dupStats.removed_forward + "\n"); bfw.write("Merged removed: " + rmdup.dupStats.removed_merged + "\n"); bfw.write("Total removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse) + "\n"); bfw.write("Duplication Rate: " + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total)); bfw.flush(); bfw.close(); histbfw.write(rmdup.oc.getHistogram()); histbfw.flush(); histbfw.close(); System.out.println("Total reads: " + rmdup.dupStats.total + "\n"); System.out.println("Unmerged removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_reverse) + "\n"); System.out.println("Merged removed: " + rmdup.dupStats.removed_merged + "\n"); System.out.println("Total removed: " + (rmdup.dupStats.removed_forward + rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse) + "\n"); if (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_forward + rmdup.dupStats.removed_reverse == 0) { System.out.println("Duplication Rate: " + df.format(0.00)); } else { System.out.println("Duplication Rate: " + df.format((double) (rmdup.dupStats.removed_merged + rmdup.dupStats.removed_reverse + rmdup.dupStats.removed_forward) / (double) rmdup.dupStats.total)); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:Main.java
public static String formatNumber(int value) { return new DecimalFormat("00").format(value); }