public static object scaleAndFormatCurrency(decimal paramBigDecimal) { string str = BothDBPreferences.Instance.CurrencySymbol; decimal bigDecimal = paramBigDecimal.setScale(BothDBPreferences.Instance.BigDecimalScale, BothDBPreferences.Instance.BigDecimalRoundingMode); return((str.Equals("TRls") || str.Equals("MRls")) ? DecimalFormat.format(bigDecimal).concat(" " + str) : (str + " " + DecimalFormat.format(bigDecimal))); }
/** * Constructor called when creating a data validation from the API */ public DVParser(double val1, double val2, Condition c) { wasCopied = false; type = DECIMAL; errorStyle = STOP; condition = c; hasExtendedCellsValidation = false; // the options stringListGiven = false; emptyCellsAllowed = true; suppressArrow = false; showPrompt = true; showError = true; promptTitle = "\0"; errorTitle = "\0"; promptText = "\0"; errorText = "\0"; formula1String = DECIMAL_FORMAT.format(val1); if (!System.Double.IsNaN(val2)) { formula2String = DECIMAL_FORMAT.format(val2); } }
// obtains the data and calculates the grid of results private static void calculate(CalculationRunner runner) { // the trade that will have measures calculated IList <Trade> trades = ImmutableList.of(createVanillaFixedVsLibor3mSwap()); // the columns, specifying the measures to be calculated IList <Column> columns = ImmutableList.of(Column.of(Measures.PRESENT_VALUE), Column.of(Measures.PV01_CALIBRATED_SUM)); // use the built-in example market data ExampleMarketDataBuilder marketDataBuilder = ExampleMarketData.builder(); // the complete set of rules for calculating measures LocalDate valuationDate = LocalDate.of(2014, 1, 22); CalculationFunctions functions = StandardComponents.calculationFunctions(); CalculationRules rules = CalculationRules.of(functions, Currency.USD, marketDataBuilder.ratesLookup(valuationDate)); // mappings that select which market data to apply perturbations to // this applies the perturbations above to all curves PerturbationMapping <Curve> mapping = PerturbationMapping.of(MarketDataFilter.ofIdType(typeof(CurveId)), CurveParallelShifts.absolute(0, ONE_BP)); // create a scenario definition containing the single mapping above // this creates two scenarios - one for each perturbation in the mapping ScenarioDefinition scenarioDefinition = ScenarioDefinition.ofMappings(mapping); // build a market data snapshot for the valuation date MarketData marketData = marketDataBuilder.buildSnapshot(valuationDate); // the reference data, such as holidays and securities ReferenceData refData = ReferenceData.standard(); // calculate the results MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData); ScenarioMarketData scenarioMarketData = marketDataFactory().createMultiScenario(reqs, MarketDataConfig.empty(), marketData, refData, scenarioDefinition); Results results = runner.calculateMultiScenario(rules, trades, columns, scenarioMarketData, refData); // TODO Replace the results processing below with a report once the reporting framework supports scenarios // The results are lists of currency amounts containing one value for each scenario //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.data.scenario.ScenarioArray<?> pvList = (com.opengamma.strata.data.scenario.ScenarioArray<?>) results.get(0, 0).getValue(); ScenarioArray <object> pvList = (ScenarioArray <object>)results.get(0, 0).Value; //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.data.scenario.ScenarioArray<?> pv01List = (com.opengamma.strata.data.scenario.ScenarioArray<?>) results.get(0, 1).getValue(); ScenarioArray <object> pv01List = (ScenarioArray <object>)results.get(0, 1).Value; double pvBase = ((CurrencyAmount)pvList.get(0)).Amount; double pvShifted = ((CurrencyAmount)pvList.get(1)).Amount; double pv01Base = ((CurrencyAmount)pv01List.get(0)).Amount; NumberFormat numberFormat = new DecimalFormat("###,##0.00", new DecimalFormatSymbols(Locale.ENGLISH)); Console.WriteLine(" PV (base) = " + numberFormat.format(pvBase)); Console.WriteLine(" PV (1 bp curve shift) = " + numberFormat.format(pvShifted)); Console.WriteLine("PV01 (algorithmic differentiation) = " + numberFormat.format(pv01Base)); Console.WriteLine(" PV01 (finite difference) = " + numberFormat.format(pvShifted - pvBase)); }
void Tango.IOnTangoUpdateListener.OnPoseAvailable(TangoPoseData pose) { ParentActivity.RunOnUiThread(() => { MotionTracking parent = (mParentActivity as MotionTracking); // Log whenever Motion Tracking enters a n invalid state if (!parent.mIsAutoRecovery && (pose.StatusCode == TangoPoseData.PoseInvalid)) { Log.Wtf(mParentActivity.GetType().Name, "Invalid State"); } parent.mDeltaTime = (float)(pose.Timestamp - parent.mPreviousTimeStamp) * SECS_TO_MILLISECS; parent.mPreviousTimeStamp = (float)pose.Timestamp; Log.Info(_TAG, "Delta Time is: " + parent.mDeltaTime); parent.count++; // Update the OpenGL renderable objects with the new Tango Pose // data float[] translation = pose.GetTranslationAsFloats(); parent.mRenderer.Trajectory.updateTrajectory(translation); parent.mRenderer.ModelMatCalculator.updateModelMatrix(translation, pose.GetRotationAsFloats()); parent.mRenderer.updateViewMatrix(); parent.mGLView.RequestRender(); DecimalFormat threeDec = new DecimalFormat("0.000"); string translationString = "[" + threeDec.format(pose.Translation[0]) + ", " + threeDec.format(pose.Translation[1]) + ", " + threeDec.format(pose.Translation[2]) + "] "; string quaternionString = "[" + threeDec.format(pose.Rotation[0]) + ", " + threeDec.format(pose.Rotation[1]) + ", " + threeDec.format(pose.Rotation[2]) + ", " + threeDec.format(pose.Rotation[3]) + "] "; // Display pose data On screen in TextViews parent.mPoseTextView.Text = translationString; parent.mQuatTextView.Text = quaternionString; parent.mPoseCountTextView.Text = parent.count.ToString(); parent.mDeltaTextView.Text = threeDec.format(parent.mDeltaTime); if (pose.StatusCode == TangoPoseData.PoseValid) { parent.mPoseStatusTextView.Text = "Valid"; } else if (pose.StatusCode == TangoPoseData.PoseInvalid) { parent.mPoseStatusTextView.Text = "Invalid"; } else if (pose.StatusCode == TangoPoseData.PoseInitializing) { parent.mPoseStatusTextView.Text = "Initializing"; } else if (pose.StatusCode == TangoPoseData.PoseUnknown) { parent.mPoseStatusTextView.Text = "Unknown"; } }); }
/// <summary> /// Converts an amount to a string. /// </summary> /// <param name="currency"> the currency </param> /// <param name="value"> the value </param> /// <returns> the string form </returns> public static string amount(Currency currency, double value) { decimal dec = decimal.valueOf(value).stripTrailingZeros(); string symbol = currency.Code + " "; if (dec.scale() <= -3) { if (Math.Abs(dec.longValue()) >= 1_000_000L) { dec = dec.movePointLeft(6); return(symbol + dec.toPlainString() + "mm"); } else { dec = dec.movePointLeft(3); return(symbol + dec.toPlainString() + "k"); } } if (dec.scale() > currency.MinorUnitDigits) { dec = dec.setScale(currency.MinorUnitDigits, RoundingMode.HALF_UP); } DecimalFormat formatter = new DecimalFormat("###,###.###", new DecimalFormatSymbols(Locale.UK)); return(symbol + formatter.format(dec)); }
private static void outputPnl <T1>(IList <LocalDate> scenarioDates, ScenarioArray <T1> scenarioValuations) { NumberFormat numberFormat = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH)); double basePv = ((CurrencyAmount)scenarioValuations.get(0)).Amount; Console.WriteLine("Base PV (USD): " + numberFormat.format(basePv)); Console.WriteLine(); Console.WriteLine("P&L series (USD):"); for (int i = 1; i < scenarioValuations.ScenarioCount; i++) { double scenarioPv = ((CurrencyAmount)scenarioValuations.get(i)).Amount; double pnl = scenarioPv - basePv; LocalDate scenarioDate = scenarioDates[i]; Console.WriteLine(Messages.format("{} = {}", scenarioDate, numberFormat.format(pnl))); } }
/// <summary> /// Return a string matching all the outcome names with all the /// probabilities produced by the <code>eval(String[] context)</code> /// method. /// </summary> /// <param name="ocs"> A <code>double[]</code> as returned by the /// <code>eval(String[] context)</code> /// method. </param> /// <returns> String containing outcome names paired with the normalized /// probability (contained in the <code>double[] ocs</code>) /// for each one. </returns> public string getAllOutcomes(double[] ocs) { if (ocs.Length != outcomeNames.Length) { return ("The double array sent as a parameter to GISModel.getAllOutcomes() must not have been produced by this model."); } else { DecimalFormat df = new DecimalFormat("0.0000"); StringBuilder sb = new StringBuilder(ocs.Length * 2); sb.Append(outcomeNames[0]).Append("[").Append(df.format(ocs[0])).Append("]"); for (int i = 1; i < ocs.Length; i++) { sb.Append(" ").Append(outcomeNames[i]).Append("[").Append(df.format(ocs[i])).Append("]"); } return(sb.ToString()); } }
public void stateChanged(ChangeEvent param1ChangeEvent) { double d = outerInstance.o_progressBar.PercentComplete; if (d > 1.0D) { d = 1.0D; } outerInstance.o_progressBar.String = decimalFormat.format(d * 100.0D) + "%"; }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void listSegments() throws java.io.IOException public virtual void listSegments() { DecimalFormat formatter = new DecimalFormat("###,###.###", DecimalFormatSymbols.getInstance(Locale.ROOT)); for (int x = 0; x < infos.size(); x++) { SegmentCommitInfo info = infos.info(x); string sizeStr = formatter.format(info.sizeInBytes()); Console.WriteLine(info.info.name + " " + sizeStr); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static String format(double paramDouble, String paramString) throws org.boris.expr.ExprException public static string format(double paramDouble, string paramString) { try { DecimalFormat decimalFormat = new DecimalFormat(paramString); return(decimalFormat.format(paramDouble)); } catch (Exception exception) { throw new ExprException(exception.Message); } }
public static object formatRate(decimal paramBigDecimal) { null = DecimalFormat.format(paramBigDecimal); int i = paramBigDecimal.ToString().IndexOf(".", StringComparison.Ordinal); int j = null.IndexOf(DecimalFormat.DecimalFormatSymbols.DecimalSeparator); if (i != -1 && j != -1) { string str1 = null.substring(0, j); string str2 = paramBigDecimal.ToString().Substring(i + 1, (paramBigDecimal.ToString().Length) - (i + 1)); null = str1 + "" + DecimalFormat.DecimalFormatSymbols.DecimalSeparator + str2; } return(removeZerosFromEnd(null)); }
private BigDecimal nDigitFormat(BigDecimal value, int scale) { /* * I needed 123,45, locale independent.I tried * NumberFormat.getCurrencyInstance().format( 12345.6789 ); but that is * locale specific.I also tried DecimalFormat df = new DecimalFormat( * "0,00" ); df.setDecimalSeparatorAlwaysShown(true); * df.setGroupingUsed(false); DecimalFormatSymbols symbols = new * DecimalFormatSymbols(); symbols.setDecimalSeparator(','); * symbols.setGroupingSeparator(' '); * df.setDecimalFormatSymbols(symbols); * * but that would not switch off grouping. Although I liked very much * the (incomplete) "BNF diagram" in * http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html * in the end I decided to calculate myself and take eur+sparator+cents * * This function will cut off, i.e. floor() subcent values Tests: * System.err.println(utils.currencyFormat(new BigDecimal(0), * ".")+"\n"+utils.currencyFormat(new BigDecimal("-1.10"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("-1.1"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("-1.01"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3489"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3419"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("12"), ",")); * * results 0.00 -1,10 -1,10 -1,01 20000123,34 20000123,34 12,00 */ value = value.setScale(scale, BigDecimal.ROUND_HALF_UP); // first, round // so that // e.g. // 1.189999999999999946709294817992486059665679931640625 // becomes // 1.19 char[] repeat = new char[scale]; Arrays.fill(repeat, '0'); DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(); otherSymbols.setDecimalSeparator('.'); DecimalFormat dec = new DecimalFormat("0." + new String(repeat), otherSymbols); return(new BigDecimal(dec.format(value))); }
/*** * MUST represent all integer numbers (those with a zero-valued fractional part) * without a leading minus sign when the value is zero, and * without a decimal point, and * without an exponent * * MUST represent all non-integer numbers in exponential notation * including a nonzero single-digit significant integer part, and * including a nonempty significant fractional part, and * including no trailing zeroes in the significant fractional part (other than as part of a ".0" required to satisfy the preceding point), and * including a capital "E", and * including no plus sign in the exponent, and * including no insignificant leading zeroes in the exponent * @param bd * @throws IOException */ private void SerializeNumber(string value) { BigDecimal bd = new BigDecimal(value); try { //attempt converting to fixed number buffer.append(bd.toBigIntegerExact().toString()); } catch (java.lang.ArithmeticException) { NumberFormat formatter = new DecimalFormat("0.0E0"); formatter.setMinimumFractionDigits(1); formatter.setMaximumFractionDigits(bd.precision()); string val = formatter.format(bd).Replace("+", ""); buffer.append(val); } }
public static string doubleToScientificString(double number, int fractionDigits) { DecimalFormat decimalFormat = new DecimalFormat(); StringBuilder stringBuilder = new StringBuilder(5 + fractionDigits).append("0."); for (int i = 0; i < fractionDigits; i++) { stringBuilder.append('0'); } stringBuilder.append("E00"); decimalFormat.applyPattern(stringBuilder.toString()); string text = decimalFormat.format(number); int num = String.instancehelper_indexOf(text, 69); if (String.instancehelper_charAt(text, num + 1) != '-') { return(new StringBuilder().append(String.instancehelper_substring(text, 0, num + 1)).append('+').append(String.instancehelper_substring(text, num + 1)).toString()); } return(text); }
//------------------------------------------------------------------------- //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(enabled = false) public void test_javaBroken() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void test_javaBroken() { // uncomment system out to see how broken it is // very specific format instance needed DecimalFormat format = new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH)); Random random = new Random(1); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); AtomicInteger broken = new AtomicInteger(); int threadCount = 15; for (int i = 0; i < threadCount; i++) { ThreadStart runner = () => { try { latch.await(); int val = random.Next(999); string a = format.format((double)val); string b = Convert.ToInt32(val).ToString(); Console.WriteLine(a + " " + b); if (!a.Equals(b)) { broken.incrementAndGet(); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }; (new Thread(runner, "TestThread" + i)).Start(); } // start all threads together latch.Signal(); Thread.Sleep(1000); Console.WriteLine("Broken: " + broken.get()); assertTrue(broken.get() > 0); }
public static void Main(string[] args) { if (args.Length == 0) { Console.Error.WriteLine("Usage: GISModel modelname < contexts"); Environment.Exit(1); } AbstractModel m = (new SuffixSensitiveGISModelReader(new Jfile(args[0]))).Model; BufferedReader @in = new BufferedReader(new InputStreamReader(new InputStream(Console.OpenStandardInput()))); // TODO get from System.in DecimalFormat df = new DecimalFormat(".###"); for (string line = @in.readLine(); line != null; line = @in.readLine()) { string[] context = line.Split(" ", true); double[] dist = m.eval(context); for (int oi = 0; oi < dist.Length; oi++) { Console.Write("[" + m.getOutcome(oi) + " " + df.format(dist[oi]) + "] "); } Console.WriteLine(); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void addBinaryField(index.FieldInfo field, Iterable<util.BytesRef> values) throws java.io.IOException public override void addBinaryField(FieldInfo field, IEnumerable <BytesRef> values) { Debug.Assert(fieldSeen(field.name)); Debug.Assert(field.DocValuesType == FieldInfo.DocValuesType.BINARY); int maxLength = 0; foreach (BytesRef value in values) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int length = value == null ? 0 : value.length; int length = value == null ? 0 : value.length; maxLength = Math.Max(maxLength, length); } writeFieldEntry(field, FieldInfo.DocValuesType.BINARY); // write maxLength SimpleTextUtil.write(data, MAXLENGTH); SimpleTextUtil.write(data, Convert.ToString(maxLength), scratch); SimpleTextUtil.WriteNewline(data); int maxBytesLength = Convert.ToString(maxLength).Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxBytesLength; i++) { sb.Append('0'); } // write our pattern for encoding lengths SimpleTextUtil.write(data, PATTERN); SimpleTextUtil.write(data, sb.ToString(), scratch); SimpleTextUtil.WriteNewline(data); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat encoder = new java.text.DecimalFormat(sb.toString(), new java.text.DecimalFormatSymbols(java.util.Locale.ROOT)); DecimalFormat encoder = new DecimalFormat(sb.ToString(), new DecimalFormatSymbols(Locale.ROOT)); int numDocsWritten = 0; foreach (BytesRef value in values) { // write length //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int length = value == null ? 0 : value.length; int length = value == null ? 0 : value.length; SimpleTextUtil.write(data, LENGTH); SimpleTextUtil.write(data, encoder.format(length), scratch); SimpleTextUtil.WriteNewline(data); // write bytes -- don't use SimpleText.write // because it escapes: if (value != null) { data.writeBytes(value.bytes, value.offset, value.length); } // pad to fit for (int i = length; i < maxLength; i++) { data.writeByte((sbyte)' '); } SimpleTextUtil.WriteNewline(data); if (value == null) { SimpleTextUtil.write(data, "F", scratch); } else { SimpleTextUtil.write(data, "T", scratch); } SimpleTextUtil.WriteNewline(data); numDocsWritten++; } Debug.Assert(numDocs == numDocsWritten); }
public virtual double roundFourDecimals(double d) { DecimalFormat fourDForm = new DecimalFormat("#.####"); return(Convert.ToDouble(fourDForm.format(d))); }
//------------------------------------------------------------------------- //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(enabled = false) public void test_performance() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void test_performance() { ThreadLocal <DecimalFormat> thread = ThreadLocal.withInitial(() => new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH))); DecimalFormat java = new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH)); NumberFormatter strata = NumberFormatter.of(true, 0, 3); Random random = new Random(1); for (int i = 0; i < 20; i++) { long start0 = System.nanoTime(); for (int j = 0; j < 100_000; j++) { double val = random.NextDouble(); string str = java.format(val); if (str.Length == 0) { throw new System.InvalidOperationException("Just to avoid dead code elimination: " + str); } } long end0 = System.nanoTime(); Console.WriteLine(" Java: " + ((end0 - start0) / 1_000_000d) + "ms"); long start1 = System.nanoTime(); for (int j = 0; j < 100_000; j++) { double val = random.NextDouble(); string str = thread.get().format(val); if (str.Length == 0) { throw new System.InvalidOperationException("Just to avoid dead code elimination: " + str); } } long end1 = System.nanoTime(); Console.WriteLine("JavaTL: " + ((end1 - start1) / 1_000_000d) + "ms"); long start1b = System.nanoTime(); for (int j = 0; j < 100_000; j++) { double val = random.NextDouble(); string str = ((NumberFormat)java.clone()).format(val); if (str.Length == 0) { throw new System.InvalidOperationException("Just to avoid dead code elimination: " + str); } } long end1b = System.nanoTime(); Console.WriteLine("JavaCl: " + ((end1b - start1b) / 1_000_000d) + "ms"); long start2 = System.nanoTime(); for (int j = 0; j < 100_000; j++) { double val = random.NextDouble(); string str = strata.format(val); if (str.Length == 0) { throw new System.InvalidOperationException("Just to avoid dead code elimination: " + str); } } long end2 = System.nanoTime(); Console.WriteLine("Strata: " + ((end2 - start2) / 1_000_000d) + "ms"); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void test10kPulsed() throws Exception public virtual void test10kPulsed() { // we always run this test with pulsing codec. Codec cp = TestUtil.alwaysPostingsFormat(new Pulsing41PostingsFormat(1)); File f = createTempDir("10kpulsed"); BaseDirectoryWrapper dir = newFSDirectory(f); dir.CheckIndexOnClose = false; // we do this ourselves explicitly RandomIndexWriter iw = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setCodec(cp)); Document document = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); switch (TestUtil.Next(random(), 0, 2)) { case 0: ft.IndexOptions = IndexOptions.DOCS_ONLY; break; case 1: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS; break; default: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; break; } Field field = newField("field", "", ft); document.add(field); NumberFormat df = new DecimalFormat("00000", new DecimalFormatSymbols(Locale.ROOT)); for (int i = 0; i < 10050; i++) { field.StringValue = df.format(i); iw.addDocument(document); } IndexReader ir = iw.Reader; iw.close(); TermsEnum te = MultiFields.getTerms(ir, "field").iterator(null); DocsEnum de = null; for (int i = 0; i < 10050; i++) { string expected = df.format(i); assertEquals(expected, te.next().utf8ToString()); de = TestUtil.docs(random(), te, null, de, DocsEnum.FLAG_NONE); assertTrue(de.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); assertEquals(DocIdSetIterator.NO_MORE_DOCS, de.nextDoc()); } ir.close(); TestUtil.checkIndex(dir); dir.close(); }
/// <summary> /// a variant, that uses pulsing, but uses a high TF to force pass thru to the underlying codec /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void test10kNotPulsed() throws Exception public virtual void test10kNotPulsed() { // we always run this test with pulsing codec. int freqCutoff = TestUtil.Next(random(), 1, 10); Codec cp = TestUtil.alwaysPostingsFormat(new Pulsing41PostingsFormat(freqCutoff)); File f = createTempDir("10knotpulsed"); BaseDirectoryWrapper dir = newFSDirectory(f); dir.CheckIndexOnClose = false; // we do this ourselves explicitly RandomIndexWriter iw = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setCodec(cp)); Document document = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); switch (TestUtil.Next(random(), 0, 2)) { case 0: ft.IndexOptions = IndexOptions.DOCS_ONLY; break; case 1: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS; break; default: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; break; } Field field = newField("field", "", ft); document.add(field); NumberFormat df = new DecimalFormat("00000", new DecimalFormatSymbols(Locale.ROOT)); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int freq = freqCutoff + 1; int freq = freqCutoff + 1; for (int i = 0; i < 10050; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < freq; j++) { sb.Append(df.format(i)); sb.Append(' '); // whitespace } field.StringValue = sb.ToString(); iw.addDocument(document); } IndexReader ir = iw.Reader; iw.close(); TermsEnum te = MultiFields.getTerms(ir, "field").iterator(null); DocsEnum de = null; for (int i = 0; i < 10050; i++) { string expected = df.format(i); assertEquals(expected, te.next().utf8ToString()); de = TestUtil.docs(random(), te, null, de, DocsEnum.FLAG_NONE); assertTrue(de.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); assertEquals(DocIdSetIterator.NO_MORE_DOCS, de.nextDoc()); } ir.close(); TestUtil.checkIndex(dir); dir.close(); }
public override string ToString() { DecimalFormat twoDigits = new DecimalFormat("00"); return(((Hour == 12 || Hour == 0) ? 12 : Hour % 12) + ":" + twoDigits.format(Minute) + ":" + twoDigits.format(Second) + (Hour < 12 ? " AM" : " PM")); }
public virtual string toUniversalString() { DecimalFormat twoDigits = new DecimalFormat("00"); return(twoDigits.format(Hour) + ":" + twoDigits.format(Minute) + ":" + twoDigits.format(Second)); }
public override string ToString() { int length = mainFunction.Size; return("Name: " + this.name.ToString() + " Outcomes: " + totalOutcomes.ToString() + " Weight: " + weightFormat.format(Weight) + " Length: " + length.ToString() + " Children: " + totalChildren.ToString()); }
//when the user copies to clip board, select the entire table. //then pull the data off of the grid and create a string object //that is the formatted matrix that the UCI file expects. public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuffer sbf = new StringBuffer(); // Check to ensure we have selected only a contiguous block of cells int numcols = jTable1.getColumnCount(); //jTable1.getSelectedColumnCount(); int numrows = jTable1.getRowCount(); //jTable1.getSelectedRowCount(); jTable1.selectAll(); int[] rowsselected = jTable1.getSelectedRows(); int[] colsselected = jTable1.getSelectedColumns(); if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) { JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE); return; } //write the name of the calculator to the string buffer //xyang sbf.append(" *** " + this.calculatorType + " ***\n"); if (this.calculatorType == "TRAPEZOIDAL") { string txt = plotdata.trapPanel.lblChannelDepth.getText(); //xyang sbf.append(" *** " + txt + " "); double outvalue = plotdata.value[0]; sbf.append(outvalue + "***\n"); txt = plotdata.trapPanel.lblTopChannelWidth.getText(); sbf.append(" *** " + txt + " "); outvalue = plotdata.value[1]; sbf.append(outvalue + "***\n"); txt = plotdata.trapPanel.lblSideChannelSlope.getText(); sbf.append(" *** " + txt + " "); outvalue = plotdata.value[2]; sbf.append(outvalue + "***\n"); txt = plotdata.trapPanel.lblChannelLength.getText(); sbf.append(" *** " + txt + " "); outvalue = plotdata.value[3]; sbf.append(outvalue + "***\n"); /*txt = plotdata.trapPanel.lblChannelMannigsValue.getText(); * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[4]; * sbf.append(outvalue + "***\n");*/ /* txt = plotdata.trapPanel.lblChannelAvgSlope.getText(); * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[5]; * sbf.append(outvalue + "***\n");*/ txt = plotdata.trapPanel.lblIncrement.getText(); sbf.append(" *** " + txt + " "); outvalue = plotdata.value[6]; sbf.append(outvalue + "***\n"); } else if (this.calculatorType == "PARABOLIC") { string txt = plotdata.parabolicPanel.lblChannelLength.getText(); //xyang sbf.append(" *** " + txt + " "); double outvalue = plotdata.value[0]; sbf.append(outvalue + "***\n"); txt = plotdata.parabolicPanel.lblChannelWidth.getText(); sbf.append(" *** " + txt + " "); outvalue = plotdata.value[1]; sbf.append(outvalue + "***\n"); txt = plotdata.parabolicPanel.lblChannelDepth.getText(); sbf.append(" *** " + txt + " "); outvalue = plotdata.value[2]; sbf.append(outvalue + "***\n"); /*txt = plotdata.parabolicPanel.lblChannelMannigsValue.getText(); * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[3]; * sbf.append(outvalue + "***\n"); * * txt = plotdata.parabolicPanel.lblChannelAvgSlope.getText(); * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[4]; * sbf.append(outvalue + "***\n");*/ txt = plotdata.parabolicPanel.lblIncrement.getText(); sbf.append(" *** " + txt + " "); outvalue = plotdata.value[5]; sbf.append(outvalue + "***\n"); } else if (this.calculatorType == "CIRCULAR") { string txt = plotdata.circPanel.lblChannelLength.getText(); //xyang sbf.append(" *** " + txt + " "); double outvalue = plotdata.value[0]; sbf.append(outvalue + "***\n"); txt = plotdata.circPanel.lblChannelDiameter.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[1]; sbf.append(outvalue + "***\n"); /*txt = plotdata.circPanel.lblChannelMannigsValue.getText();//xyang * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[2]; * sbf.append(outvalue + "***\n");*/ txt = plotdata.circPanel.lblChannelAvgSlope.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[3]; sbf.append(outvalue + "***\n"); txt = plotdata.circPanel.lblIncrement.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[4]; sbf.append(outvalue + "***\n"); } else if (this.calculatorType == "RECTANGULAR") { string txt = plotdata.recPanel.lblChannelDepth.getText(); //xyang sbf.append(" *** " + txt + " "); double outvalue = plotdata.value[0]; sbf.append(outvalue + "***\n"); txt = plotdata.recPanel.lblChannelWidth.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[1]; sbf.append(outvalue + "***\n"); txt = plotdata.recPanel.lblChannelLength.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[2]; sbf.append(outvalue + "***\n"); /*txt = plotdata.recPanel.lblChannelMannigsValue.getText();//xyang * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[3]; * sbf.append(outvalue + "***\n");*/ /*txt = plotdata.recPanel.lblChannelAvgSlope.getText();//xyang * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[4]; * sbf.append(outvalue + "***\n");*/ txt = plotdata.recPanel.lblIncrement.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[5]; sbf.append(outvalue + "***\n"); } else if (this.calculatorType == "TRIANGULAR") { string txt = plotdata.triPanel.lblChannelDepth.getText(); //xyang sbf.append(" *** " + txt + " "); double outvalue = plotdata.value[0]; sbf.append(outvalue + "***\n"); txt = plotdata.triPanel.lblChannelWidth.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[1]; sbf.append(outvalue + "***\n"); txt = plotdata.triPanel.lblChannelLength.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[2]; sbf.append(outvalue + "***\n"); /*txt = plotdata.triPanel.lblChannelMannigsValue.getText();//xyang * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[3]; * sbf.append(outvalue + "***\n"); * * txt = plotdata.triPanel.lblChannelAvgSlope.getText();//xyang * sbf.append(" *** " + txt + " "); * outvalue = plotdata.value[4]; * sbf.append(outvalue + "***\n");*/ txt = plotdata.triPanel.lblIncrement.getText(); //xyang sbf.append(" *** " + txt + " "); outvalue = plotdata.value[5]; sbf.append(outvalue + "***\n"); } //xyang end sbf.append(" FTABLE 999\n"); //sbf.append(" 999's are placeholders for user provided ID 1-3 digits in length***"); //sbf.append("\n"); sbf.append(" rows cols ***\n"); //the following section requires me to do a calculation to correctly right justify the rows and cols figures. sbf.append(FiveSpaceFormat(numrows.toString()) + FiveSpaceFormat(numcols.toString()) + "\n"); for (int i = 0; i < numcols; i++) { string colName = jTable1.getColumnModel().getColumn(i).getHeaderValue().toString(); colName = colName.substring(0, colName.indexOf("(")); sbf.append(TenSpaceFormat(colName)); } sbf.append(" ***"); sbf.append("\n"); for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { //jTable1.getValueAt(rowsselected[i],colsselected[j]); double newValue = double.valueOf(jTable1.getValueAt(rowsselected[i], colsselected[j]).toString()); if (newValue.equals(double.NaN)) { newValue = 0.000000d; } DecimalFormat df = new DecimalFormat("#.######"); // if (newValue <= 9E-6){ // sbf.append(TenSpaceFormat("0.00000")); // } // else{ sbf.append(TenSpaceFormat(df.format(newValue))); //} //if (j<numcols-1) sbf.append("\t"); } sbf.append("\n"); } sbf.append("\n"); sbf.append("\n"); sbf.append(FiveSpaceFormat(" END FTABLE999")); /*stsel = new StringSelection(sbf.toString()); * system = Toolkit.getDefaultToolkit().getSystemClipboard(); * system.setContents(stsel,stsel);*/ this.jTArea.setText(sbf.toString()); } }
//------------------------------------------------------------------------- public string formatForCsv(double?amount) { return(FULL_AMOUNT_FORMAT.format(amount.Value)); }
/// <summary> /// Formats a double value for display, using the specified number of decimal places. /// </summary> /// <param name="amount"> the amount </param> /// <param name="decimalPlaces"> the number of decimal places to display </param> /// <returns> the formatted amount </returns> public string formatForDisplay(double amount, int decimalPlaces) { DecimalFormat format = getDecimalPlacesFormat(decimalPlaces); return(format.format(amount)); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void addNumericField(index.FieldInfo field, Iterable<Number> values) throws java.io.IOException public override void addNumericField(FieldInfo field, IEnumerable <Number> values) { Debug.Assert(fieldSeen(field.name)); assert(field.DocValuesType == FieldInfo.DocValuesType.NUMERIC || field.NormType == FieldInfo.DocValuesType.NUMERIC); writeFieldEntry(field, FieldInfo.DocValuesType.NUMERIC); // first pass to find min/max long minValue = long.MaxValue; long maxValue = long.MinValue; foreach (Number n in values) { long v = n == null ? 0 : (long)n; minValue = Math.Min(minValue, v); maxValue = Math.Max(maxValue, v); } // write our minimum value to the .dat, all entries are deltas from that SimpleTextUtil.write(data, MINVALUE); SimpleTextUtil.write(data, Convert.ToString(minValue), scratch); SimpleTextUtil.WriteNewline(data); // build up our fixed-width "simple text packed ints" // format System.Numerics.BigInteger maxBig = System.Numerics.BigInteger.valueOf(maxValue); System.Numerics.BigInteger minBig = System.Numerics.BigInteger.valueOf(minValue); System.Numerics.BigInteger diffBig = maxBig - minBig; int maxBytesPerValue = diffBig.ToString().Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxBytesPerValue; i++) { sb.Append('0'); } // write our pattern to the .dat SimpleTextUtil.write(data, PATTERN); SimpleTextUtil.write(data, sb.ToString(), scratch); SimpleTextUtil.WriteNewline(data); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String patternString = sb.toString(); string patternString = sb.ToString(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat encoder = new java.text.DecimalFormat(patternString, new java.text.DecimalFormatSymbols(java.util.Locale.ROOT)); DecimalFormat encoder = new DecimalFormat(patternString, new DecimalFormatSymbols(Locale.ROOT)); int numDocsWritten = 0; // second pass to write the values foreach (Number n in values) { long value = n == null ? 0 : (long)n; Debug.Assert(value >= minValue); Number delta = System.Numerics.BigInteger.valueOf(value) - System.Numerics.BigInteger.valueOf(minValue); string s = encoder.format(delta); Debug.Assert(s.Length == patternString.Length); SimpleTextUtil.write(data, s, scratch); SimpleTextUtil.WriteNewline(data); if (n == null) { SimpleTextUtil.write(data, "F", scratch); } else { SimpleTextUtil.write(data, "T", scratch); } SimpleTextUtil.WriteNewline(data); numDocsWritten++; Debug.Assert(numDocsWritten <= numDocs); } Debug.Assert(numDocs == numDocsWritten, "numDocs=" + numDocs + " numDocsWritten=" + numDocsWritten); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void addSortedSetField(index.FieldInfo field, Iterable<util.BytesRef> values, Iterable<Number> docToOrdCount, Iterable<Number> ords) throws java.io.IOException public override void addSortedSetField(FieldInfo field, IEnumerable <BytesRef> values, IEnumerable <Number> docToOrdCount, IEnumerable <Number> ords) { Debug.Assert(fieldSeen(field.name)); Debug.Assert(field.DocValuesType == FieldInfo.DocValuesType.SORTED_SET); writeFieldEntry(field, FieldInfo.DocValuesType.SORTED_SET); long valueCount = 0; int maxLength = 0; foreach (BytesRef value in values) { maxLength = Math.Max(maxLength, value.length); valueCount++; } // write numValues SimpleTextUtil.write(data, NUMVALUES); SimpleTextUtil.write(data, Convert.ToString(valueCount), scratch); SimpleTextUtil.WriteNewline(data); // write maxLength SimpleTextUtil.write(data, MAXLENGTH); SimpleTextUtil.write(data, Convert.ToString(maxLength), scratch); SimpleTextUtil.WriteNewline(data); int maxBytesLength = Convert.ToString(maxLength).Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxBytesLength; i++) { sb.Append('0'); } // write our pattern for encoding lengths SimpleTextUtil.write(data, PATTERN); SimpleTextUtil.write(data, sb.ToString(), scratch); SimpleTextUtil.WriteNewline(data); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat encoder = new java.text.DecimalFormat(sb.toString(), new java.text.DecimalFormatSymbols(java.util.Locale.ROOT)); DecimalFormat encoder = new DecimalFormat(sb.ToString(), new DecimalFormatSymbols(Locale.ROOT)); // compute ord pattern: this is funny, we encode all values for all docs to find the maximum length int maxOrdListLength = 0; StringBuilder sb2 = new StringBuilder(); IEnumerator <Number> ordStream = ords.GetEnumerator(); foreach (Number n in docToOrdCount) { sb2.Length = 0; int count = (int)n; for (int i = 0; i < count; i++) { //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: long ord = (long)ordStream.next(); if (sb2.Length > 0) { sb2.Append(","); } sb2.Append(Convert.ToString(ord)); } maxOrdListLength = Math.Max(maxOrdListLength, sb2.Length); } sb2.Length = 0; for (int i = 0; i < maxOrdListLength; i++) { sb2.Append('X'); } // write our pattern for ord lists SimpleTextUtil.write(data, ORDPATTERN); SimpleTextUtil.write(data, sb2.ToString(), scratch); SimpleTextUtil.WriteNewline(data); // for asserts: long valuesSeen = 0; foreach (BytesRef value in values) { // write length SimpleTextUtil.write(data, LENGTH); SimpleTextUtil.write(data, encoder.format(value.length), scratch); SimpleTextUtil.WriteNewline(data); // write bytes -- don't use SimpleText.write // because it escapes: data.writeBytes(value.bytes, value.offset, value.length); // pad to fit for (int i = value.length; i < maxLength; i++) { data.writeByte((sbyte)' '); } SimpleTextUtil.WriteNewline(data); valuesSeen++; Debug.Assert(valuesSeen <= valueCount); } Debug.Assert(valuesSeen == valueCount); ordStream = ords.GetEnumerator(); // write the ords for each doc comma-separated foreach (Number n in docToOrdCount) { sb2.Length = 0; int count = (int)n; for (int i = 0; i < count; i++) { //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: long ord = (long)ordStream.next(); if (sb2.Length > 0) { sb2.Append(","); } sb2.Append(Convert.ToString(ord)); } // now pad to fit: these are numbers so spaces work well. reader calls trim() int numPadding = maxOrdListLength - sb2.Length; for (int i = 0; i < numPadding; i++) { sb2.Append(' '); } SimpleTextUtil.write(data, sb2.ToString(), scratch); SimpleTextUtil.WriteNewline(data); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void addSortedField(index.FieldInfo field, Iterable<util.BytesRef> values, Iterable<Number> docToOrd) throws java.io.IOException public override void addSortedField(FieldInfo field, IEnumerable <BytesRef> values, IEnumerable <Number> docToOrd) { Debug.Assert(fieldSeen(field.name)); Debug.Assert(field.DocValuesType == FieldInfo.DocValuesType.SORTED); writeFieldEntry(field, FieldInfo.DocValuesType.SORTED); int valueCount = 0; int maxLength = -1; foreach (BytesRef value in values) { maxLength = Math.Max(maxLength, value.length); valueCount++; } // write numValues SimpleTextUtil.write(data, NUMVALUES); SimpleTextUtil.write(data, Convert.ToString(valueCount), scratch); SimpleTextUtil.WriteNewline(data); // write maxLength SimpleTextUtil.write(data, MAXLENGTH); SimpleTextUtil.write(data, Convert.ToString(maxLength), scratch); SimpleTextUtil.WriteNewline(data); int maxBytesLength = Convert.ToString(maxLength).Length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxBytesLength; i++) { sb.Append('0'); } // write our pattern for encoding lengths SimpleTextUtil.write(data, PATTERN); SimpleTextUtil.write(data, sb.ToString(), scratch); SimpleTextUtil.WriteNewline(data); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat encoder = new java.text.DecimalFormat(sb.toString(), new java.text.DecimalFormatSymbols(java.util.Locale.ROOT)); DecimalFormat encoder = new DecimalFormat(sb.ToString(), new DecimalFormatSymbols(Locale.ROOT)); int maxOrdBytes = Convert.ToString(valueCount + 1L).Length; sb.Length = 0; for (int i = 0; i < maxOrdBytes; i++) { sb.Append('0'); } // write our pattern for ords SimpleTextUtil.write(data, ORDPATTERN); SimpleTextUtil.write(data, sb.ToString(), scratch); SimpleTextUtil.WriteNewline(data); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat ordEncoder = new java.text.DecimalFormat(sb.toString(), new java.text.DecimalFormatSymbols(java.util.Locale.ROOT)); DecimalFormat ordEncoder = new DecimalFormat(sb.ToString(), new DecimalFormatSymbols(Locale.ROOT)); // for asserts: int valuesSeen = 0; foreach (BytesRef value in values) { // write length SimpleTextUtil.write(data, LENGTH); SimpleTextUtil.write(data, encoder.format(value.length), scratch); SimpleTextUtil.WriteNewline(data); // write bytes -- don't use SimpleText.write // because it escapes: data.writeBytes(value.bytes, value.offset, value.length); // pad to fit for (int i = value.length; i < maxLength; i++) { data.writeByte((sbyte)' '); } SimpleTextUtil.WriteNewline(data); valuesSeen++; Debug.Assert(valuesSeen <= valueCount); } Debug.Assert(valuesSeen == valueCount); foreach (Number ord in docToOrd) { SimpleTextUtil.write(data, ordEncoder.format((long)ord + 1), scratch); SimpleTextUtil.WriteNewline(data); } }