List of usage examples for java.io PrintWriter printf
public PrintWriter printf(String format, Object... args)
From source file:fNIRs.FNIRsStats.java
public static void oldWriteANOVAs(File outFile, GroupedChannels data, List<String> groupNames, List<Integer> conditions, int numChunks, int precision) { // open file for writing with a nice print stream object: PrintWriter ostream = makePWriter(outFile); // OKAY VAR NAME? // get all condition-group sequences: ArrayList<GroupedChannels.TaggedDataSequence> allTDSs = data.getAllSelectedTDSs(groupNames, conditions); // chunkData(allTDSs, numChunks); // COMMENT THIS LATER // calculate required widths for printed names and condition numbers: int nameWidth = longestLength(groupNames); // length of longest name int conditionWidth = // number of digits in the largest condition number String.valueOf(Collections.max(conditions)).length(); // make sure the fields will be wide enough to hold the ANOVA values, // which will consist of a 0 or 1 followed by a . and precision 0s: int idFieldWidth = nameWidth + 2 + conditionWidth; // 2 == " c".length() if (idFieldWidth < precision + 2) { // 2 == "1.".length() // if not, increase the condition width so the total field width is // large enough: // System.out.println("ANOVA values are wider than identifiers."); idFieldWidth = precision + 2;//w w w . j av a 2s.c om } String idFieldFormat = "%-" + idFieldWidth + "s"; // format string // output the first row, containing identifying information for each // group-condition combination: // first, output proper-width placeholder for the identifier column: ostream.printf("%" + idFieldWidth + "s ", ""); // TOO HACKY?? // then, output all tds identifiers: for (GroupedChannels.TaggedDataSequence tds : allTDSs) { ostream.printf(idFieldFormat + " ", tds.getGroupName() + " c" + tds.getCondition()); // ostream.printf(idFieldFormat + " ", // tds.getGroupName(), // tds.getCondition()); } ostream.println(); // print newline // output ANOVA values line by line: OneWayAnova myANOVA = new OneWayAnova(); for (GroupedChannels.TaggedDataSequence first : allTDSs) { // output tds identifier in first column: ostream.printf(idFieldFormat + " ", first.getGroupName() + " c" + first.getCondition()); // create Collection to send to the ANOVA object: LinkedList<double[]> dataSets = new LinkedList<double[]>(); // convert first's data sequence to an array, then add it to // dataSets dataSets.add(toPrimitiveDoubleArray(first.getData())); dataSets.add(null); // placeholder for second's data sequence for (GroupedChannels.TaggedDataSequence second : allTDSs) { // convert and add second's data sequence to position one in // dataSets: dataSets.set(1, toPrimitiveDoubleArray(second.getData())); double result = -1; // not a valid ANOVA value so we know if // something went wrong try { result = myANOVA.anovaPValue(dataSets); // if (first == second) { // if the two TDSs are the same // TDS, // result = 1; // then the ANOVA value should be 1, even // though a divide-by-zero // } } catch (Exception ex) { ostream.println(); localError("unknown problem calculating ANOVA: " + ex.getMessage()); } if (result != result) { // if result is NaN System.out.println("NaN on " + first.getGroupName() + " c" + first.getCondition() + " and " + second.getGroupName() + " c" + second.getCondition()); } ostream.printf("%-" + idFieldWidth + "." + precision + "f ", result); } ostream.println(); // print newline } ostream.close(); }
From source file:com.memonews.mahout.sentiment.SentimentModelTester.java
public void run(final PrintWriter output) throws IOException { final File base = new File(inputFile); // contains the best model final OnlineLogisticRegression classifier = ModelSerializer.readBinary(new FileInputStream(modelFile), OnlineLogisticRegression.class); final Dictionary newsGroups = new Dictionary(); final Multiset<String> overallCounts = HashMultiset.create(); final List<File> files = Lists.newArrayList(); for (final File newsgroup : base.listFiles()) { if (newsgroup.isDirectory()) { newsGroups.intern(newsgroup.getName()); files.addAll(Arrays.asList(newsgroup.listFiles())); }//from w ww.j a v a2 s . c om } System.out.printf("%d test files\n", files.size()); final ResultAnalyzer ra = new ResultAnalyzer(newsGroups.values(), "DEFAULT"); for (final File file : files) { final String ng = file.getParentFile().getName(); final int actual = newsGroups.intern(ng); final SentimentModelHelper helper = new SentimentModelHelper(); final Vector input = helper.encodeFeatureVector(file, overallCounts);// no // leak // type // ensures // this // is // a // normal // vector final Vector result = classifier.classifyFull(input); final int cat = result.maxValueIndex(); final double score = result.maxValue(); final double ll = classifier.logLikelihood(actual, input); final ClassifierResult cr = new ClassifierResult(newsGroups.values().get(cat), score, ll); ra.addInstance(newsGroups.values().get(actual), cr); } output.printf("%s\n\n", ra.toString()); }
From source file:GUI.GUIModel.java
private void StartCaptureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartCaptureActionPerformed final PlotHere PlotArea = new PlotHere("Data Aquisition"); PlotAr = PlotArea;/*from w w w . j a v a 2s. c o m*/ PlotArea.setDefaultCloseOperation(HIDE_ON_CLOSE); //PlotArea.setVisible(true); if (!ExpThread) { ExpThread = true; StopExperiment = false; ExpStatus.setText("Experiment started"); EnableForExperiment(false); Thread t1 = new Thread(new Runnable() { @Override public void run() { PrintWriter writer; DateFormat df1 = new SimpleDateFormat("yyyyMMdd-HHmmss-"); DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date today = Calendar.getInstance().getTime(); String reportDate = df1.format(today); try { writer = new PrintWriter(reportDate.concat(ExperimentName.getText()).concat(".csv"), "UTF-8"); byte[] data = new byte[1]; // my data if (SetClkOCClk.isSelected()) data[0] = 0x6; else data[0] = 0x7; //data[2] = (byte) n; byte ReportID = 0; if (ExperimentName.getText().length() != 0) writer.printf("\"Experiment Name\",\"%s\"\n", ExperimentName.getText()); if (Comments.getText().length() != 0) writer.printf("\"Comments\",\"%s\"\n", Comments.getText()); for (int i = 0; i < 10 * Integer.parseInt(Steps.getValue().toString()); i = i + 1) { Thread.sleep(100); if (StopExperiment) break; try { today = Calendar.getInstance().getTime(); reportDate = df2.format(today); if (SendAndWait()) { writer.printf("\"%s\"", reportDate); /*for (int Ite=0;Ite<8;Ite++) { writer.printf(",\"%d\"",getBit(PORTA,Ite)); } for (int Ite=0;Ite<8;Ite++) { writer.printf(",\"%d\"",getBit(PORTB,Ite)); }*/ for (int Ite = 0; Ite < 8; Ite++) { writer.printf(",\"%d\"", getBit(PORTC, Ite)); } writer.printf("\n"); //writer.printf("\"%s\",\"%d\",\"%s\",\"%s\",\"%s\"\n",reportDate, i, ADC00.getText(),ADC01.getText(),ADC02.getText()); /*PlotArea.PutPoint(0, i*0.015, Double.parseDouble(ADC00.getText())); PlotArea.PutPoint(1, i*0.015, Double.parseDouble(ADC01.getText())); PlotArea.PutPoint(2, i*0.015, Double.parseDouble(ADC02.getText()));*/ } else writer.printf("\"%s\",\"%d\",\"nan\",\"nan\",\"nan\"\n", reportDate, i); StatusText.setText("Finished step ".concat(String.valueOf(i + 1))); ExpStatus.setText("Finished step ".concat(String.valueOf(i + 1))); } catch (Exception e) { SetEnabledActivities(false); StatusText.setText( "Communication Error: Please remove and connect the USB cable and press reset button on the PIC."); } /*try { Thread.sleep(100); } catch (Exception e){}*/ } writer.close(); data[0] = 0x9; PIC.setOutputReport(ReportID, data, data.length); } catch (Exception e) { StatusText.setText("Unable to open the file."); } ExpThread = false; SetEnabledActivities(true); } }); t1.start(); } PlotArea.setDefaultCloseOperation(DISPOSE_ON_CLOSE); }
From source file:GUI.GUIModel.java
private void StartExpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartExpActionPerformed // TODO add your handling code here: //int n = Integer.parseInt(NSteps.getValue().toString()); final PlotHere PlotArea = new PlotHere("Experiment Results"); PlotAr = PlotArea;//w ww .ja v a 2 s . c om PlotArea.setDefaultCloseOperation(HIDE_ON_CLOSE); PlotArea.setVisible(true);//.show(); if (!ExpThread) { ExpThread = true; StopExperiment = false; ExpStatus.setText("Experiment started"); EnableForExperiment(false); Thread t1 = new Thread(new Runnable() { @Override public void run() { PrintWriter writer; DateFormat df1 = new SimpleDateFormat("yyyyMMdd-HHmmss-"); DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date today = Calendar.getInstance().getTime(); String reportDate = df1.format(today); try { writer = new PrintWriter(reportDate.concat(ExperimentName.getText()).concat(".csv"), "UTF-8"); byte[] data = new byte[1]; // my data if (SetClkOCClk.isSelected()) data[0] = 0x6; else data[0] = 0x7; //data[2] = (byte) n; byte ReportID = 0; if (ExperimentName.getText().length() != 0) writer.printf("\"Experiment Name\",\"%s\"\n", ExperimentName.getText()); if (Comments.getText().length() != 0) writer.printf("\"Comments\",\"%s\"\n", Comments.getText()); writer.printf("\"Motor step delay\",\"%s\"\n", MotorStepDelay.getValue().toString()); for (int i = 0; i < Integer.parseInt(Steps.getValue().toString()); i = i + 1) { if (StopExperiment) break; try { SetAllAInputRec(false); int sent = PIC.setOutputReport(ReportID, data, data.length); if (sent > 0) StatusText.setText("Rotated and read"); else { StatusText.setText("Communication error"); SetEnabledActivities(false); } if (sent > 0) { today = Calendar.getInstance().getTime(); reportDate = df2.format(today); if (WaitTillReceived()) { writer.printf("\"%s\",\"%d\",\"%s\",\"%s\",\"%s\"\n", reportDate, i, ADC00.getText(), ADC01.getText(), ADC02.getText()); PlotArea.PutPoint(0, i * 0.015, Double.parseDouble(ADC00.getText())); PlotArea.PutPoint(1, i * 0.015, Double.parseDouble(ADC01.getText())); PlotArea.PutPoint(2, i * 0.015, Double.parseDouble(ADC02.getText())); } else writer.printf("\"%s\",\"%d\",\"nan\",\"nan\",\"nan\"\n", reportDate, i); } StatusText.setText("Finished step ".concat(String.valueOf(i + 1))); ExpStatus.setText("Finished step ".concat(String.valueOf(i + 1))); } catch (Exception e) { SetEnabledActivities(false); StatusText.setText( "Communication Error: Please remove and connect the USB cable and press reset button on the PIC."); } /*try { Thread.sleep(100); } catch (Exception e){}*/ } writer.close(); data[0] = 0x9; PIC.setOutputReport(ReportID, data, data.length); } catch (Exception e) { StatusText.setText("Unable to open the file."); } ExpThread = false; SetEnabledActivities(true); } }); t1.start(); } PlotArea.setDefaultCloseOperation(DISPOSE_ON_CLOSE); }
From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java
private void addHistogramDetails(PrintWriter pw, SortedMap<String, Histogram> histograms) { if (histograms.isEmpty()) { return;/*from w w w . ja va2 s . c o m*/ } pw.println("<br>"); pw.println("<div class='table'>"); pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Histograms</div>"); pw.println("<table class='nicetable' id='data-histograms'>"); pw.println("<thead>"); pw.println("<tr>"); pw.println("<th class='header'>Name</th>"); pw.println("<th class='header'>Count</th>"); pw.println("<th class='header'>50%</th>"); pw.println("<th class='header'>Min</th>"); pw.println("<th class='header'>Max</th>"); pw.println("<th class='header'>Mean</th>"); pw.println("<th class='header'>StdDev</th>"); pw.println("<th class='header'>75%</th>"); pw.println("<th class='header'>95%</th>"); pw.println("<th class='header'>98%</th>"); pw.println("<th class='header'>99%</th>"); pw.println("<th class='header'>999%</th>"); pw.println("<th>Duration Unit</th>"); pw.println("</tr>"); pw.println("</thead>"); pw.println("<tbody>"); String rowClass = "odd"; for (Map.Entry<String, Histogram> e : histograms.entrySet()) { Histogram h = e.getValue(); Snapshot s = h.getSnapshot(); String name = e.getKey(); double durationFactor = 1.0 / timeUnit.durationFor(name).toNanos(1); String durationUnit = timeUnit.durationFor(name).toString().toLowerCase(Locale.US); pw.printf("<tr class='%s ui-state-default'>%n", rowClass); pw.printf("<td>%s</td>", name); pw.printf("<td>%d</td>", h.getCount()); pw.printf("<td>%f</td>", s.getMedian() * durationFactor); pw.printf("<td>%f</td>", s.getMin() * durationFactor); pw.printf("<td>%f</td>", s.getMax() * durationFactor); pw.printf("<td>%f</td>", s.getMean() * durationFactor); pw.printf("<td>%f</td>", s.getStdDev() * durationFactor); pw.printf("<td>%f</td>", s.get75thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get95thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get98thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get99thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get999thPercentile() * durationFactor); pw.printf("<td>%s</td>", durationUnit); pw.println("</tr>"); rowClass = "odd".equals(rowClass) ? "even" : "odd"; } pw.println("</tbody>"); pw.println("</table>"); pw.println("</div>"); }
From source file:net.shipilev.fjptrace.tasks.PrintSummaryTask.java
@Override public void doWork() throws Exception { // walk the trees PrintWriter pw = new PrintWriter(fileName); LayerStatistics global = new LayerStatistics(); SortedMap<Integer, LayerStatistics> layerStats = new TreeMap<>(); for (Task t : subgraphs.getParents()) { // compute transitive closure Set<Task> visited = new HashSet<>(); Set<Long> workers = new HashSet<>(); List<Task> prev = new ArrayList<>(); List<Task> cur = new ArrayList<>(); int depth = 0; cur.add(t);// w ww .j a v a2 s . c o m while (visited.addAll(cur)) { prev.clear(); prev.addAll(cur); cur.clear(); Set<Long> layerWorkers = new HashSet<>(); LayerStatistics layerStat = layerStats.get(depth); if (layerStat == null) { layerStat = new LayerStatistics(); layerStats.put(depth, layerStat); } for (Task c : prev) { Collection<Task> children = c.getChildren(); if (!children.isEmpty()) { cur.addAll(children); } layerStat.arities.addValue(children.size()); layerStat.selfTime.addValue(c.getSelfTime() / 1_000_000.0); layerStat.totalTime.addValue(c.getTotalTime() / 1_000_000.0); global.selfTime.addValue(c.getSelfTime() / 1_000_000.0); global.totalTime.addValue(c.getTotalTime() / 1_000_000.0); global.arities.addValue(children.size()); layerWorkers.add(c.getWorker()); } layerStat.counts.addValue(prev.size()); layerStat.threads.addValue(layerWorkers.size()); workers.addAll(layerWorkers); depth++; } global.depths.addValue(depth); global.counts.addValue(visited.size()); global.threads.addValue(workers.size()); } pw.println("Summary statistics:"); pw.printf(" total external tasks = %.0f\n", layerStats.get(0).counts.getSum()); pw.printf(" total subtasks = %.0f\n", global.counts.getSum()); pw.printf(" total threads = %.0f\n", global.threads.getMean()); pw.println(); pw.println("Per task statistics:"); pw.printf(" tasks: sum = %10.0f, min = %5.2f, avg = %5.2f, max = %5.2f\n", global.counts.getSum(), global.counts.getMin(), global.counts.getMean(), global.counts.getMax()); pw.printf(" depth: min = %5.2f, avg = %5.2f, max = %5.2f\n", global.depths.getMin(), global.depths.getMean(), global.depths.getMax()); pw.printf(" arity: min = %5.2f, avg = %5.2f, max = %5.2f\n", global.arities.getMin(), global.arities.getMean(), global.arities.getMax()); pw.printf(" threads: min = %5.2f, avg = %5.2f, max = %5.2f\n", global.threads.getMin(), global.threads.getMean(), global.threads.getMax()); pw.println(); pw.println("Per task + per depth statistics:"); for (Integer depth : layerStats.keySet()) { LayerStatistics s = layerStats.get(depth); pw.printf(" Depth = %d: \n", depth); pw.printf(" tasks: sum = %10.0f, min = %5.2f, avg = %5.2f, max = %5.2f\n", s.counts.getSum(), s.counts.getMin(), s.counts.getMean(), s.counts.getMax()); pw.printf(" self time (ms): sum = %10.0f, min = %5.2f, avg = %5.2f, max = %5.2f\n", s.selfTime.getSum(), s.selfTime.getMin(), s.selfTime.getMean(), s.selfTime.getMax()); pw.printf(" total time (ms): sum = %10.0f, min = %5.2f, avg = %5.2f, max = %5.2f\n", s.totalTime.getSum(), s.totalTime.getMin(), s.totalTime.getMean(), s.totalTime.getMax()); pw.printf(" arity: min = %5.2f, avg = %5.2f, max = %5.2f\n", s.arities.getMin(), s.arities.getMean(), s.arities.getMax()); pw.printf(" threads: min = %5.2f, avg = %5.2f, max = %5.2f\n", s.threads.getMin(), s.threads.getMean(), s.threads.getMax()); } summarizeEvents(pw, events); pw.flush(); pw.close(); }
From source file:com.xyphos.vmtgen.GUI.java
private void writeKeyValue(boolean condition, PrintWriter out, String key, String value, int padding) { if (condition) { out.printf("\t\"%s\"", key); for (int i = 0; i < padding; i++) { out.print("\t"); }// ww w . j a v a2s .c om out.printf("\"%s\"%n", value); } }
From source file:com.stanley.captioner.Transcriber.java
public void start() { // Create stream speech recognizer. StreamSpeechRecognizer recognizer = null; try {/*from w w w . j a v a 2 s .c om*/ recognizer = new StreamSpeechRecognizer(config); } catch (IOException e) { System.out.println("Failed to create recognizer."); } // Open print writer for writing text output. PrintWriter writer = null; try { writer = new PrintWriter(textOut); } catch (FileNotFoundException e) { System.out.println("Failed to create print writer."); } // Open stream for first pass. InputStream stream = null; try { stream = new FileInputStream(audio); } catch (FileNotFoundException e) { System.out.println("Failed to stream file."); } // Initialize loop variables. SpeechResult result; int resultCount = 0; Stats stats = recognizer.createStats(1); // Start recognizer for first pass. recognizer.startRecognition(stream); System.out.println("First pass (stats collection) started."); // First pass loop to collect statistics for model adaptation. while ((result = recognizer.getResult()) != null) { try { stats.collect(result); } catch (Exception e) { System.out.println("Failed to collect stats."); } resultCount++; // Toggle for testing. if (quickTest && resultCount > 5) { break; } } // Close recognizer (end of first pass). recognizer.stopRecognition(); System.out.println("Stats collection stopped."); // Transform model using model adaptation. Transform transform = stats.createTransform(); recognizer.setTransform(transform); // Reopen stream for second pass. stream = null; try { stream = new FileInputStream(audio); } catch (FileNotFoundException e) { System.out.println("Failed to stream file."); } // Start recognizer for second pass. recognizer.startRecognition(stream); System.out.println("Second pass started."); // Create output text file header. writer.printf("%-20s", "WORD:"); writer.printf("%20s", "CONFIDENCE:"); writer.printf("%20s", "START TIME:"); writer.printf("%20s", "END_TIME:"); writer.println(); for (int i = 0; i < 80; i++) { writer.print("-"); } writer.println(); // Initialize loop variables. int wordCount = 0; String sentence = ""; int sentenceLength = 0; long sentenceStart = 0; long sentenceEnd = 0; ArrayList<Sentence> sentences = new ArrayList<>(); // Second pass loop to calculate sentences. RECOG: while ((result = recognizer.getResult()) != null) { for (WordResult wordResult : result.getWords()) { wordCount++; String word = wordResult.getWord().toString(); double confidence = wordResult.getConfidence(); long startTime = wordResult.getTimeFrame().getStart(); long endTime = wordResult.getTimeFrame().getEnd(); writer.printf("%-20s", word); writer.printf("%20.1f", confidence); writer.printf("%20d", startTime); writer.printf("%20d", endTime); writer.println(); if (sentenceLength + word.length() < 40) { // Add to current sentence. sentence += " " + word; sentenceLength += word.length(); sentenceEnd = endTime; } else { // End of current sentence, store and start a new one. sentences.add(new Sentence(sentence, sentenceStart, sentenceEnd)); sentenceStart = sentenceEnd; sentence = ""; sentenceLength = 0; } // Toggle for testing. if (quickTest && wordCount > 50) { break RECOG; } } } // Close print writer and recognizer (end of second pass). writer.close(); recognizer.stopRecognition(); System.out.println("Second pass stopped."); // Create folder for caption images. String imageDirPath = FilenameUtils.concat(textOut.getParent(), FilenameUtils.getBaseName(textOut.getAbsolutePath())); System.out.println(imageDirPath); File imageDir = new File(imageDirPath); if (!imageDir.exists()) { // Create the folder if it doesn't already exist. imageDir.mkdir(); } // Calculate video output path. String videoOutPath = FilenameUtils.concat(textOut.getParent(), FilenameUtils.getBaseName(textOut.getAbsolutePath()) + ".mp4"); System.out.println(videoOutPath); // Initialize a command string for overlaying the captions. String commandString = String.format("%s -y -loglevel quiet -i %s", new Converter().getFFmpegPath(), videoIn.getAbsolutePath()); System.out.println(commandString); // Initialize a complex filter for overlaying the captions. String filterString = "-filter_complex"; // Acquire a probe object for collecting video details. Converter converter = new Converter(); FFprobe ffprobe = null; try { ffprobe = new FFprobe(converter.getFFprobePath()); } catch (IOException e) { System.out.println("Failed to find ffprobe."); } // Probe the video for details. FFmpegProbeResult probeResult = null; try { probeResult = ffprobe.probe(videoIn.getAbsolutePath()); } catch (IOException e) { System.out.println("Failed to probe video file."); } // Get the width and height of the video. FFmpegStream videoStream = probeResult.getStreams().get(0); int videoWidth = videoStream.width; int videoHeight = videoStream.height; // Calculate the x and y coordinates of the captions. int captionX = (videoWidth / 2) - 220; int captionY = videoHeight - 25 - 10; // Loop over the sentences, generate captions, and build command string. int k = 0; for (Sentence s : sentences) { // Create caption image from sentence. BufferedImage bi = new BufferedImage(440, 50, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bi.createGraphics(); g.setPaint(new Color(0, 0, 0, 128)); g.fillRect(0, 0, 440, 50); g.setPaint(new Color(255, 255, 255, 255)); g.setFont(new Font("Serif", Font.BOLD, 20)); FontMetrics fm = g.getFontMetrics(); int x = bi.getWidth() - fm.stringWidth(s.text) - 5; int y = fm.getHeight() - 5; g.drawString(s.text, x, y); g.dispose(); // Write the image to file for future reference. String suffix = String.format("caption-%03d.png", k); String imagePath = FilenameUtils.concat(imageDirPath, suffix); try { File imageFile = new File(imagePath); ImageIO.write(bi, "png", imageFile); } catch (IOException e) { System.out.println("Failed to write caption image to file."); } // Add the caption image path to the command string. commandString += " -i " + imagePath; // Add an entry to the complex filter with the caption timeframe. if (k == 0) { filterString += String.format(" \"[0:v][1:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", captionX, captionY, s.startTime / 1000, s.endTime / 1000, (k == sentences.size() - 1) ? "\"" : " [tmp];"); } else { filterString += String.format(" [tmp][%d:v] overlay=%d:%d:enable='between(t,%d,%d)'%s", k + 1, captionX, captionY, s.startTime / 1000, s.endTime / 1000, (k == sentences.size() - 1) ? "\"" : " [tmp];"); } k++; } // Build final command string. String finalCommand = String.format("%s %s -codec:a copy %s", commandString, filterString, videoOutPath); System.out.println(finalCommand); // Attempt to run the final command string to embed the captions. try { Process p = Runtime.getRuntime().exec(finalCommand); try { if (p.waitFor() != 0) { // Embedding the captions failed. System.out.println("Image overlay failed."); } } catch (InterruptedException e) { // Embedding the captions was interrupted. System.out.println("Interrupted image overlay."); } } catch (IOException e) { // Command string failed to execute. System.out.println("Failed to execute image overlay."); } // Delete intermediate audio file. audio.delete(); System.out.println("........................CAPTIONING COMPLETE........................"); }
From source file:org.apache.sling.commons.metrics.internal.MetricWebConsolePlugin.java
private void addTimerDetails(PrintWriter pw, SortedMap<String, Timer> timers) { if (timers.isEmpty()) { return;/*from w w w . ja v a 2s.c o m*/ } pw.println("<br>"); pw.println("<div class='table'>"); pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>Timers</div>"); pw.println("<table class='nicetable' id='data-timers'>"); pw.println("<thead>"); pw.println("<tr>"); pw.println("<th class='header'>Name</th>"); pw.println("<th class='header'>Count</th>"); pw.println("<th class='header'>Mean Rate</th>"); pw.println("<th class='header'>1 min rate</th>"); pw.println("<th class='header'>5 mins rate</th>"); pw.println("<th class='header'>15 mins rate</th>"); pw.println("<th class='header'>50%</th>"); pw.println("<th class='header'>Min</th>"); pw.println("<th class='header'>Max</th>"); pw.println("<th class='header'>Mean</th>"); pw.println("<th class='header'>StdDev</th>"); pw.println("<th class='header'>75%</th>"); pw.println("<th class='header'>95%</th>"); pw.println("<th class='header'>98%</th>"); pw.println("<th class='header'>99%</th>"); pw.println("<th class='header'>999%</th>"); pw.println("<th>Rate Unit</th>"); pw.println("<th>Duration Unit</th>"); pw.println("</tr>"); pw.println("</thead>"); pw.println("<tbody>"); String rowClass = "odd"; for (Map.Entry<String, Timer> e : timers.entrySet()) { Timer t = e.getValue(); Snapshot s = t.getSnapshot(); String name = e.getKey(); double rateFactor = timeUnit.rateFor(name).toSeconds(1); String rateUnit = "events/" + calculateRateUnit(timeUnit.rateFor(name)); double durationFactor = 1.0 / timeUnit.durationFor(name).toNanos(1); String durationUnit = timeUnit.durationFor(name).toString().toLowerCase(Locale.US); pw.printf("<tr class='%s ui-state-default'>%n", rowClass); pw.printf("<td>%s</td>", name); pw.printf("<td>%d</td>", t.getCount()); pw.printf("<td>%f</td>", t.getMeanRate() * rateFactor); pw.printf("<td>%f</td>", t.getOneMinuteRate() * rateFactor); pw.printf("<td>%f</td>", t.getFiveMinuteRate() * rateFactor); pw.printf("<td>%f</td>", t.getFifteenMinuteRate() * rateFactor); pw.printf("<td>%f</td>", s.getMedian() * durationFactor); pw.printf("<td>%f</td>", s.getMin() * durationFactor); pw.printf("<td>%f</td>", s.getMax() * durationFactor); pw.printf("<td>%f</td>", s.getMean() * durationFactor); pw.printf("<td>%f</td>", s.getStdDev() * durationFactor); pw.printf("<td>%f</td>", s.get75thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get95thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get98thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get99thPercentile() * durationFactor); pw.printf("<td>%f</td>", s.get999thPercentile() * durationFactor); pw.printf("<td>%s</td>", rateUnit); pw.printf("<td>%s</td>", durationUnit); pw.println("</tr>"); rowClass = "odd".equals(rowClass) ? "even" : "odd"; } pw.println("</tbody>"); pw.println("</table>"); pw.println("</div>"); }
From source file:fr.inrialpes.exmo.align.cli.GenPlot.java
/** * This does average plus plot/*from w w w . j a v a2 s . c om*/ * * @param result the resulting plot * @param writer in which the output is sent */ public void printPGFTex(Vector<Vector<Pair>> result, PrintWriter writer) { int i = 0; String marktable[] = { "+", "*", "x", "-", "|", "o", "asterisk", "star", "oplus", "oplus*", "otimes", "otimes*", "square", "square*", "triangle", "triangle*", "diamond", "diamond*", "pentagon", "pentagon*" }; String colortable[] = { "black", "red", "green!50!black", "blue", "cyan", "magenta" }; writer.println("\\documentclass[11pt]{book}"); writer.println(); writer.println("\\usepackage{pgf}"); writer.println("\\usepackage{tikz}"); writer.println("\\usetikzlibrary{plotmarks}"); writer.println(); writer.println("\\begin{document}"); writer.println("\\date{today}"); writer.println(""); writer.println("\n%% Plot generated by GenPlot of alignapi"); writer.println("\\begin{tikzpicture}[cap=round]"); writer.println("% Draw grid"); writer.println("\\draw[step=" + (STEP / 10) + "cm,very thin,color=gray] (-0.2,-0.2) grid (" + STEP + "," + STEP + ");"); writer.println("\\draw[->] (-0.2,0) -- (10.2,0);"); writer.println("\\draw (5,-0.3) node {$" + xlabel + "$}; "); writer.println("\\draw (0,-0.3) node {0.}; "); writer.println("\\draw (10,-0.3) node {1.}; "); writer.println("\\draw[->] (0,-0.2) -- (0,10.2);"); writer.println("\\draw (-0.3,0) node {0.}; "); writer.println("\\draw (-0.3,5) node[rotate=90] {$" + ylabel + "$}; "); writer.println("\\draw (-0.3,10) node {1.}; "); writer.println("% Plots"); i = 0; for (String m : listAlgo) { writer.print("\\draw[" + colortable[i % 6]); if (!listEvaluators.get(i).isValid()) writer.print(",dotted"); writer.println("] plot[mark=" + marktable[i % 19] + "] file {" + m + ".table};"); //,smooth i++; } // And a legend writer.println("% Legend"); i = 0; for (String m : listAlgo) { writer.print("\\draw[" + colortable[i % 6]); if (!listEvaluators.get(i).isValid()) writer.print(",dotted"); writer.println("] plot[mark=" + marktable[i % 19] + "] coordinates {(" + ((i % 3) * 3 + 1) + "," + (-(i / 3) * .8 - 1) + ") (" + ((i % 3) * 3 + 3) + "," + (-(i / 3) * .8 - 1) + ")};"); //,smooth writer.println("\\draw[" + colortable[i % 6] + "] (" + ((i % 3) * 3 + 2) + "," + (-(i / 3) * .8 - .8) + ") node {" + m + "};"); writer.printf("\\draw[" + colortable[i % 6] + "] (" + ((i % 3) * 3 + 2) + "," + (-(i / 3) * .8 - 1.2) + ") node {%1.2f};\n", listEvaluators.get(i).getGlobalResult()); i++; } writer.println("\\end{tikzpicture}"); writer.println(); writer.println("\\end{document}"); File dir = null; if (outputfilename == null) { dir = new File("."); } else { dir = (new File(outputfilename)).getParentFile(); } i = 0; for (Vector<Pair> table : result) { String algo = listAlgo[i]; // Open one file PrintWriter auxwriter = null; try { // Here, if -o is used, every file should go there auxwriter = new PrintWriter(new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File(dir, algo + ".table")), "UTF-8")), true); // Print header auxwriter.println("#Curve 0, " + (STEP + 1) + " points"); auxwriter.println("#x y type"); auxwriter.println("%% Plot generated by GenPlot of alignapi"); auxwriter.println("%% Include in PGF tex by:\n"); auxwriter.println("%% \\begin{tikzpicture}[cap=round]"); auxwriter.println("%% \\draw[step=" + (STEP / 10) + "cm,very thin,color=gray] (-0.2,-0.2) grid (" + STEP + "," + STEP + ");"); auxwriter.println("%% \\draw[->] (-0.2,0) -- (10.2,0) node[right] {$" + xlabel + "$}; "); auxwriter.println("%% \\draw[->] (0,-0.2) -- (0,10.2) node[above] {$" + ylabel + "$}; "); auxwriter.println("%% \\draw plot[mark=+,smooth] file {" + algo + ".table};"); auxwriter.println("%% \\end{tikzpicture}"); auxwriter.println(); for (Pair p : table) { //logger.trace( " >> {} - {}", p.getX(), p.getY() ); auxwriter.println(p.getX() * 10 + " " + p.getY() * 10); } } catch (FileNotFoundException fnfex) { logger.error("IGNORED Exception", fnfex); } catch (UnsupportedEncodingException ueex) { logger.error("IGNORED Exception", ueex); } finally { if (auxwriter != null) auxwriter.close(); } // UnsupportedEncodingException + FileNotFoundException i++; } }