List of usage examples for java.text NumberFormat getInstance
public static final NumberFormat getInstance()
From source file:edu.cornell.med.icb.goby.modes.SplitTranscriptsMode.java
/** * Perform the split transcripts mode./*from w w w. j a va2s . c o m*/ * * @throws IOException error reading / writing */ @Override public void execute() throws IOException { // Load the gene to transcripts file if (!config.validate()) { throw new IOException("Invalid SplitTranscripts configuration"); } final GeneTranscriptRelationships gtr = new GeneTranscriptRelationships(); final IndexedIdentifier transcriptIdents = new IndexedIdentifier(); final Int2ObjectMap<MutableString> transcriptIndexToIdMap = new Int2ObjectOpenHashMap<MutableString>(); final List<FastXEntry> fastxEntries = new LinkedList<FastXEntry>(); // // Pass through the file once to collect the transcript - gene relationships // int entryCount = 0; try { for (final FastXEntry entry : new FastXReader(config.getInputFile())) { entryCount++; parseHeader(entry.getEntryHeader()); final MutableString transcriptId = transcriptHeader.get("transcriptId"); final MutableString geneId = transcriptHeader.get("geneId"); final int transcriptIndex = transcriptIdents.registerIdentifier(transcriptId); gtr.addRelationship(geneId, transcriptIndex); transcriptIndexToIdMap.put(transcriptIndex, transcriptId); fastxEntries.add(entry.clone()); } } catch (CloneNotSupportedException e) { LOG.error("Couldn't clone for some reason", e); throw new GobyRuntimeException("Couldn't clone for some reason", e); } LOG.info("Loading map of genes-transcripts complete."); // // Scan through the transcript-gene relationships to determine which // transcript id goes into which file // final Int2IntMap transcriptIndex2FileIndex = new Int2IntOpenHashMap(); final String configOutputFilename = config.getOutputBase() + ".config"; final String configOutputPath = FilenameUtils.getFullPath(configOutputFilename); if (StringUtils.isNotBlank(configOutputPath)) { LOG.info("Creating output directory: " + configOutputPath); FileUtils.forceMkdir(new File(configOutputPath)); } PrintWriter configOutput = null; try { configOutput = new PrintWriter(configOutputFilename); configOutput.println("Ensembl Gene ID\tEnsembl Transcript ID"); final Int2IntMap fileIndex2NumberOfEntries = new Int2IntOpenHashMap(); fileIndex2NumberOfEntries.defaultReturnValue(0); transcriptIndex2FileIndex.defaultReturnValue(-1); final int initialNumberOfFiles = getNumberOfFiles(gtr, transcriptIndex2FileIndex); for (int geneIndex = 0; geneIndex < gtr.getNumberOfGenes(); geneIndex++) { final MutableString geneId = gtr.getGeneId(geneIndex); final IntSet transcriptIndices = gtr.getTranscriptSet(geneIndex); int fileNum = 0; for (final int transcriptIndex : transcriptIndices) { if (transcriptIndex2FileIndex.get(transcriptIndex) != -1) { LOG.warn("Skipping repeated transcriptIndex: " + transcriptIndex); continue; } final int maxEntriesPerFile = config.getMaxEntriesPerFile(); final int numberOfEntriesInOriginalBucket = fileIndex2NumberOfEntries.get(fileNum); final int adjustedFileIndex = fileNum + initialNumberOfFiles * (numberOfEntriesInOriginalBucket / maxEntriesPerFile); transcriptIndex2FileIndex.put(transcriptIndex, adjustedFileIndex); fileIndex2NumberOfEntries.put(fileNum, fileIndex2NumberOfEntries.get(fileNum) + 1); final MutableString transcriptId = transcriptIndexToIdMap.get(transcriptIndex); configOutput.printf("%s\t%s%n", geneId, transcriptId); fileNum++; } } } finally { IOUtils.closeQuietly(configOutput); } final int numFiles = getFileIndices(transcriptIndex2FileIndex).size(); if (LOG.isInfoEnabled()) { LOG.info(NumberFormat.getInstance().format(entryCount) + " entries will be written to " + numFiles + " files"); final int maxEntriesPerFile = config.getMaxEntriesPerFile(); if (maxEntriesPerFile < Integer.MAX_VALUE) { LOG.info("Each file will contain at most " + maxEntriesPerFile + " entries"); } } // formatter for uniquely numbering files each with the same number of digits final NumberFormat fileNumberFormatter = getNumberFormatter(numFiles - 1); final ProgressLogger progressLogger = new ProgressLogger(); progressLogger.expectedUpdates = entryCount; progressLogger.itemsName = "entries"; progressLogger.start(); // Write each file one at a time rather than in the order they appear in the input file // to avoid the issue of having too many streams open at the same or continually opening // and closing streams which is quite costly. We could store the gene/transcripts in // memory and then just write the files at the end but that could be worse. for (final int fileIndex : getFileIndices(transcriptIndex2FileIndex)) { final String filename = config.getOutputBase() + "." + fileNumberFormatter.format(fileIndex) + ".fa.gz"; PrintStream printStream = null; try { // each file is compressed printStream = new PrintStream(new GZIPOutputStream(new FileOutputStream(filename))); // // Read through the input file get the actual sequence information // final Iterator<FastXEntry> entries = fastxEntries.iterator(); while (entries.hasNext()) { final FastXEntry entry = entries.next(); parseHeader(entry.getEntryHeader()); final MutableString transcriptId = transcriptHeader.get("transcriptId"); final MutableString geneId = transcriptHeader.get("geneId"); final int transcriptIndex = transcriptIdents.getInt(transcriptId); final int transcriptFileIndex = transcriptIndex2FileIndex.get(transcriptIndex); if (transcriptFileIndex == fileIndex) { printStream.print(entry.getHeaderSymbol()); printStream.print(transcriptId); printStream.print(" gene:"); printStream.println(geneId); printStream.println(entry.getEntrySansHeader()); entries.remove(); progressLogger.lightUpdate(); } } } finally { IOUtils.closeQuietly(printStream); } } assert progressLogger.count == entryCount : "Some entries were not processed!"; progressLogger.done(); }
From source file:org.testeditor.dashboard.TableDurationTrend.java
/** * designs and creates graph from data sets. * /*from ww w . j a va 2 s.c o m*/ * @param objektList * list of all suite GoogleSucheSuite runs <AllRunsResult> * @param parent * composite parent * @param modelService * to find part label * @param window * trimmed window * @param app * org.eclipse.e4.ide.application */ @SuppressWarnings({ "serial" }) @Inject @Optional public void createControls(@UIEventTopic("Testobjektlist") List<AllRunsResult> objektList, Composite parent, EModelService modelService, MWindow window, MApplication app) { MPart mPart = (MPart) modelService.find("org.testeditor.ui.part.2", app); String[] arr = objektList.get(0).getFilePath().getName().split("\\."); String filenameSplitted = arr[arr.length - 1]; mPart.setLabel(translationService.translate("%dashboard.table.label.duration", CONTRIBUTOR_URI) + " " + filenameSplitted); mPart.setTooltip(translationService.translate("%dashboard.table.label.duration", CONTRIBUTOR_URI) + " " + objektList.get(0).getFilePath().getName()); parent.setLayout(new FillLayout()); // create the chart... chart = ChartFactory.createBarChart3D(null, // chart // title translationService.translate("%dashboard.table.label.duration.axis.dates", CONTRIBUTOR_URI), // domain // X axis // label translationService.translate("%dashboard.table.label.duration.axis.duration", CONTRIBUTOR_URI) + " h:m:s:ms", // range // Y axis // label createDataset(objektList), // data PlotOrientation.VERTICAL, // orientation false, // include legend true, // tooltips? false // URLs? ); // get a reference to the plot for further customisation... final CategoryPlot plot = chart.getCategoryPlot(); // y axis right plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT); // set the range axis to display integers only... final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); rangeAxis.setNumberFormatOverride(new NumberFormat() { // show duration // values in // h:m:s:ms @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { // return new StringBuffer(String.format("%f", number)); return new StringBuffer(String.format(formatDuration(number))); } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { // return new StringBuffer(String.format("%f", number)); return new StringBuffer(String.format(formatDuration(number))); } @Override public Number parse(String source, ParsePosition parsePosition) { return null; } }); // disable bar outlines... final BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator("{1} " + translationService.translate("%dashboard.table.label.duration.axis.duration", CONTRIBUTOR_URI) + ": {2}ms", NumberFormat.getInstance())); renderer.setDrawBarOutline(false); renderer.setMaximumBarWidth(.15); final CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(1.57)); Color color = toAwtColor(ColorConstants.COLOR_BLUE); final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, color, 0, 0, color); renderer.setSeriesPaint(0, gp0); chartComposite = new ChartComposite(parent, SWT.EMBEDDED); chartComposite.setSize(800, 800); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); chartComposite.setLayoutData(data); chartComposite.setHorizontalAxisTrace(false); chartComposite.setVerticalAxisTrace(false); chartComposite.setChart(chart); chartComposite.pack(true); chartComposite.setVisible(true); chartComposite.forceRedraw(); parent.layout(); }
From source file:com.nextgis.mobile.forms.CompassFragment.java
public static String formatNumber(Object value, int max, int min) { NumberFormat f = NumberFormat.getInstance(); f.setMaximumFractionDigits(max);/* w w w .j a v a 2 s .c om*/ f.setMinimumFractionDigits(min); f.setGroupingUsed(false); try { return f.format(value); } catch (IllegalArgumentException e) { return "err"; } }
From source file:com.keylesspalace.tusky.AccountActivity.java
private void onObtainAccountSuccess(Account account) { loadedAccount = account;/*from w w w .jav a 2s. co m*/ TextView username = (TextView) findViewById(R.id.account_username); TextView displayName = (TextView) findViewById(R.id.account_display_name); TextView note = (TextView) findViewById(R.id.account_note); CircularImageView avatar = (CircularImageView) findViewById(R.id.account_avatar); ImageView header = (ImageView) findViewById(R.id.account_header); String usernameFormatted = String.format(getString(R.string.status_username_format), account.username); username.setText(usernameFormatted); displayName.setText(account.getDisplayName()); note.setText(account.note); note.setLinksClickable(true); note.setMovementMethod(LinkMovementMethod.getInstance()); if (account.locked) { accountLockedView.setVisibility(View.VISIBLE); } else { accountLockedView.setVisibility(View.GONE); } Picasso.with(this).load(account.avatar).placeholder(R.drawable.avatar_default) .error(R.drawable.avatar_error).into(avatar); Picasso.with(this).load(account.header).placeholder(R.drawable.account_header_missing).into(header); NumberFormat nf = NumberFormat.getInstance(); // Add counts to the tabs in the TabLayout. String[] counts = { nf.format(Integer.parseInt(account.statusesCount)), nf.format(Integer.parseInt(account.followingCount)), nf.format(Integer.parseInt(account.followersCount)), }; for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayout.Tab tab = tabLayout.getTabAt(i); if (tab != null) { View view = tab.getCustomView(); if (view != null) { TextView total = (TextView) view.findViewById(R.id.total); total.setText(counts[i]); } } } }
From source file:Demo3D.java
/** * This run method allows to launch the computation of all frames per second * for the framemeter.//w ww. ja v a2s . com */ public void run() { long lastFrameTime; double fps; double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; long count = 0; double sum = 0; double mean = 0; while (true) { lastFrameTime = viewBr.view.getLastFrameDuration(); if (lastFrameTime > 0) { fps = 1000 / (double) lastFrameTime; count += 1; sum += fps; mean = sum / count; // To format all fps-informations. NumberFormat numbForm; numbForm = NumberFormat.getInstance(); numbForm.setMaximumFractionDigits(decimalForAllFps); if (min > fps && fps != 0 && count > 4) min = fps; if (max < fps) max = fps; jLabel.setText("Frames/sec = " + numbForm.format(fps) + " ; minFrames/sec = " + numbForm.format(min) + " ; maxFrames/sec = " + numbForm.format(max) + " ; meanFrames/sec = " + numbForm.format(mean)); // System.out.println("Frames per second = " + fps); } try { Thread.sleep(sleepDuration); } catch (InterruptedException e) { } } }
From source file:com.signalcollect.sna.gephiconnectors.SignalCollectGephiConnector.java
/** * Gets the Label Propagation in the graph and creates a chart out of it * //from w ww.j a va 2 s. com * @throws IOException */ public void getLabelPropagation() throws IOException { Map<Integer, Map<String, Integer>> m = LabelPropagation.run(graph, signalSteps.get()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); final JFreeChart chart = ChartFactory.createStackedBarChart("Evolving Label Propagation", "Signal Step", null, dataset, PlotOrientation.VERTICAL, false, false, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); StackedBarRenderer renderer = new StackedBarRenderer(); plot.setDataset(dataset); plot.setRenderer(renderer); renderer.setBaseItemLabelGenerator( new StandardCategoryItemLabelGenerator("{0} {2} {3}", NumberFormat.getInstance())); renderer.setBaseItemLabelsVisible(true); if (signalSteps.get() > 10) { long stepInterval = Math.round(new Double(signalSteps.get().doubleValue() / 10d)); for (int i = (int) stepInterval; i <= signalSteps.get(); i += stepInterval) { Set<Map.Entry<String, Integer>> entrySet = m.get(new Integer(i)).entrySet(); for (Map.Entry<String, Integer> subentry : entrySet) { dataset.addValue(subentry.getValue(), subentry.getKey(), new Integer(i)); } } } else { for (Map.Entry<Integer, Map<String, Integer>> entry : m.entrySet()) { for (Map.Entry<String, Integer> subentry : entry.getValue().entrySet()) { dataset.addValue(subentry.getValue(), subentry.getKey(), entry.getKey()); } } } renderer.setRenderAsPercentages(true); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance()); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(1200, 600)); ApplicationFrame f = new ApplicationFrame("Label Propagation"); f.setContentPane(chartPanel); f.pack(); f.setVisible(true); }
From source file:LineTypes.java
public void init() { // set up a NumFormat object to print out float with only 3 fraction // digits/* www . j a v a2 s . c o m*/ nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(3); setLayout(new BorderLayout()); GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); canvas = new Canvas3D(config); add("Center", canvas); // Create a simple scene and attach it to the virtual universe BranchGroup scene = createSceneGraph(); u = new SimpleUniverse(canvas); if (isApplication) { offScreenCanvas = new OffScreenCanvas3D(config, true); // set the size of the off-screen canvas based on a scale // of the on-screen size Screen3D sOn = canvas.getScreen3D(); Screen3D sOff = offScreenCanvas.getScreen3D(); Dimension dim = sOn.getSize(); dim.width *= 1.0f; dim.height *= 1.0f; sOff.setSize(dim); sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * offScreenScale); sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * offScreenScale); // attach the offscreen canvas to the view u.getViewer().getView().addCanvas3D(offScreenCanvas); } // This will move the ViewPlatform back a bit so the // objects in the scene can be viewed. u.getViewingPlatform().setNominalViewingTransform(); u.addBranchGraph(scene); view = u.getViewer().getView(); add("South", guiPanel()); }
From source file:chibi.gemmaanalysis.OutlierDetectionTestCli.java
/*** Write results to the output file; file name must be given as argument ***/ private void writeResultsToFileByMedian(BufferedWriter bw, ExpressionExperiment ee, OutlierDetectionTestDetails testDetails) { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(4);/* ww w . j a v a 2s. c o m*/ try { // Get information about the experiment: ee = this.eeService.thawLite(ee); System.out.println("Writing results to file for " + ee.getShortName()); bw.write(ee.getShortName()); bw.write("\t" + getPlatforms(ee)); bw.write("\t" + testDetails.getNumExpFactors()); if (useRegression) { bw.write("\t" + testDetails.getNumSigFactors()); } bw.write("\t" + ee.getBioAssays().size()); bw.write("\t" + testDetails.getNumOutliers()); // Get information about each of the outliers (should be in sorted order since outliers is a sorted list): for (OutlierDetails outlier : testDetails.getOutliers()) { bw.write("\t" + outlier.getBioAssay().getName()); bw.write("\t" + nf.format(outlier.getFirstQuartile()) + "/" + nf.format(outlier.getMedianCorrelation()) + "/" + nf.format(outlier.getThirdQuartile())); } if (useRegression) { for (ExperimentalFactor factor : testDetails.getSignificantFactors()) { bw.write("\t" + factor.getName()); } } bw.newLine(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:ca.wumbo.doommanager.client.controller.ConsoleController.java
/** * Takes whatever is in the text field and submits it. *///from w w w. j av a 2s . com private void submitLineToConsole() { // Trim the string before using, also nulls shouldn't happen (but just in case). String text = textField.getText().trim().replace('\0', '?'); // Ignore empty lines. if (text.isEmpty()) return; // Remember what we submitted, most recent goes first. commandBuffer.add(text); // Reset due to submission of text. commandBufferIndex = commandBuffer.size(); // Handle commands. switch (text.toLowerCase()) { case "clear": textArea.clear(); break; case "connect": // Note: Debugging only. textArea.appendText("Starting connection to local host..." + System.lineSeparator()); Optional<SelectionKey> key = clientSelector.openTCPConnection( new InetSocketAddress("localhost", Server.DEFAULT_LISTEN_PORT), new NetworkReceiver() { @Override public void signalConnectionTerminated() { System.out.println("Test connection killed."); } @Override public void receiveData(byte[] data) { System.out.println("Got data: " + data.length + " = " + Arrays.toString(data)); } }); if (key.isPresent()) { SelectionKey k = key.get(); Platform.runLater(() -> { try { Thread.sleep(2000); clientSelector.writeData(k, new byte[] { 1, 2 }); System.out.println("Go forth..."); } catch (Exception e) { System.err.println("UGH"); e.printStackTrace(); } }); } textArea.appendText("Connection made = " + key.isPresent() + System.lineSeparator()); break; case "copy": try { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection stringSelection = new StringSelection(textArea.getText()); clipboard.setContents(stringSelection, stringSelection); textArea.appendText("Copied to clipboard." + System.lineSeparator()); } catch (Exception e) { textArea.appendText("Error: Unable to get system clipboard." + System.lineSeparator()); } break; case "exit": coreController.exit(); break; case "getconnections": int numKeys = clientSelector.getNumConnections(); textArea.appendText("There " + (numKeys != 1 ? "are " : "is ") + numKeys + " key" + (numKeys != 1 ? "s." : ".") + System.lineSeparator()); break; case "help": textArea.appendText("Commands:" + System.lineSeparator()); textArea.appendText(" clear - Clears the console" + System.lineSeparator()); textArea.appendText(" copy - Copies all the content to your clipboard" + System.lineSeparator()); textArea.appendText(" exit - Exits the program" + System.lineSeparator()); textArea.appendText(" getconnections - Lists the connections available" + System.lineSeparator()); textArea.appendText(" help - Shows this help" + System.lineSeparator()); textArea.appendText(" history - Prints command history for " + MAX_COMMANDS_REMEMBERED + " entries" + System.lineSeparator()); textArea.appendText(" memory - Get current memory statistics" + System.lineSeparator()); textArea.appendText(" version - Gets the version information" + System.lineSeparator()); break; case "history": if (commandBuffer.size() <= 1) { textArea.appendText("No history to display" + System.lineSeparator()); break; } textArea.appendText("History:" + System.lineSeparator()); for (int i = 0; i < commandBuffer.size() - 1; i++) textArea.appendText(" " + commandBuffer.get(i) + System.lineSeparator()); // Print everything but the last command (which was this). break; case "memory": NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2); long totalMem = Runtime.getRuntime().totalMemory(); long usedMem = totalMem - Runtime.getRuntime().freeMemory(); long maxMem = Runtime.getRuntime().maxMemory(); double megabyte = 1024.0 * 1024.0; textArea.appendText("Memory statistics:" + System.lineSeparator()); textArea.appendText( " Memory used: " + nf.format(Math.abs(((double) usedMem / (double) maxMem)) * 100.0) + "%" + System.lineSeparator()); textArea.appendText( " " + nf.format(usedMem / megabyte) + " mb (used memory)" + System.lineSeparator()); textArea.appendText( " " + nf.format(maxMem / megabyte) + " mb (max memory)" + System.lineSeparator()); break; // DEBUG case "startserver": if (Start.getParsedRuntimeArgs().isClientServer()) { if (!serverManager.isInitialized()) { try { textArea.appendText("Starting server on port " + Server.DEFAULT_LISTEN_PORT + "." + System.lineSeparator()); serverManager.initialize(); } catch (Exception e) { textArea.appendText("Unable to initialize server." + System.lineSeparator()); textArea.appendText(" " + e.getMessage() + System.lineSeparator()); } } if (serverManager.isInitialized()) { if (!serverManager.isRunning()) { textArea.appendText("Running server on port " + Server.DEFAULT_LISTEN_PORT + "." + System.lineSeparator()); try { new Thread(serverManager, "ClientConsoleServer").start(); textArea.appendText("Successfully set up server." + System.lineSeparator()); } catch (Exception e) { textArea.appendText("Error setting up server:" + System.lineSeparator()); textArea.appendText(" " + e.getMessage() + System.lineSeparator()); } } else { textArea.appendText("Server is already running." + System.lineSeparator()); } } else { textArea.appendText("Server not initialized, cannot run." + System.lineSeparator()); } } break; // DEBUG case "stopserver": if (Start.getParsedRuntimeArgs().isClientServer()) { if (serverManager.isInitialized() && serverManager.isRunning()) { serverManager.requestServerTermination(); textArea.appendText("Requested server termination." + System.lineSeparator()); } else { textArea.appendText( "Cannot stop server, it has not been initialized or started." + System.lineSeparator()); } } break; case "version": textArea.appendText(applicationTitle + " version: " + applicationVersion + System.lineSeparator()); break; default: textArea.appendText("Unknown command: " + text + System.lineSeparator()); textArea.appendText("Type 'help' for commands" + System.lineSeparator()); break; } textField.clear(); }
From source file:ventanas.intervalosLenguaje.java
private double truncarNumero(double numero, int decimales) { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(decimales); String n = nf.format(numero); return Double.parseDouble(n.replace(',', '.')); }