List of usage examples for java.text DecimalFormat format
public final String format(double number)
From source file:Main.java
public static void main(String[] argv) { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(); DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); dfs.setZeroDigit('\u0660'); df.setDecimalFormatSymbols(dfs);//www . j a va 2 s .c om System.out.println(df.format(1234567.89)); }
From source file:HTMLDemo.java
public static void main(String[] a) throws IOException { PrintWriter pw = new PrintWriter(new FileWriter("test.html")); DecimalFormat ff = new DecimalFormat("#0"), cf = new DecimalFormat("0.0"); pw.println("<TABLE BORDER><TR><TH>Fahrenheit<TH>Celsius</TR>"); for (double f = 100; f <= 400; f += 10) { double c = 5 * (f - 32) / 9; pw.println("<TR ALIGN=RIGHT><TD>" + ff.format(f) + "<TD>" + cf.format(c)); }//from ww w. j ava2 s. c o m pw.println("</TABLE>"); pw.close(); // Without this, the output file may be empty }
From source file:com.mycompany.myelasticsearch.MainClass.java
/** * @param args the command line arguments *//* www . ja v a 2s . co 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: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;/* www. j a v a 2s . c o m*/ 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:fr.cs.examples.attitude.EarthObservation.java
/** Program entry point. * @param args program arguments (unused here) *//*w w w .j a v a 2s . com*/ public static void main(String[] args) { try { // configure Orekit Autoconfiguration.configureOrekit(); final SortedSet<String> output = new TreeSet<String>(); // Initial state definition : date, orbit final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, TimeScalesFactory.getUTC()); final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680); final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231); final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity), FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU); // Attitudes sequence definition final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0); final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH); final PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth(); final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>()); final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>()); final AttitudesSequence attitudesSequence = new AttitudesSequence(); final AttitudesSequence.SwitchHandler switchHandler = new AttitudesSequence.SwitchHandler() { public void switchOccurred(AttitudeProvider preceding, AttitudeProvider following, SpacecraftState s) { if (preceding == dayObservationLaw) { output.add(s.getDate() + ": switching to night law"); } else { output.add(s.getDate() + ": switching to day law"); } } }; attitudesSequence.addSwitchingCondition(dayObservationLaw, nightRestingLaw, dayNightEvent, false, true, 10.0, AngularDerivativesFilter.USE_R, switchHandler); attitudesSequence.addSwitchingCondition(nightRestingLaw, dayObservationLaw, nightDayEvent, true, false, 10.0, AngularDerivativesFilter.USE_R, switchHandler); if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) { // initial position is in daytime attitudesSequence.resetActiveProvider(dayObservationLaw); } else { // initial position is in nighttime attitudesSequence.resetActiveProvider(nightRestingLaw); } // Propagator : consider the analytical Eckstein-Hechler model final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence, Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU, Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40, Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60); // Register the switching events to the propagator attitudesSequence.registerSwitchEvents(propagator); propagator.setMasterMode(180.0, new OrekitFixedStepHandler() { public void init(final SpacecraftState s0, final AbsoluteDate t) { } public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException { try { DecimalFormatSymbols angleDegree = new DecimalFormatSymbols(Locale.US); angleDegree.setDecimalSeparator('\u00b0'); DecimalFormat ad = new DecimalFormat(" 00.000;-00.000", angleDegree); // the Earth position in spacecraft frame should be along spacecraft Z axis // during nigthtime and away from it during daytime due to roll and pitch offsets final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO); final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K); // the g function is the eclipse indicator, its an angle between Sun and Earth limb, // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb final double eclipseAngle = dayNightEvent.g(currentState); output.add(currentState.getDate() + " " + ad.format(FastMath.toDegrees(eclipseAngle)) + " " + ad.format(FastMath.toDegrees(pointingOffset))); } catch (OrekitException oe) { throw new PropagationException(oe); } } }); // Propagate from the initial date for the fixed duration SpacecraftState finalState = propagator.propagate(initialDate.shiftedBy(12600.)); // we print the lines according to lexicographic order, which is chronological order here // to make sure out of orders calls between step handler and event handlers don't mess things up for (final String line : output) { System.out.println(line); } System.out.println("Propagation ended at " + finalState.getDate()); } catch (OrekitException oe) { System.err.println(oe.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 ww w . j a v a 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: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 w ww . j a v a2 s. 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.iciql.test.IciqlSuite.java
/** * Main entry point for the test suite. Executing this method will run the * test suite on all registered databases. * // www. java 2 s. c o m * @param args * @throws Exception */ public static void main(String... args) throws Exception { Params params = new Params(); JCommander jc = new JCommander(params); try { jc.parse(args); } catch (ParameterException t) { usage(jc, t); } // Replace System.out with a file if (!StringUtils.isNullOrEmpty(params.dbPerformanceFile)) { out = new PrintStream(params.dbPerformanceFile); System.setErr(out); } deleteRecursively(new File("testdbs")); // Start the HSQL and H2 servers in-process org.hsqldb.Server hsql = startHSQL(); org.h2.tools.Server h2 = startH2(); // Statement logging final FileWriter statementWriter; if (StringUtils.isNullOrEmpty(params.sqlStatementsFile)) { statementWriter = null; } else { statementWriter = new FileWriter(params.sqlStatementsFile); } IciqlListener statementListener = new IciqlListener() { @Override public void logIciql(StatementType type, String statement) { if (statementWriter == null) { return; } try { statementWriter.append(statement); statementWriter.append('\n'); } catch (IOException e) { e.printStackTrace(); } } }; IciqlLogger.registerListener(statementListener); SuiteClasses suiteClasses = IciqlSuite.class.getAnnotation(SuiteClasses.class); long quickestDatabase = Long.MAX_VALUE; String dividerMajor = buildDivider('*', 79); String dividerMinor = buildDivider('-', 79); // Header out.println(dividerMajor); out.println(MessageFormat.format("{0} {1} ({2}) testing {3} database configurations", Constants.NAME, Constants.VERSION, Constants.VERSION_DATE, TEST_DBS.length)); out.println(dividerMajor); out.println(); showProperty("java.vendor"); showProperty("java.runtime.version"); showProperty("java.vm.name"); showProperty("os.name"); showProperty("os.version"); showProperty("os.arch"); showProperty("available processors", "" + Runtime.getRuntime().availableProcessors()); showProperty("available memory", MessageFormat.format("{0,number,0.0} GB", ((double) Runtime.getRuntime().maxMemory()) / (1024 * 1024))); out.println(); // Test a database long lastCount = 0; for (TestDb testDb : TEST_DBS) { out.println(dividerMinor); out.println("Testing " + testDb.describeDatabase()); out.println(" " + testDb.url); out.println(dividerMinor); // inject a database section delimiter in the statement log if (statementWriter != null) { statementWriter.append("\n\n"); statementWriter.append("# ").append(dividerMinor).append('\n'); statementWriter.append("# ").append("Testing " + testDb.describeDatabase()).append('\n'); statementWriter.append("# ").append(dividerMinor).append('\n'); statementWriter.append("\n\n"); } if (testDb.getVersion().equals("OFFLINE")) { // Database not available out.println("Skipping. Could not find " + testDb.url); out.println(); } else { // Setup system properties System.setProperty("iciql.url", testDb.url); System.setProperty("iciql.user", testDb.username); System.setProperty("iciql.password", testDb.password); // Test database Result result = JUnitCore.runClasses(suiteClasses.value()); // Report results testDb.runtime = result.getRunTime(); if (testDb.runtime < quickestDatabase) { quickestDatabase = testDb.runtime; } testDb.statements = IciqlLogger.getTotalCount() - lastCount; // reset total count for next database lastCount = IciqlLogger.getTotalCount(); out.println(MessageFormat.format( "{0} tests ({1} failures, {2} ignores) {3} statements in {4,number,0.000} secs", result.getRunCount(), result.getFailureCount(), result.getIgnoreCount(), testDb.statements, result.getRunTime() / 1000f)); if (result.getFailureCount() == 0) { out.println(); out.println(" 100% successful test suite run."); out.println(); } else { for (Failure failure : result.getFailures()) { out.println(MessageFormat.format("\n + {0}\n {1}", failure.getTestHeader(), failure.getMessage())); } out.println(); } } } // Display runtime results sorted by performance leader out.println(); out.println(dividerMajor); out.println(MessageFormat.format("{0} {1} ({2}) test suite performance results", Constants.NAME, Constants.VERSION, Constants.VERSION_DATE)); out.println(dividerMajor); List<TestDb> dbs = Arrays.asList(TEST_DBS); Collections.sort(dbs); out.println(MessageFormat.format("{0} {1} {2} {3} {4}", StringUtils.pad("Name", 11, " ", true), StringUtils.pad("Type", 5, " ", true), StringUtils.pad("Version", 23, " ", true), StringUtils.pad("Stats/Sec", 10, " ", true), "Runtime")); out.println(dividerMinor); for (TestDb testDb : dbs) { DecimalFormat df = new DecimalFormat("0.0"); out.println(MessageFormat.format("{0} {1} {2} {3} {4} {5}s ({6,number,0.0}x)", StringUtils.pad(testDb.name, 11, " ", true), testDb.isEmbedded ? "E" : "T", testDb.isMemory ? "M" : "F", StringUtils.pad(testDb.getVersion(), 21, " ", true), StringUtils.pad("" + testDb.getStatementRate(), 10, " ", false), StringUtils.pad(df.format(testDb.getRuntime()), 8, " ", false), ((double) testDb.runtime) / quickestDatabase)); } out.println(dividerMinor); out.println(" E = embedded connection"); out.println(" T = tcp/ip connection"); out.println(" M = memory database"); out.println(" F = file/persistent database"); // cleanup for (PoolableConnectionFactory factory : connectionFactories.values()) { factory.getPool().close(); } IciqlLogger.unregisterListener(statementListener); out.close(); System.setErr(ERR); if (statementWriter != null) { statementWriter.close(); } hsql.stop(); h2.stop(); System.exit(0); }
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 {/*from www. j av a2 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:com.music.Generator.java
public static void main(String[] args) throws Exception { Score score1 = new Score(); Read.midi(score1, "c:/tmp/gen.midi"); for (Part part : score1.getPartArray()) { System.out.println(part.getInstrument()); }/*from w w w. j av a2 s.com*/ new StartupListener().contextInitialized(null); Generator generator = new Generator(); generator.configLocation = "c:/config/music"; generator.maxConcurrentGenerations = 5; generator.init(); UserPreferences prefs = new UserPreferences(); prefs.setElectronic(Ternary.YES); //prefs.setSimpleMotif(Ternary.YES); //prefs.setMood(Mood.MAJOR); //prefs.setDrums(Ternary.YES); //prefs.setClassical(true); prefs.setAccompaniment(Ternary.YES); prefs.setElectronic(Ternary.YES); final ScoreContext ctx = generator.generatePiece(); Score score = ctx.getScore(); for (Part part : score.getPartArray()) { System.out.println(part.getTitle() + ": " + part.getInstrument()); } System.out.println("Metre: " + ctx.getMetre()[0] + "/" + ctx.getMetre()[1]); System.out.println(ctx); Write.midi(score, "c:/tmp/gen.midi"); new Thread(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(0, 0, 500, 500); frame.setVisible(true); Part part = ctx.getParts().get(PartType.MAIN); Note[] notes = part.getPhrase(0).getNoteArray(); List<Integer> pitches = new ArrayList<Integer>(); for (Note note : notes) { if (!note.isRest()) { pitches.add(note.getPitch()); } } GraphicsPanel gp = new GraphicsPanel(pitches); frame.setContentPane(gp); } }).start(); DecimalFormat df = new DecimalFormat("#.##"); for (Part part : score.getPartArray()) { StringBuilder sb = new StringBuilder(); printStatistics(ctx, part); System.out.println("------------ " + part.getTitle() + "-----------------"); Phrase[] phrases = part.getPhraseArray(); for (Phrase phr : phrases) { if (phr instanceof ExtendedPhrase) { sb.append("Contour=" + ((ExtendedPhrase) phr).getContour() + " "); } double measureSize = 0; int measures = 0; double totalLength = 0; List<String> pitches = new ArrayList<String>(); List<String> lengths = new ArrayList<String>(); System.out.println("((Phrase notes: " + phr.getNoteArray().length + ")"); for (Note note : phr.getNoteArray()) { if (!note.isRest()) { int degree = 0; if (phr instanceof ExtendedPhrase) { degree = Arrays.binarySearch(((ExtendedPhrase) phr).getScale().getDefinition(), note.getPitch() % 12); } pitches.add(String.valueOf(note.getPitch() + " (" + degree + ") ")); } else { pitches.add(" R "); } lengths.add(df.format(note.getRhythmValue())); measureSize += note.getRhythmValue(); totalLength += note.getRhythmValue(); ; if (measureSize >= ctx.getNormalizedMeasureSize()) { pitches.add(" || "); lengths.add(" || " + (measureSize > ctx.getNormalizedMeasureSize() ? "!" : "")); measureSize = 0; measures++; } } sb.append(pitches.toString() + "\r\n"); sb.append(lengths.toString() + "\r\n"); if (part.getTitle().equals(PartType.MAIN.getTitle())) { sb.append("\r\n"); } System.out.println("Phrase measures: " + measures); System.out.println("Phrase length: " + totalLength); } System.out.println(sb.toString()); } MutingPrintStream.ignore.set(true); Write.midi(score, "c:/tmp/gen.midi"); MutingPrintStream.ignore.set(null); Play.midi(score); generator.toMp3(FileUtils.readFileToByteArray(new File("c:/tmp/gen.midi"))); }