private void PrintCounters(StringBuilder buff, Counters totalCounters, Counters mapCounters , Counters reduceCounters) { // Killed jobs might not have counters if (totalCounters == null) { return; } buff.Append("\nCounters: \n\n"); buff.Append(string.Format("|%1$-30s|%2$-30s|%3$-10s|%4$-10s|%5$-10s|", "Group Name" , "Counter name", "Map Value", "Reduce Value", "Total Value")); buff.Append("\n------------------------------------------" + "---------------------------------------------" ); foreach (string groupName in totalCounters.GetGroupNames()) { CounterGroup totalGroup = totalCounters.GetGroup(groupName); CounterGroup mapGroup = mapCounters.GetGroup(groupName); CounterGroup reduceGroup = reduceCounters.GetGroup(groupName); Format @decimal = new DecimalFormat(); IEnumerator <Counter> ctrItr = totalGroup.GetEnumerator(); while (ctrItr.HasNext()) { Counter counter = ctrItr.Next(); string name = counter.GetName(); string mapValue = @decimal.Format(mapGroup.FindCounter(name).GetValue()); string reduceValue = @decimal.Format(reduceGroup.FindCounter(name).GetValue()); string totalValue = @decimal.Format(counter.GetValue()); buff.Append(string.Format("%n|%1$-30s|%2$-30s|%3$-10s|%4$-10s|%5$-10s", totalGroup .GetDisplayName(), counter.GetDisplayName(), mapValue, reduceValue, totalValue)); } } }
private void OutputStatistics() { DecimalFormat formatPercentage = new DecimalFormat("##.##"); DecimalFormat formatCount = new DecimalFormat("###,###"); long totalCount = _readCount + _writeCount + _syncCount + _seekCount; string totalCountString = formatCount.Format(totalCount); double readCountPercentage = CountPercentage(_readCount, totalCount); string readCountPercentageString = formatPercentage.Format(readCountPercentage); double writeCountPercentage = CountPercentage(_writeCount, totalCount); string writeCountPercentageString = formatPercentage.Format(writeCountPercentage); double syncCountPercentage = CountPercentage(_syncCount, totalCount); string syncCountPercentageString = formatPercentage.Format(syncCountPercentage); double seekCountPercentage = CountPercentage(_seekCount, totalCount); string seekCountPercentageString = formatPercentage.Format(seekCountPercentage); long totalBytes = _readBytes + _writeBytes; string totalBytesString = formatCount.Format(totalBytes); double readBytesPercentage = CountPercentage(_readBytes, totalBytes); string readBytesPercentageString = formatPercentage.Format(readBytesPercentage); double writeBytesPercentage = CountPercentage(_writeBytes, totalBytes); string writeBytesPercentageString = formatPercentage.Format(writeBytesPercentage); string readCountString = formatCount.Format(_readCount); string writeCountString = formatCount.Format(_writeCount); string syncCountString = formatCount.Format(_syncCount); string seekCountString = formatCount.Format(_seekCount); string readBytesString = formatCount.Format(_readBytes); string writeBytesString = formatCount.Format(_writeBytes); PrintHeader(); _out.WriteLine("<tr><td>Reads</td><td></td><td align=\"right\">" + readCountString + "</td><td></td><td align=\"right\">" + readCountPercentageString + "</td><td></td><td align=\"right\">" + readBytesString + "</td><td></td><td align=\"right\">" + readBytesPercentageString + "</td></tr>"); _out.WriteLine("<tr><td>Writes</td><td></td><td align=\"right\">" + writeCountString + "</td><td></td><td align=\"right\">" + writeCountPercentageString + "</td><td></td><td align=\"right\">" + writeBytesString + "</td><td></td><td align=\"right\">" + writeBytesPercentageString + "</td></tr>"); _out.WriteLine("<tr><td>Seeks</td><td></td><td align=\"right\">" + seekCountString + "</td><td></td><td align=\"right\">" + seekCountPercentageString + "</td><td></td><td></td></tr>" ); _out.WriteLine("<tr><td>Syncs</td><td></td><td align=\"right\">" + syncCountString + "</td><td></td><td align=\"right\">" + syncCountPercentageString + "</td><td></td><td></td></tr>" ); _out.WriteLine("<tr><td colspan=\"9\"></td></tr>"); _out.WriteLine("<tr><td>Total</td><td></td><td align=\"right\">" + totalCountString + "</td><td></td><td></td><td></td><td>" + totalBytesString + "</td><td></td></tr>" ); _out.WriteLine("</table>"); double avgBytesPerRead = _readBytes / _readCount; string avgBytesPerReadString = formatCount.Format(avgBytesPerRead); double avgBytesPerWrite = _writeBytes / _writeCount; string avgBytesPerWriteString = formatCount.Format(avgBytesPerWrite); _out.WriteLine("<p>"); _out.WriteLine("Average byte count per read: " + avgBytesPerReadString); _out.WriteLine("<br>"); _out.WriteLine("Average byte count per write: " + avgBytesPerWriteString); _out.WriteLine("</p>"); PrintFooter(); }
public virtual string GetFNumberDescription() { Rational value = _directory.GetRational(XmpDirectory.TagFNumber); if (value == null) { return(null); } return("F" + SimpleDecimalFormatter.Format(value.DoubleValue())); }
/// <summary> /// Processes the audio frame and calculates sound pressure (dB). /// </summary> /// <param name="audioFrame">The audio frame.</param> /// <returns></returns> private int ProcessAudio(short[] audioFrame) { // Compute the RMS value. (Note that this does not remove DC). double rms = 0; for (int i = 0; i < audioFrame.Length; i++) { rms += audioFrame[i] * audioFrame[i]; } rms = Java.Lang.Math.Sqrt(rms / audioFrame.Length); // Compute a smoothed version for less flickering of the display. _rmsSmoothed = _rmsSmoothed * _alpha + (1 - _alpha) * rms; var rmsdB = 20.0 * Java.Lang.Math.Log10(_gain * _rmsSmoothed); DecimalFormat df = new DecimalFormat("##"); DecimalFormat df_fraction = new DecimalFormat("#"); var oneDecimal = (int)(Java.Lang.Math.Round(Java.Lang.Math.Abs(rmsdB * 10))) % 10; var result = string.Format("{0}.{1} dB", df.Format(20 + rmsdB), oneDecimal); var c = Java.Lang.Math.Round((float)(20 + rmsdB)); _listener.ProcessContent(result, ((c > 45) ? AnimationType.KissBack : AnimationType.None)); return(c); }
public static string DecimalToDegreesMinutesSecondsString(double @decimal) { double[] dms = DecimalToDegreesMinutesSeconds(@decimal); DecimalFormat format = new DecimalFormat("0.##"); return(Sharpen.Extensions.StringFormat("%s° %s' %s\"", format.Format(dms[0]), format.Format(dms[1]), format.Format(dms[2]))); }
/// <exception cref="System.IO.IOException"/> public static string GetEvalSummary(string evalScript, string goldFile, string predictFile) { ProcessBuilder process = new ProcessBuilder(evalScript, "all", goldFile, predictFile, "none"); StringOutputStream errSos = new StringOutputStream(); StringOutputStream outSos = new StringOutputStream(); PrintWriter @out = new PrintWriter(outSos); PrintWriter err = new PrintWriter(errSos); SystemUtils.Run(process, @out, err); @out.Close(); err.Close(); string summary = outSos.ToString(); string errStr = errSos.ToString(); if (!errStr.IsEmpty()) { summary += "\nERROR: " + errStr; } Pattern pattern = Pattern.Compile("\\d+\\.\\d\\d\\d+"); DecimalFormat df = new DecimalFormat("#.##"); Matcher matcher = pattern.Matcher(summary); while (matcher.Find()) { string number = matcher.Group(); summary = summary.ReplaceFirst(number, df.Format(double.Parse(number))); } return(summary); }
public override StringBuilder Format(Object number, StringBuilder toAppendTo, CultureInfo culture) { double value; if (Number.IsNumber(number)) { value = double.Parse(number.ToString()); if (Double.IsInfinity(value) || Double.IsNaN(value)) { return(integerFormat.Format(number, toAppendTo, culture)); } } else { // testBug54786 Gets here with a date, so retain previous behaviour return(integerFormat.Format(number, toAppendTo, culture)); } double abs = Math.Abs(value); if (abs >= 1E11 || (abs <= 1E-10 && abs > 0)) { return(scientificFormat.Format(number, toAppendTo, culture)); } else if (Math.Floor(value) == value || abs >= 1E10) { // integer, or integer portion uses all 11 allowed digits return(integerFormat.Format(number, toAppendTo, culture)); } // Non-integers of non-scientific magnitude are formatted as "up to 11 // numeric characters, with the decimal point counting as a numeric // character". We know there is a decimal point, so limit to 10 digits. // https://support.microsoft.com/en-us/kb/65903 //double rounded = new BigDecimal(value).round(TO_10_SF); // calculate round precision int digits = 10; if (Math.Abs(value) > 1) { int len = (int)Math.Log10((int)Math.Abs(value)) + 1; digits -= len; } double rounded = Math.Round(value, digits, MidpointRounding.AwayFromZero); return(decimalFormat.Format(rounded, toAppendTo, culture)); }
/** * 绘制阅读页面 * * @param canvas */ public /*synchronized*/ void onDraw(Canvas canvas) { if (mLines.Size() == 0) { curEndPos = curBeginPos; mLines = pageDown(); } if (mLines.Size() > 0) { int y = marginHeight + (mLineSpace << 1); // 绘制背景 if (mBookPageBg != null) { canvas.DrawBitmap(mBookPageBg, null, rectF, null); } else { canvas.DrawColor(Color.White); } // 绘制标题 canvas.DrawText(chaptersList[currentChapter - 1].title, marginWidth, y, mTitlePaint); y += mLineSpace + mNumFontSize; // 绘制阅读页面文字 for (var i = 0; i < mLines.Size(); i++) { var line = mLines.Get(i).ToString(); y += mLineSpace; if (line.EndsWith("@")) { canvas.DrawText(line.Substring(0, line.Count() - 1), marginWidth, y, mPaint); y += mLineSpace; } else { canvas.DrawText(line, marginWidth, y, mPaint); } y += mFontSize; } // 绘制提示内容 if (batteryBitmap != null) { canvas.DrawBitmap(batteryBitmap, marginWidth + 2, mHeight - marginHeight - ScreenUtils.dpToPxInt(12), mTitlePaint); } float percent = (float)currentChapter * 100 / chapterSize; canvas.DrawText(decimalFormat.Format(percent) + "%", (mWidth - percentLen) / 2, mHeight - marginHeight, mTitlePaint); string mTime = dateFormat.Format(new Date()); canvas.DrawText(mTime, mWidth - marginWidth - timeLen, mHeight - marginHeight, mTitlePaint); // 保存阅读进度 Settings.SaveReadProgress(bookId, currentChapter, curBeginPos, curEndPos); } }
public override String ToString() { if (IsNumber) { return(decimalTextFormat.Format(Value.Value)); } else { return(this.String); } }
public virtual string GetSubjectDistanceDescription() { Rational value = _directory.GetRational(ExifSubIFDDirectory.TagSubjectDistance); if (value == null) { return(null); } DecimalFormat formatter = new DecimalFormat("0.0##"); return(formatter.Format(value.DoubleValue()) + " metres"); }
public virtual string GetFocalLengthDescription() { Rational value = _directory.GetRational(XmpDirectory.TagFocalLength); if (value == null) { return(null); } DecimalFormat formatter = new DecimalFormat("0.0##"); return(formatter.Format(value.DoubleValue()) + " mm"); }
private void SetUiAfterVerification(VerifyResult result) { mProgressDialog.Dismiss(); SetAllButtonEnabledStatus(true); if (result != null) { DecimalFormat formatter = new DecimalFormat("#0.00"); String verificationResult = (result.IsIdentical ? "The same person" : "Different persons") + ". The confidence is " + formatter.Format(result.Confidence); SetInfo(verificationResult); } }
public virtual void PrintF1(Logger logger, bool printF1First) { NumberFormat nf = new DecimalFormat("0.0000"); double r = GetRecall(); double p = GetPrecision(); double f1 = GetF1(); string R = nf.Format(r); string P = nf.Format(p); string F1 = nf.Format(f1); NumberFormat nf2 = new DecimalFormat("00.0"); string Rr = nf2.Format(r * 100); string Pp = nf2.Format(p * 100); string F1f1 = nf2.Format(f1 * 100); if (printF1First) { string str = "F1 = " + F1 + ", P = " + P + " (" + (int)precisionNumSum + "/" + (int)precisionDenSum + "), R = " + R + " (" + (int)recallNumSum + "/" + (int)recallDenSum + ")"; if (scoreType == CorefScorer.ScoreType.Pairwise) { logger.Fine("Pairwise " + str); } else { if (scoreType == CorefScorer.ScoreType.BCubed) { logger.Fine("B cubed " + str); } else { logger.Fine("MUC " + str); } } } else { logger.Fine("& " + Pp + " & " + Rr + " & " + F1f1); } }
public override void Display(bool verbose, PrintWriter pw) { base.Display(verbose, pw); if (doCatLevelEval) { NumberFormat nf = new DecimalFormat("0.00"); ICollection <string> cats = Generics.NewHashSet(); Random rand = new Random(); Sharpen.Collections.AddAll(cats, precisions.KeySet()); Sharpen.Collections.AddAll(cats, recalls.KeySet()); IDictionary <double, string> f1Map = new SortedDictionary <double, string>(); foreach (string cat in cats) { double pnum2 = pnums2.GetCount(cat); double rnum2 = rnums2.GetCount(cat); double prec = precisions2.GetCount(cat) / pnum2; double rec = recalls2.GetCount(cat) / rnum2; double f1 = 2.0 / (1.0 / prec + 1.0 / rec); if (f1.Equals(double.NaN)) { f1 = -1.0; } if (f1Map.Contains(f1)) { f1Map[f1 + (rand.NextDouble() / 1000.0)] = cat; } else { f1Map[f1] = cat; } } pw.Println("============================================================"); pw.Println("Tagging Performance by Category -- final statistics"); pw.Println("============================================================"); foreach (string cat_1 in f1Map.Values) { double pnum2 = pnums2.GetCount(cat_1); double rnum2 = rnums2.GetCount(cat_1); double prec = precisions2.GetCount(cat_1) / pnum2; prec *= 100.0; double rec = recalls2.GetCount(cat_1) / rnum2; rec *= 100.0; double f1 = 2.0 / (1.0 / prec + 1.0 / rec); double oovRate = (lex == null) ? -1.0 : percentOOV.GetCount(cat_1) / percentOOV2.GetCount(cat_1); pw.Println(cat_1 + "\tLP: " + ((pnum2 == 0.0) ? " N/A" : nf.Format(prec)) + "\tguessed: " + (int)pnum2 + "\tLR: " + ((rnum2 == 0.0) ? " N/A" : nf.Format(rec)) + "\tgold: " + (int)rnum2 + "\tF1: " + ((pnum2 == 0.0 || rnum2 == 0.0) ? " N/A" : nf.Format(f1)) + "\tOOV: " + ((lex == null) ? " N/A" : nf.Format(oovRate))); } pw.Println("============================================================"); } }
/** * 转换文件大小 * * @param fileLen 单位B * @return */ public static string formatFileSizeToString(long fileLen) { DecimalFormat df = new DecimalFormat("0.00"); string fileSizestring = ""; if (fileLen < 1024) { fileSizestring = df.Format((double)fileLen) + "B"; } else if (fileLen < 1048576) { fileSizestring = df.Format((double)fileLen / 1024) + "K"; } else if (fileLen < 1073741824) { fileSizestring = df.Format((double)fileLen / 1048576) + "M"; } else { fileSizestring = df.Format((double)fileLen / 1073741824) + "G"; } return(fileSizestring); }
public string GetStringComma(string str) { var _result = ""; if (str.Length > 0) { var value = Java.Lang.Double.ParseDouble(str); var format = new DecimalFormat("###,###"); _result = format.Format(value); } return(_result); }
public override void Display(bool verbose, PrintWriter pw) { NumberFormat nf = new DecimalFormat("0.00"); ICollection <CollinsRelation> cats = Generics.NewHashSet(); Random rand = new Random(); Sharpen.Collections.AddAll(cats, precisions.KeySet()); Sharpen.Collections.AddAll(cats, recalls.KeySet()); IDictionary <double, CollinsRelation> f1Map = new SortedDictionary <double, CollinsRelation>(); foreach (CollinsRelation cat in cats) { double pnum2 = pnums2.GetCount(cat); double rnum2 = rnums2.GetCount(cat); double prec = precisions2.GetCount(cat) / pnum2; //(num > 0.0 ? precision/num : 0.0); double rec = recalls2.GetCount(cat) / rnum2; //(num > 0.0 ? recall/num : 0.0); double f1 = 2.0 / (1.0 / prec + 1.0 / rec); //(num > 0.0 ? f1/num : 0.0); if (f1.Equals(double.NaN)) { f1 = -1.0; } if (f1Map.Contains(f1)) { f1Map[f1 + (rand.NextDouble() / 1000.0)] = cat; } else { f1Map[f1] = cat; } } pw.Println(" Abstract Collins Dependencies -- final statistics"); pw.Println("================================================================================"); foreach (CollinsRelation cat_1 in f1Map.Values) { double pnum2 = pnums2.GetCount(cat_1); double rnum2 = rnums2.GetCount(cat_1); double prec = precisions2.GetCount(cat_1) / pnum2; //(num > 0.0 ? precision/num : 0.0); double rec = recalls2.GetCount(cat_1) / rnum2; //(num > 0.0 ? recall/num : 0.0); double f1 = 2.0 / (1.0 / prec + 1.0 / rec); //(num > 0.0 ? f1/num : 0.0); pw.Println(cat_1 + "\tLP: " + ((pnum2 == 0.0) ? " N/A" : nf.Format(prec)) + "\tguessed: " + (int)pnum2 + "\tLR: " + ((rnum2 == 0.0) ? " N/A" : nf.Format(rec)) + "\tgold: " + (int)rnum2 + "\tF1: " + ((pnum2 == 0.0 || rnum2 == 0.0) ? " N/A" : nf.Format(f1))); } pw.Println("================================================================================"); }
private void PrintQueueInfo(PrintWriter writer, QueueInfo queueInfo) { writer.Write("Queue Name : "); writer.WriteLine(queueInfo.GetQueueName()); writer.Write("\tState : "); writer.WriteLine(queueInfo.GetQueueState()); DecimalFormat df = new DecimalFormat("#.0"); writer.Write("\tCapacity : "); writer.WriteLine(df.Format(queueInfo.GetCapacity() * 100) + "%"); writer.Write("\tCurrent Capacity : "); writer.WriteLine(df.Format(queueInfo.GetCurrentCapacity() * 100) + "%"); writer.Write("\tMaximum Capacity : "); writer.WriteLine(df.Format(queueInfo.GetMaximumCapacity() * 100) + "%"); writer.Write("\tDefault Node Label expression : "); if (null != queueInfo.GetDefaultNodeLabelExpression()) { writer.WriteLine(queueInfo.GetDefaultNodeLabelExpression()); } else { writer.WriteLine(); } ICollection <string> nodeLabels = queueInfo.GetAccessibleNodeLabels(); StringBuilder labelList = new StringBuilder(); writer.Write("\tAccessible Node Labels : "); foreach (string nodeLabel in nodeLabels) { if (labelList.Length > 0) { labelList.Append(','); } labelList.Append(nodeLabel); } writer.WriteLine(labelList.ToString()); }
/// <summary> ///* 转换文件大小单位(b/kb/mb/gb) ** /// </summary> public static string FormetFileSize(this long fileS) { // 转换文件大小 DecimalFormat df = new DecimalFormat("#.00"); string fileSizeString = ""; if (fileS < 1024) { fileSizeString = df.Format((double)fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.Format((double)fileS / 1024) + "K"; } else if (fileS < 1073741824) { fileSizeString = df.Format((double)fileS / 1048576) + "M"; } else { fileSizeString = df.Format((double)fileS / 1073741824) + "G"; } return(fileSizeString); }
private void DisplaySuccess(ML3DFace mLFace) { float[] projectionMatrix = new float[4 * 4]; float[] viewMatrix = new float[4 * 4]; mLFace.Get3DProjectionMatrix(projectionMatrix, 1, 10); mLFace.Get3DViewMatrix(viewMatrix); DecimalFormat decimalFormat = new DecimalFormat("0.00"); string result = "3DFaceEulerX: " + decimalFormat.Format(mLFace.Get3DFaceEulerX()); result += "\n3DFaceEulerY: " + decimalFormat.Format(mLFace.Get3DFaceEulerY()); result += "\n3DFaceEulerZ: " + decimalFormat.Format(mLFace.Get3DFaceEulerZ()); result += "\n3DProjectionMatrix:"; for (int i = 0; i < 16; i++) { result += " " + decimalFormat.Format(projectionMatrix[i]); } result += "\nViewMatrix:"; for (int i = 0; i < 16; i++) { result += " " + decimalFormat.Format(viewMatrix[i]); } this.mTextView.Text = result; }
public virtual void TestVariance(double[] x) { int[] batchSizes = new int[] { 10, 20, 35, 50, 75, 150, 300, 500, 750, 1000, 5000, 10000 }; double[] varResult; PrintWriter file = null; NumberFormat nf = new DecimalFormat("0.000E0"); try { file = new PrintWriter(new FileOutputStream("var.out"), true); } catch (IOException e) { log.Info("Caught IOException outputing List to file: " + e.Message); System.Environment.Exit(1); } foreach (int bSize in batchSizes) { varResult = GetVariance(x, bSize); file.Println(bSize + "," + nf.Format(varResult[0]) + "," + nf.Format(varResult[1]) + "," + nf.Format(varResult[2]) + "," + nf.Format(varResult[3])); log.Info("Batch size of: " + bSize + " " + varResult[0] + "," + nf.Format(varResult[1]) + "," + nf.Format(varResult[2]) + "," + nf.Format(varResult[3])); } file.Close(); }
private string GetEVDescription(int tagType) { int[] values = _directory.GetIntArray(tagType); if (values == null) { return(null); } if (values.Length < 3 || values[2] == 0) { return(null); } DecimalFormat decimalFormat = new DecimalFormat("0.##"); double ev = values[0] * values[1] / (double)values[2]; return(decimalFormat.Format(ev) + " EV"); }
/// <summary> /// Display result in TextView /// </summary> private void DisplaySuccess(MLFace mFace) { DecimalFormat decimalFormat = new DecimalFormat("0.000"); string result = "Left eye open Probability: " + decimalFormat.Format(mFace.Features.LeftEyeOpenProbability); result += "\nRight eye open Probability: " + decimalFormat.Format(mFace.Features.RightEyeOpenProbability); result += "\nMoustache Probability: " + decimalFormat.Format(mFace.Features.MoustacheProbability); result += "\nGlass Probability: " + decimalFormat.Format(mFace.Features.SunGlassProbability); result += "\nHat Probability: " + decimalFormat.Format(mFace.Features.HatProbability); result += "\nAge: " + mFace.Features.Age; result += "\nGender: " + ((mFace.Features.SexProbability > 0.5f) ? "Female" : "Male"); result += "\nRotationAngleY: " + decimalFormat.Format(mFace.RotationAngleY); result += "\nRotationAngleZ: " + decimalFormat.Format(mFace.RotationAngleZ); result += "\nRotationAngleX: " + decimalFormat.Format(mFace.RotationAngleX); this.mTextView.Text = (result); }
public ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { if (args.Length != 1 && args.Length != 2) { return(ErrorEval.VALUE_INVALID); } try { double val = singleOperandEvaluate(args[0], srcRowIndex, srcColumnIndex); double d1 = args.Length == 1 ? 2.0 : singleOperandEvaluate(args[1], srcRowIndex, srcColumnIndex); // second arg converts to int by truncating toward zero int nPlaces = (int)d1; if (nPlaces > 127) { return(ErrorEval.VALUE_INVALID); } if (nPlaces < 0) { d1 = Math.Abs(d1); double temp = val / Math.Pow(10, d1); temp = Math.Round(temp, 0); val = temp * Math.Pow(10, d1); } StringBuilder decimalPlacesFormat = new StringBuilder(); if (nPlaces > 0) { decimalPlacesFormat.Append('.'); } for (int i = 0; i < nPlaces; i++) { decimalPlacesFormat.Append('0'); } StringBuilder decimalFormatString = new StringBuilder(); decimalFormatString.Append("$#,##0").Append(decimalPlacesFormat) .Append(";($#,##0").Append(decimalPlacesFormat).Append(')'); DecimalFormat df = new DecimalFormat(decimalFormatString.ToString()); return(new StringEval(df.Format(val))); } catch (EvaluationException e) { return(e.GetErrorEval()); } }
public static String FormatBytes(long bytes) { long inputBytes = bytes; BigDecimal bigBytes = new BigDecimal(bytes); NumberFormat numberFormat = new DecimalFormat(); numberFormat.MaximumFractionDigits = 1; int index; for (index = 0; index < BYTES_UNIT_LIST.Length; index++) { if (inputBytes < CONVERSION_BASE) { break; } inputBytes /= CONVERSION_BASE; } return(numberFormat.Format(bigBytes.Divide(new BigDecimal(BASE_LIST[index]))) + " " + BYTES_UNIT_LIST[index]); }
public virtual void ArrayToFile(double[] thisArray, string fileName) { PrintWriter file = null; NumberFormat nf = new DecimalFormat("0.000E0"); try { file = new PrintWriter(new FileOutputStream(fileName), true); } catch (IOException e) { log.Info("Caught IOException outputing List to file: " + e.Message); System.Environment.Exit(1); } foreach (double element in thisArray) { file.Print(nf.Format(element) + " "); } file.Close(); }
/// <summary> /// Formats a number or date cell, be that a real number, or the /// answer to a formula /// </summary> /// <param name="cell">The cell.</param> /// <param name="value">The value.</param> /// <returns></returns> private String FormatNumberDateCell(CellValueRecordInterface cell, double value) { // Get the built in format, if there is one int formatIndex = ft.GetFormatIndex(cell); String formatString = ft.GetFormatString(cell); if (formatString == null) { return(value.ToString(CultureInfo.InvariantCulture)); } else { // Is it a date? if (Npoi.Core.SS.UserModel.DateUtil.IsADateFormat(formatIndex, formatString) && Npoi.Core.SS.UserModel.DateUtil.IsValidExcelDate(value)) { // Java wants M not m for month formatString = formatString.Replace('m', 'M'); // Change \- into -, if it's there formatString = formatString.Replace("\\\\-", "-"); // Format as a date DateTime d = Npoi.Core.SS.UserModel.DateUtil.GetJavaDate(value, false); SimpleDateFormat df = new SimpleDateFormat(formatString); return(df.Format(d, CultureInfo.CurrentCulture)); } else { if (formatString == "General") { // Some sort of wierd default return(value.ToString(CultureInfo.InvariantCulture)); } // Format as a number DecimalFormat df = new DecimalFormat(formatString); return(df.Format(value, CultureInfo.CurrentCulture)); } } }
/// <summary> /// Lists the applications matching the given application Types And application /// States present in the Resource Manager /// </summary> /// <param name="appTypes"/> /// <param name="appStates"/> /// <exception cref="Org.Apache.Hadoop.Yarn.Exceptions.YarnException"/> /// <exception cref="System.IO.IOException"/> private void ListApplications(ICollection <string> appTypes, EnumSet <YarnApplicationState > appStates) { PrintWriter writer = new PrintWriter(new OutputStreamWriter(sysout, Sharpen.Extensions.GetEncoding ("UTF-8"))); if (allAppStates) { foreach (YarnApplicationState appState in YarnApplicationState.Values()) { appStates.AddItem(appState); } } else { if (appStates.IsEmpty()) { appStates.AddItem(YarnApplicationState.Running); appStates.AddItem(YarnApplicationState.Accepted); appStates.AddItem(YarnApplicationState.Submitted); } } IList <ApplicationReport> appsReport = client.GetApplications(appTypes, appStates); writer.WriteLine("Total number of applications (application-types: " + appTypes + " and states: " + appStates + ")" + ":" + appsReport.Count); writer.Printf(ApplicationsPattern, "Application-Id", "Application-Name", "Application-Type" , "User", "Queue", "State", "Final-State", "Progress", "Tracking-URL"); foreach (ApplicationReport appReport in appsReport) { DecimalFormat formatter = new DecimalFormat("###.##%"); string progress = formatter.Format(appReport.GetProgress()); writer.Printf(ApplicationsPattern, appReport.GetApplicationId(), appReport.GetName (), appReport.GetApplicationType(), appReport.GetUser(), appReport.GetQueue(), appReport .GetYarnApplicationState(), appReport.GetFinalApplicationStatus(), progress, appReport .GetOriginalTrackingUrl()); } writer.Flush(); }
public double PorcentajeVuelos(DtoRPorcentaje dto) { double porcentaje = 0; using (AlasPUMEntities context = new AlasPUMEntities()) { int vuelos = context.Vuelo.Select(s => s).Count(); List <Vuelo> colVuelo = context.Vuelo.Where(w => w.dtLlegada == dto.fechaInicio && w.dtSalida == dto.fechaFin).ToList(); int eso = colVuelo.Count(); porcentaje = (vuelos * eso) / 100; } DecimalFormat df = new DecimalFormat("#.00"); string total = df.Format(porcentaje); porcentaje = double.Parse(total); return(porcentaje); }
// no public constructor; use static methods instead public override string ToString() { NumberFormat nf = new DecimalFormat("0.0##E0"); IList <E> keyList = new List <E>(KeySet()); keyList.Sort(null); StringBuilder sb = new StringBuilder(); sb.Append("["); for (int i = 0; i < NumEntriesInString; i++) { if (keyList.Count <= i) { break; } E o = keyList[i]; double prob = ProbabilityOf(o); sb.Append(o).Append(":").Append(nf.Format(prob)).Append(" "); } sb.Append("]"); return(sb.ToString()); }
/// <summary> /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or /// node object to an RDF resource. /// </summary> /// <remarks> /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or /// node object to an RDF resource. /// </remarks> /// <param name="item">the JSON-LD value or node object.</param> /// <param name="namer">the UniqueNamer to use to assign blank node names.</param> /// <returns>the RDF literal or RDF resource.</returns> private static JObject ObjectToRDF(JToken item, UniqueNamer namer) { JObject @object = new JObject(); // convert value object to RDF if (JsonLdUtils.IsValue(item)) { @object["type"] = "literal"; JToken value = ((JObject)item)["@value"]; JToken datatype = ((JObject)item)["@type"]; // convert to XSD datatypes as appropriate if (value.Type == JTokenType.Boolean || value.Type == JTokenType.Float || value.Type == JTokenType.Integer ) { // convert to XSD datatype if (value.Type == JTokenType.Boolean) { @object["value"] = value.ToString(); @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdBoolean : datatype; } else { if (value.Type == JTokenType.Float) { // canonical double representation @object["value"] = string.Format("{0:0.0###############E0}", (double)value); @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdDouble : datatype; } else { DecimalFormat df = new DecimalFormat("0"); @object["value"] = df.Format((int)value); @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdInteger : datatype; } } } else { if (((IDictionary<string, JToken>)item).ContainsKey("@language")) { @object["value"] = value; @object["datatype"] = datatype.IsNull() ? JSONLDConsts.RdfLangstring : datatype; @object["language"] = ((IDictionary<string, JToken>)item)["@language"]; } else { @object["value"] = value; @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdString : datatype; } } } else { // convert string/node object to RDF string id = JsonLdUtils.IsObject(item) ? (string)((JObject)item )["@id"] : (string)item; if (id.IndexOf("_:") == 0) { @object["type"] = "blank node"; @object["value"] = namer.GetName(id); } else { @object["type"] = "IRI"; @object["value"] = id; } } return @object; }
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { double s0; String s1; try { s0 = TextFunction.EvaluateDoubleArg(arg0, srcRowIndex, srcColumnIndex); s1 = TextFunction.EvaluateStringArg(arg1, srcRowIndex, srcColumnIndex); } catch (EvaluationException e) { return e.GetErrorEval(); } if (Regex.Match(s1, "[y|m|M|d|s|h]+").Success) { //may be datetime string ValueEval result = TryParseDateTime(s0, s1); if (result != ErrorEval.VALUE_INVALID) return result; } //The regular expression needs ^ and $. if (Regex.Match(s1, @"^[\d,\#,\.,\$,\,]+$").Success) { //TODO: simulate DecimalFormat class in java. FormatBase formatter = new DecimalFormat(s1); return new StringEval(formatter.Format(s0)); } else if (s1.IndexOf("/", StringComparison.Ordinal) == s1.LastIndexOf("/", StringComparison.Ordinal) && s1.IndexOf("/", StringComparison.Ordinal) >= 0 && !s1.Contains("-")) { double wholePart = Math.Floor(s0); double decPart = s0 - wholePart; if (wholePart * decPart == 0) { return new StringEval("0"); } String[] parts = s1.Split(' '); String[] fractParts; if (parts.Length == 2) { fractParts = parts[1].Split('/'); } else { fractParts = s1.Split('/'); } if (fractParts.Length == 2) { double minVal = 1.0; double currDenom = Math.Pow(10, fractParts[1].Length) - 1d; double currNeum = 0; for (int i = (int)(Math.Pow(10, fractParts[1].Length) - 1d); i > 0; i--) { for (int i2 = (int)(Math.Pow(10, fractParts[1].Length) - 1d); i2 > 0; i2--) { if (minVal >= Math.Abs((double)i2 / (double)i - decPart)) { currDenom = i; currNeum = i2; minVal = Math.Abs((double)i2 / (double)i - decPart); } } } FormatBase neumFormatter = new DecimalFormat(fractParts[0]); FormatBase denomFormatter = new DecimalFormat(fractParts[1]); if (parts.Length == 2) { FormatBase wholeFormatter = new DecimalFormat(parts[0]); String result = wholeFormatter.Format(wholePart) + " " + neumFormatter.Format(currNeum) + "/" + denomFormatter.Format(currDenom); return new StringEval(result); } else { String result = neumFormatter.Format(currNeum + (currDenom * wholePart)) + "/" + denomFormatter.Format(currDenom); return new StringEval(result); } } else { return ErrorEval.VALUE_INVALID; } } else { return TryParseDateTime(s0, s1); } }
private void ShowNotification() { Log.Debug(logTag, "GpsService.ShowNotification called"); Intent intent = new Intent(this, typeof(MainActivity)); PendingIntent pendingintent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent); DecimalFormat decimalformat = new DecimalFormat("###.######"); ; string s = "Waiting for next location. Please wait..."; if (Session.hasValidLocation()) { s = String.Format("Lat {0} Lon {1}", decimalformat.Format(Session.getCurrentLatitude()), decimalformat.Format(Session.getCurrentLongitude())); } // Build the notification NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .SetAutoCancel(true) // dismiss the notification from the notification area when the user clicks on it //.SetContentIntent(pendingintent) // start up this activity when the user clicks the intent. .SetContentTitle("in1go Tracker running...") // Set the title .SetSmallIcon(Resource.Drawable.icon) // This is the icon to display .SetContentText(s); // the message to display. gpsNotifyManager.Notify(NOTIFICATION_ID, builder.Build()); StartForeground(NOTIFICATION_ID, builder.Build()); }
/// <summary> /// Formats a number or date cell, be that a real number, or the /// answer to a formula /// </summary> /// <param name="cell">The cell.</param> /// <param name="value">The value.</param> /// <returns></returns> private String FormatNumberDateCell(CellValueRecordInterface cell, double value) { // Get the built in format, if there is one int formatIndex = ft.GetFormatIndex(cell); String formatString = ft.GetFormatString(cell); if (formatString == null) { return value.ToString(CultureInfo.InvariantCulture); } else { // Is it a date? if (LF.Utils.NPOI.SS.UserModel.DateUtil.IsADateFormat(formatIndex, formatString) && LF.Utils.NPOI.SS.UserModel.DateUtil.IsValidExcelDate(value)) { // Java wants M not m for month formatString = formatString.Replace('m', 'M'); // Change \- into -, if it's there formatString = formatString.Replace("\\\\-", "-"); // Format as a date DateTime d = LF.Utils.NPOI.SS.UserModel.DateUtil.GetJavaDate(value, false); SimpleDateFormat df = new SimpleDateFormat(formatString); return df.Format(d); } else { if (formatString == "General") { // Some sort of wierd default return value.ToString(CultureInfo.InvariantCulture); } // Format as a number DecimalFormat df = new DecimalFormat(formatString); return df.Format(value); } } }