System.Math.Round(double, int)

Here are the examples of the csharp api System.Math.Round(double, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1369 Examples 7

19 View Source File : Angle2D.cs
License : GNU General Public License v3.0
Project Creator : anotak

public static float DoomToReal(int doomangle)
		{
			return (float)Math.Round(Normalized(DegToRad((float)(doomangle + 90))), 4);
		}

19 View Source File : ExcelDrawingBase.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal int GetPixelWidth()
        {
            ExcelWorksheet ws = _drawings.Worksheet;
            decimal mdw = ws.Workbook.MaxFontWidth;

            int pix = -From.ColumnOff / EMU_PER_PIXEL;
            for (int col = From.Column + 1; col <= To.Column; col++)
            {
                pix += (int)decimal.Truncate(((256 * GetColumnWidth(col) + decimal.Truncate(128 / (decimal)mdw)) / 256) * mdw);
            }
            pix += Convert.ToInt32(Math.Round(Convert.ToDouble(To.ColumnOff) / EMU_PER_PIXEL,0));
            return pix;
        }

19 View Source File : DoubleExtension.cs
License : MIT License
Project Creator : AlphaYu

public static double Round(this double a, int digits) => Math.Round(a, digits);

19 View Source File : ParetoChartType.cs
License : MIT License
Project Creator : AngeloCresta

void MakeParetoChart(Chart chart, string srcSeriesName, string destSeriesName)
		{

			// get name of the ChartAre of the source series
			string strChartArea = chart.Series[srcSeriesName].ChartArea;

			// ensure the source series is a column chart type
			chart.Series[srcSeriesName].ChartType = SeriesChartType.Column;

			// sort the data in the series to be by values in descending order
			chart.DataManipulator.Sort(PointSortOrder.Descending, srcSeriesName);

			// find the total of all points in the source series
			double total = 0.0;
			foreach (DataPoint pt in chart.Series[srcSeriesName].Points)
				total += pt.YValues[0];

			// set the max value on the primary axis to total
			chart.ChartAreas[strChartArea].AxisY.Maximum = total;

			// create the destination series and add it to the chart
			Series destSeries = new Series(destSeriesName);
			chart.Series.Add(destSeries);

			// ensure the destination series is a Line or Spline chart type
			destSeries.ChartType = SeriesChartType.Line;

			destSeries.BorderWidth = 3;

			// replacedign the series to the same chart area as the column chart
			destSeries.ChartArea = chart.Series[srcSeriesName].ChartArea;

			// replacedign this series to use the secondary axis and set it maximum to be 100%
			destSeries.YAxisType = AxisType.Secondary;
			chart.ChartAreas[strChartArea].AxisY2.Maximum = 100; 

			// locale specific percentage format with no decimals
			chart.ChartAreas[strChartArea].AxisY2.LabelStyle.Format = "P0";

			// turn off the end point values of the primary X axis
			chart.ChartAreas[strChartArea].AxisX.LabelStyle.IsEndLabelVisible = false;

			// for each point in the source series find % of total and replacedign to series
			double percentage = 0.0;

			foreach(DataPoint pt in chart.Series[srcSeriesName].Points)
			{
				percentage += (pt.YValues[0] / total * 100.0);
				destSeries.Points.Add(Math.Round(percentage,2));
			}
		}

19 View Source File : TestDMInput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

double GetFirstParameterDouble(string value, string MessageHelp)
        {
            var commands = value.Split(' ');
            double Result;
            try
            {
                Result = double.Parse(commands[0]);
                Result = Math.Round(Result, 1);
            }
            catch (Exception)
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
                return 0xffff;
            }
            return Result;
        }

19 View Source File : FileAttachmentControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private static string BytesToString(long byteCount)
        {
            string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; // Longs run out around EB
            if (byteCount == 0)
            {
                return "0" + suf[0];
            }

            long bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return (Math.Sign(byteCount) * num).ToString() + " " + suf[place];
        }

19 View Source File : ProgressCircle.xaml.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void Render()
        {
            if (this.Visibility == Visibility.Collapsed)
            {
                return;
            }

            // 大きさを設定する
            if (this.ForeCircle.Radius != this.Radius) this.ForeCircle.Radius = this.Radius;
            if (this.ForeCircle.StrokeThickness != this.Thickness) this.ForeCircle.StrokeThickness = this.Thickness;

            if (this.Visibility == Visibility.Hidden)
            {
                return;
            }

            // エフェクトを設定する
            var effect = this.ForeCircle.Effect as DropShadowEffect;
            if (effect != null)
            {
                if (this.BlurRadius > 0)
                {
                    effect.BlurRadius = this.BlurRadius;
                    effect.Opacity = this.Opacity;
                }
                else
                {
                    effect.BlurRadius = 0;
                    effect.Opacity = 0;
                }
            }

            // 背景色と前景色を設定する
            if (this.Fill is SolidColorBrush fill)
            {
                if (this.ForeCircle.Stroke != fill)
                {
                    this.BackCircle.Stroke =
                        this.IsDarkBackground ?
                        fill.Color.ChangeBrightness(ToDarkRatio).ToBrush() :
                        fill.Color.ChangeBrightness(ToLightRatio).ToBrush();

                    this.ForeCircle.Stroke = fill;
                }
            }
            else
            {
                this.BackCircle.Stroke = Brushes.Black;
                this.ForeCircle.Stroke = this.Fill;
            }

            // 枠の色を設定する
            if (this.Stroke is SolidColorBrush stroke)
            {
                if (this.ForeCircle.Stroke == stroke)
                {
                    this.StrokeCircle.Stroke = this.BackCircle.Stroke;
                }
                else
                {
                    this.StrokeCircle.Stroke = stroke;
                }
            }
            else
            {
                this.StrokeCircle.Stroke = this.Stroke;
            }

            // 反転?
            this.CircleScale.ScaleX = this.IsCCW ? -1 : 1;

            var progress = this.Progress;

            if (this.Radius == 0 ||
                this.Thickness == 0)
            {
                progress = 0;
            }

            // サークルの角度を算出する
            var angle = !this.IsReverse ?
                (360.1 * progress) - 90 :
                (360.1 - (360.1 * progress)) - 90;

            angle = Math.Round(angle, 3);

            // ForeCircleを描画する
            this.ForeCircle.StartAngle = -90;
            this.ForeCircle.EndAngle = angle;

            // StrokeCircleを描画する
            this.StrokeCircle.StartAngle = -90;
            this.StrokeCircle.EndAngle = this.IsStrokeBackground ? 270.1 : angle;
        }

19 View Source File : DrawGraphics.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence

private static void EffectColourScheme(_3Matrix rotationResult, Domain.ContainerObjects.Point<_3Vector, _3Vector> pointPair, out _3Vector pointA, out _3Vector pointB, out Pen pen)
        {
            double blue = 0;
            double red = 0;
            pointA = rotationResult.MultiplyByVector(pointPair.Xval);
            pointB = rotationResult.MultiplyByVector(pointPair.Yval);
            var gradient = (pointPair.Yval.c - pointPair.Xval.c) / (pointPair.Yval.a - pointPair.Xval.a);
            if (Math.Abs(gradient) > 1)
            {
                if (Math.Abs(gradient) > 5000)
                {
                    gradient = 5000;
                }
                blue = 255 * (Math.Abs(gradient) / 5000);
            }

            if (Math.Abs(gradient) < 1)
            {
                if (gradient == 0)
                {
                    gradient = 0.001;
                }
                //19.60
                red = 255 * (1 - Math.Abs(gradient));
            }

            pen = new Pen(Color.FromArgb((int)Math.Round(red, 0), 100, (int)Math.Round(blue, 0)));
        }

19 View Source File : ExcelNumberFormatXml.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal string FormatFraction(double d)
            {
                int numerator, denomerator;

                int intPart = (int)d;

                string[] fmt = FractionFormat.Split('/');

                int fixedDenominator;
                if (!int.TryParse(fmt[1], out fixedDenominator))
                {
                    fixedDenominator = 0;
                }
                
                if (d == 0 || double.IsNaN(d))
                {
                    if (fmt[0].Trim() == "" && fmt[1].Trim() == "")
                    {
                        return new string(' ', FractionFormat.Length);
                    }
                    else
                    {
                        return 0.ToString(fmt[0]) + "/" + 1.ToString(fmt[0]);
                    }
                }

                int maxDigits = fmt[1].Length;
                string sign = d < 0 ? "-" : "";
                if (fixedDenominator == 0)
                {
                    List<double> numerators = new List<double>() { 1, 0 };
                    List<double> denominators = new List<double>() { 0, 1 };

                    if (maxDigits < 1 && maxDigits > 12)
                    {
                        throw (new ArgumentException("Number of digits out of range (1-12)"));
                    }

                    int maxNum = 0;
                    for (int i = 0; i < maxDigits; i++)
                    {
                        maxNum += 9 * (int)(Math.Pow((double)10, (double)i));
                    }

                    double divRes = 1 / ((double)Math.Abs(d) - intPart);
                    double result, prevResult = double.NaN;
                    int listPos = 2, index = 1;
                    while (true)
                    {
                        index++;
                        double intDivRes = Math.Floor(divRes);
                        numerators.Add((intDivRes * numerators[index - 1] + numerators[index - 2]));
                        if (numerators[index] > maxNum)
                        {
                            break;
                        }

                        denominators.Add((intDivRes * denominators[index - 1] + denominators[index - 2]));

                        result = numerators[index] / denominators[index];
                        if (denominators[index] > maxNum)
                        {
                            break;
                        }
                        listPos = index;

                        if (result == prevResult) break;

                        if (result == d) break;

                        prevResult = result;

                        divRes = 1 / (divRes - intDivRes);  //Rest
                    }
                    
                    numerator = (int)numerators[listPos];
                    denomerator = (int)denominators[listPos];
                }
                else
                {
                    numerator = (int)Math.Round((d - intPart) / (1D / fixedDenominator), 0);
                    denomerator = fixedDenominator;
                }
                if (numerator == denomerator || numerator==0)
                {
                    if(numerator == denomerator) intPart++;
                    return sign + intPart.ToString(NetFormat).Replace("?", new string(' ', FractionFormat.Length));
                }
                else if (intPart == 0)
                {
                    return sign + FmtInt(numerator, fmt[0]) + "/" + FmtInt(denomerator, fmt[1]);
                }
                else
                {
                    return sign + intPart.ToString(NetFormat).Replace("?", FmtInt(numerator, fmt[0]) + "/" + FmtInt(denomerator, fmt[1]));
                }
            }

19 View Source File : Program.cs
License : MIT License
Project Creator : afaniuolo

static void Main(string[] args)
		{
			// Start watch
			var stopwatch = Stopwatch.StartNew();

			// Init Console App Parameters
			InitializeAppParameters(args);

			// Render Help message if needed
			if (help)
			{
				Console.WriteLine();
				Console.WriteLine("  Executes the conversion and migration of items and data from Sitecore WFFM source to Sitecore Experience Forms destination.");
				Console.WriteLine();
				Console.WriteLine("  WFFM.ConversionTool.exe [-convert] [-nodata]");
				Console.WriteLine();
				Console.WriteLine("  -convert             to convert and migrate items and data in destination databases.");
				Console.WriteLine("  -convert -nodata     to convert and migrate only items in destination database.");
				Console.WriteLine("  -convert -onlydata   to convert and migrate only forms data in destination database.");
				Console.WriteLine();
				return;
			}

			// Init Console output
			System.Console.WriteLine();
			System.Console.WriteLine("  ***********************************************************************");
			System.Console.WriteLine("  *                                                                     *");
			System.Console.WriteLine("  *                 WFFM Conversion Tool - v1.5.0                       *");
			System.Console.WriteLine("  *                                                                     *");
			System.Console.WriteLine("  ***********************************************************************");
			System.Console.WriteLine();

			// Metadata Validation
			var metadataValidator = container.GetInstance<MetadataValidator>();
			if (!metadataValidator.Validate()) return;

			// AppSettings Validation
			var appSettingsValidator = container.GetInstance<AppSettingsValidator>();
			if (!appSettingsValidator.Validate()) return;

			// Connection Strings Testing
			var dbConnectionStringValidator = container.GetInstance<DbConnectionStringValidator>();
			if (!dbConnectionStringValidator.Validate()) return;

			// Get AppSettings instance
			var appSettings = container.GetInstance<AppSettings>();
			if (convert)
			{
				appSettings.enableOnlyreplacedysisByDefault = false;
			}

			if (!onlydata)
			{
				// Read and replacedyze source data
				var formProcessor = container.GetInstance<FormProcessor>();
				formProcessor.ConvertForms();
			}

			if (convert && !nodata)
			{
				// Convert & Migrate data
				var dataMigrator = container.GetInstance<DataMigrator>();
				dataMigrator.MigrateData();
			}

			// Stop watch
			System.Console.WriteLine();
			System.Console.WriteLine($"  Execution completed in {Math.Round(stopwatch.Elapsed.TotalMinutes, 2)} minutes.");
			System.Console.WriteLine();
		}

19 View Source File : MovingP2QuantileEstimatorTests.cs
License : MIT License
Project Creator : AndreyAkinshin

[Theory]
        [InlineData(1000, 51, 0.5, 0.2, 0.7)]
        public void MovingP2QuantileEstimatorMedianTest1(int n, int windowSize, double probability, double relativeThreshold,
            double minSuccessRate)
        {
            var random = new Random();
            double[] data = new double[n];
            for (int i = 0; i < n; i++)
            {
                data[i] = 10 + Math.Sin(i / 20.0) * 5 + random.NextDouble(-3, 3);
                if (random.Next(10) == 0 && i > windowSize / 2)
                    data[i] += random.Next(20, 50);
                data[i] = Math.Round(data[i], 3);
            }

            var mp2Estimator = new MovingP2QuantileEstimator(probability, windowSize);
            var phEstimator = new ParreplacedioningHeapsMovingQuantileEstimator(windowSize, probability);

            var outputBuilder = new StringBuilder();
            outputBuilder.AppendLine("i,data,estimation,true");
            int successCounter = 0;
            for (int i = 0; i < n; i++)
            {
                mp2Estimator.Add(data[i]);
                phEstimator.Add(data[i]);

                double mp2Estimation = mp2Estimator.GetQuantile();
                double trueValue = phEstimator.GetQuantile();

                if (Math.Abs(mp2Estimation - trueValue) / trueValue < relativeThreshold)
                    successCounter++;

                outputBuilder.Append(i);
                outputBuilder.Append(',');
                outputBuilder.Append(data[i].ToString(TestCultureInfo.Instance));
                outputBuilder.Append(',');
                outputBuilder.Append(mp2Estimation.ToString(TestCultureInfo.Instance));
                outputBuilder.Append(',');
                outputBuilder.Append(trueValue.ToString(TestCultureInfo.Instance));
                outputBuilder.AppendLine();
            }
            double actualSuccessRate = successCounter * 1.0 / n;

            output.WriteLine("ExpectedSuccessRate = " + minSuccessRate.ToString(TestCultureInfo.Instance));
            output.WriteLine("ActualSuccessRate   = " + actualSuccessRate.ToString(TestCultureInfo.Instance));
            output.WriteLine();
            output.WriteLine(outputBuilder.ToString());

            replacedert.True(successCounter * 1.0 / n > minSuccessRate);
        }

19 View Source File : NumberBox.cs
License : MIT License
Project Creator : amwx

private void UpdateTextToValue()
        {
            if (_textBox == null)
                return;

            string newText = "";

            if (!double.IsNaN(_value))
            {
                // Round to 12 digits (standard .net rounding per WinUI in the NumberBox source)
                // We do this to prevent weirdness from floating point imprecision
                var newValue = Math.Round(_value, 12);
				if (SimpleNumberFormat != null)
				{
					newText = newValue.ToString(_simpleFormat);
				}
                else if (NumberFormatter != null)
                {
                    newText = NumberFormatter(newValue);
                }
                else
                {
                    newText = newValue.ToString();
                }
            }

            _textBox.Text = newText;

            try
            {
                _textUpdating = true;
                Text = newText;
            }
            finally
            {
                _textUpdating = false;
                MoveCaretToTextEnd(); //Add this
            }
        }

19 View Source File : RoundingSettings.cs
License : MIT License
Project Creator : AlenToma

public double Round(double value)
        {
            var isNegative = (RoundingConventionMethod != null && RoundingConventionMethod != RoundingConvention.Normal) && value < 0;

            if (RoundingConventionMethod != null && isNegative)
                value = Math.Abs(value); // its very importend to have a positive number when using floor/Ceiling
            switch (RoundingConventionMethod)
            {
                case null:
                case RoundingConvention.Normal:
                    value = Math.Round(value, this.RowDecimalRoundTotal);
                    break;
                case RoundingConvention.RoundUpp:
                {
                    var adjustment = Math.Pow(10, RowDecimalRoundTotal);
                    value = (Math.Ceiling(value * adjustment) / adjustment);
                }
                    break;
                case RoundingConvention.RoundDown:
                {
                    var adjustment = Math.Pow(10, RowDecimalRoundTotal);
                    value = (Math.Floor(value * adjustment) / adjustment);
                }
                    break;
                case RoundingConvention.None:
                {
                    var adjustment = Math.Pow(10, RowDecimalRoundTotal);
                    value = (Math.Truncate(value * adjustment) / adjustment);
                }
                    break;
            }

            if (isNegative)
                value = -value;

            return value;
        }

19 View Source File : AnimationSliderTooltipConverter.xaml.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var rate = System.Convert.ToDouble(value);
            rate = Math.Round(rate, 1);
            return String.Format("Playback Rate: {0}x", rate);
        }

19 View Source File : HeatMapExampleView.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IDataSeries CreateSeries(int index, int width, int height, double cpMin, double cpMax)
        {
            var seed = SeriesAnimationBase.GlobalEnableAnimations ? (Environment.TickCount << index) : 0;
            var random = new Random(seed);
            double angle = Math.Round(Math.PI * 2 * index, 3) / seriesPerPeriod;
            int w = width, h = height;
            var data = new double[h, w];
            for (int x = 0; x < w; x++)
                for (int y = 0; y < h; y++)
                {
                    var v = (1 + Math.Round(Math.Sin(x * 0.04 + angle), 3)) * 50 + (1 + Math.Round(Math.Sin(y * 0.1 + angle), 3)) * 50 * (1 + Math.Round(Math.Sin(angle * 2), 3));
                    var cx = w / 2; var cy = h / 2;
                    var r = Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
                    var exp = Math.Max(0, 1 - r * 0.008);
                    var zValue = (v * exp + random.NextDouble() * 50);
                    data[y, x] = (zValue > cpMax) ? cpMax : zValue;
                }
            return new UniformHeatmapDataSeries<int, int, double>(data, 0, 1, 0, 1);
        }

19 View Source File : NavMeshExporter.cs
License : MIT License
Project Creator : AnotherEnd15

private static void InitFace(Face face)
        {
            face.centerX = 0;
            face.centerZ = 0;
            var vertCount = face.verts.Count;
            foreach (var vert in face.verts)
            {
                face.centerX += vert.x;
                face.centerZ += vert.z;
                if (!vertFaceDict.ContainsKey(vert))
                {
                    vertFaceDict.Add(vert, face);
                    vertList.Add(vert);
                }
            }

            face.centerX /= vertCount;
            face.centerZ /= vertCount;
            if (face.normalB != 0)
            {
                face.normalX = (float) Math.Round(face.normalA / face.normalB, 6);
                face.normalZ = (float) Math.Round(face.normalC / face.normalB, 6);
            }

            for (int i = 0, n = vertCount - 1; i <= n; i++)
            {
                var firstVert = face.verts[i];
                var secondVert = face.verts[i == n? 0 : i + 1];
                if (!vertPairDict.ContainsKey(firstVert))
                {
                    vertPairDict.Add(firstVert, new Dictionary<Vert, Pair>());
                }

                if (!vertPairDict.ContainsKey(secondVert))
                {
                    vertPairDict.Add(secondVert, new Dictionary<Vert, Pair>());
                }

                if (!vertPairDict[secondVert].ContainsKey(firstVert))
                {
                    var pair = new Pair();
                    pair.firstEdgeFace = face;
                    pair.firstEdgeIndex = i;
                    vertPairDict[firstVert][secondVert] = pair;
                }
                else
                {
                    var pair = vertPairDict[secondVert][firstVert];
                    pair.centerX = (firstVert.x + secondVert.x) / 2;
                    pair.centerZ = (firstVert.z + secondVert.z) / 2;
                    pair.secondEdgeFace = face;
                    pair.secondEdgeIndex = i;
                    pairList.Add(pair);
                }
            }

            faceList.Add(face);
        }

19 View Source File : Updater.xaml.cs
License : MIT License
Project Creator : Alkl58

private async Task DownloadBin(string DownloadURL, string PathToFile)
        {
            // Downloads the archive provided in the Link
            try
            {
                WebClient webClient = new WebClient();
                webClient.DownloadProgressChanged += (s, e) =>
                {
                    ProgressBar.Dispatcher.Invoke(() => ProgressBar.Value = e.ProgressPercentage);
                    LabelProgressBar.Dispatcher.Invoke(() => LabelProgressBar.Content = Math.Round(e.BytesReceived / 1024f / 1024f, 1) + "MB / " + Math.Round(e.TotalBytesToReceive / 1024f / 1024f, 1) + "MB - " + e.ProgressPercentage + "%");
                    Dispatcher.Invoke(() => replacedle = "Updater " + e.ProgressPercentage + "%");
                };
                webClient.DownloadFileCompleted += (s, e) =>
                {
                    ProgressBar.Dispatcher.Invoke(() => ProgressBar.Value = 0);
                    LabelProgressBar.Dispatcher.Invoke(() => LabelProgressBar.Content = "Extracting...");
                    Dispatcher.Invoke(() => replacedle = "Updater");
                };

                await webClient.DownloadFileTaskAsync(new Uri(DownloadURL), PathToFile);
            }
            catch { }
        }

19 View Source File : general.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

public static string SexySize(long size)
        {
            double return_size;
            string type;

            if (size > (1024 * 1024 * 1024))
            {
                return_size = (double)size / (1024 * 1024 * 1024);
                type = "GB";
            }
            else if (size > (1024 * 1024))
            {
                return_size = (double)size / (1024 * 1024);
                type = "MB";
            }
            else if (size > 1024)
            {
                return_size = (double)size / (1024);
                type = "KB";
            }
            else
            {
                return_size = (double)size;
                type = "B";
            }

            if (type == "GB")
                return_size = Math.Round(return_size, 3);
            else if (type == "B" || type == "KB")
                return_size = (int)return_size;
            else
                return_size = Math.Round(return_size, 2);

            return return_size.ToString() + " " + type;
        }

19 View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd

public void Calculate(AccelChartData data, ManagedAccel accel, double starter, ICollection<SimulatedMouseInput> simulatedInputData)
        {
            double lastInputMagnitude = 0;
            double lastOutputMagnitude = 0;
            SimulatedMouseInput lastInput;
            double lastSlope = 0;

            double maxRatio = 0.0;
            double minRatio = Double.MaxValue;
            double maxSlope = 0.0;
            double minSlope = Double.MaxValue;

            double log = -2;
            int index = 0;
            int logIndex = 0;

            foreach (var simulatedInputDatum in simulatedInputData)
            {
                if (simulatedInputDatum.velocity <= 0)
                {
                    continue;
                }

                var output = accel.Accelerate(simulatedInputDatum.x, simulatedInputDatum.y, 1, simulatedInputDatum.time);
                var outMagnitude = DecimalCheck(Velocity(output.Item1, output.Item2, simulatedInputDatum.time));
                var inDiff = Math.Round(simulatedInputDatum.velocity - lastInputMagnitude, 5);
                var outDiff = Math.Round(outMagnitude - lastOutputMagnitude, 5);

                if (inDiff == 0)
                {
                    continue;
                }

                if (!data.VelocityPoints.ContainsKey(simulatedInputDatum.velocity))
                {
                    data.VelocityPoints.Add(simulatedInputDatum.velocity, outMagnitude);
                }
                else
                {
                    continue;
                }

                while (Math.Pow(10,log) < outMagnitude && logIndex < data.LogToIndex.Length)
                {
                    data.LogToIndex[logIndex] = index;
                    log += 0.01;
                    logIndex++;
                }

                var ratio = DecimalCheck(outMagnitude / simulatedInputDatum.velocity);
                var slope = DecimalCheck(inDiff > 0 ? outDiff / inDiff : starter);

                if (slope < lastSlope)
                {
                    Console.WriteLine();
                }

                if (ratio > maxRatio)
                {
                    maxRatio = ratio;
                }

                if (ratio < minRatio)
                {
                    minRatio = ratio;
                }

                if (slope > maxSlope)
                {
                    maxSlope = slope;
                }

                if (slope < minSlope)
                {
                    minSlope = slope;
                }

                if (!data.AccelPoints.ContainsKey(simulatedInputDatum.velocity))
                {
                    data.AccelPoints.Add(simulatedInputDatum.velocity, ratio);
                }

                if (!data.GainPoints.ContainsKey(simulatedInputDatum.velocity))
                {
                    data.GainPoints.Add(simulatedInputDatum.velocity, slope);
                }

                lastInputMagnitude = simulatedInputDatum.velocity;
                lastOutputMagnitude = outMagnitude;
                index += 1;
                lastInput = simulatedInputDatum;
                lastSlope = slope;
            }

            index--;

            while (log <= 5.0)
            {
                data.LogToIndex[logIndex] = index;
                log += 0.01;
                logIndex++;
            }

            data.MaxAccel = maxRatio;
            data.MinAccel = minRatio;
            data.MaxGain = maxSlope;
            data.MinGain = minSlope;
        }

19 View Source File : Pi.cs
License : Apache License 2.0
Project Creator : Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            var result = System.Math.Round((double)System.Math.PI, 14);
            return CreateResult(result, DataType.Decimal);
        }

19 View Source File : AddPackageDialog.cs
License : MIT License
Project Creator : AlturosDestinations

private void ButtonSelectFolders_Click(object sender, System.EventArgs e)
        {
            using (var folderBrowser = new BetterFolderBrowser
            {
                Multiselect = true,
                RootFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents)
            })
            {
                var dialogResult = folderBrowser.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    this._packagePaths = folderBrowser.SelectedFolders.ToList();

                    this.dataGridViewPackages.DataSource = folderBrowser.SelectedFolders.Select(o => new
                    {
                        Name = o,
                        ImageCount = PackageHelper.GetImages(o).Length,
                        Size = Math.Round(this.GetDirectorySize(o), 2)
                    }).ToList();
                }
            }

            this.buttonUpload.Enabled = this._packagePaths?.Count > 0;
        }

19 View Source File : TestAnalogAudioOutput.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita

static double GetFirstParameterDouble(string value, string MessageHelp)
        {
            var commands = value.Split(' ');
            double Result;
            try
            {
                Result = double.Parse(commands[0]);
                Result = Math.Round(Result, 1);
            }
            catch (Exception)
            {
                CrestronConsole.ConsoleCommandResponse(MessageHelp);
                return 0xffff;
            }
            return Result;
        }

19 View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd

private SimulatedMouseInput SimulateAngledInput(double angle, double magnitude)
        {
            SimulatedMouseInput mouseInputData;

            var moveX = Math.Round(magnitude * Math.Cos(angle), 4);
            var moveY = Math.Round(magnitude * Math.Sin(angle), 4);

            if (moveX == 0)
            {
                mouseInputData.x = 0;
                mouseInputData.y = (int)Math.Ceiling(moveY);
                mouseInputData.time = mouseInputData.y / moveY;
            }
            else if (moveY == 0)
            {
                mouseInputData.x = (int)Math.Ceiling(moveX);
                mouseInputData.y = 0;
                mouseInputData.time = mouseInputData.x / moveX;
            }
            else
            {
                var ratio =  moveY / moveX;
                int ceilX = 0;
                int ceilY = 0;
                double biggerX = 0;
                double biggerY = 0;
                double roundedBiggerX = 0;
                double roundedBiggerY = 0;
                double roundedRatio = -1;
                double factor = 10;

                while (Math.Abs(roundedRatio - ratio) > 0.01 &&
                    biggerX < 25000 &&
                    biggerY < 25000)
                {
                    roundedBiggerX = Math.Floor(biggerX);
                    roundedBiggerY = Math.Floor(biggerY);
                    ceilX = Convert.ToInt32(roundedBiggerX);
                    ceilY = Convert.ToInt32(roundedBiggerY);
                    roundedRatio =  ceilX > 0 ? ceilY / ceilX : -1;
                    biggerX = moveX * factor;
                    biggerY = moveY * factor;
                    factor *= 10;
                }

                var ceilMagnitude = Magnitude(ceilX, ceilY);
                var timeFactor = ceilMagnitude / magnitude;

                mouseInputData.x = ceilX;
                mouseInputData.y = ceilY;
                mouseInputData.time = timeFactor;

                if (mouseInputData.x == 1 && mouseInputData.time == 1)
                {
                    Console.WriteLine("Oops");
                }

            }

            mouseInputData.velocity = DecimalCheck(Velocity(mouseInputData.x, mouseInputData.y, mouseInputData.time));

            if (double.IsNaN(mouseInputData.velocity))
            {
                Console.WriteLine("oopsie");
            }

            mouseInputData.angle = angle;
            return mouseInputData;
        }

19 View Source File : NetworkHelper.cs
License : MIT License
Project Creator : Amine-Smahi

private static double CheckInternetSpeed()
        {
            try
            {
                var timeBeforeDownloadingFile = DateTime.Now;
                var data = WebClient.DownloadData("http://google.com");
                var timeAfterDownloadingFile = DateTime.Now;
                return Math.Round(
                    data.Length / 1024.0 / (timeAfterDownloadingFile - timeBeforeDownloadingFile).TotalSeconds, 2);
            }
            catch
            {
                NotificationsHelper.DisplayMessage(Messages.NoInternet);
                return 0d;
            }
        }

19 View Source File : Math.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

[ContextMethod("Окр", "Round")]
        public double Round(double p1, int p2)
        {
            return System.Math.Round(p1, p2);
        }

19 View Source File : NativeEventHelper.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static double GetEventPercent(uint time, uint minTime, uint maxTime)
        {
            uint lenght = maxTime - minTime;
            if (lenght == 0)
            {
                return 100;
            }
            return Math.Round((((double)(time - minTime)) / ((double)lenght)) * 100, 1);
        }

19 View Source File : DownloadUpdateDialog.cs
License : MIT License
Project Creator : Analogy-LogViewer

private static string BytesToString(long byteCount)
        {
            string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
            if (byteCount == 0)
            {
                return "0" + suf[0];
            }

            long bytes = Math.Abs(byteCount);
            int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            double num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return $"{(Math.Sign(byteCount) * num).ToString(CultureInfo.InvariantCulture)} {suf[place]}";
        }

19 View Source File : UnitsCalculator.cs
License : MIT License
Project Creator : alaabenfatma

public static string SizeCalc(long byteCount)
        {
            string[] suf = {"B", "KB", "MB", "GB", "TB", "PB", "EB"};
            if (byteCount == 0)
                return "0" + suf[0];
            var bytes = Math.Abs(byteCount);
            var place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
            var num = Math.Round(bytes / Math.Pow(1024, place), 1);
            return Math.Sign(byteCount) * num + suf[place];
        }

19 View Source File : AxisLabels.cs
License : MIT License
Project Creator : AngeloCresta

internal void FillLabels(bool removeFirstRow)
        {
#if SUBAXES
			// Process all sub-axis
			foreach(SubAxis subAxis in ((Axis)this).SubAxes)
			{
				subAxis.FillLabels(true);
			}
#endif // SUBAXES

            // Labels are disabled for this axis
			if( !this.LabelStyle.Enabled || !this.enabled )
			{
				return;
			}

			// For circular chart area fill only Y axis labels
			if(this.ChartArea != null && this.ChartArea.chartAreaIsCurcular)
			{
				if(this.axisType != AxisName.Y)
				{
					ICircularChartType type = this.ChartArea.GetCircularChartType();
					if(type == null || !type.XAxisLabelsSupported())
					{
						return;
					}
				}
			}

			// Check if the custom labels exist
			bool customLabelsFlag = false;
			foreach( CustomLabel lab in CustomLabels )
			{
				if( lab.customLabel )
				{
					if( lab.RowIndex == 0 ||
						this.ChartArea.chartAreaIsCurcular)
					{
						customLabelsFlag = true;
					}
				}
			}


			// Remove the first row of labels if custom labels not exist
			if(removeFirstRow)
			{
				if( customLabelsFlag == false )
				{
					for( int index = 0; index < CustomLabels.Count; index++ )
					{
						if( CustomLabels[index].RowIndex == 0 )
						{
							CustomLabels.RemoveAt( index );
							index = -1;
						}
					}
				}
				else
				{
					return;
				}
			}

			// Get data series for this axis.
			List<string> dataSeries = null;
			switch( axisType )
			{
				case AxisName.X:
					dataSeries = ChartArea.GetXAxesSeries( AxisType.Primary, ((Axis)this).SubAxisName );
					break;
				case AxisName.Y:
					dataSeries = ChartArea.GetYAxesSeries( AxisType.Primary, ((Axis)this).SubAxisName );
					break;
				case AxisName.X2:
					dataSeries = ChartArea.GetXAxesSeries( AxisType.Secondary, ((Axis)this).SubAxisName );
					break;
				case AxisName.Y2:
					dataSeries = ChartArea.GetYAxesSeries( AxisType.Secondary, ((Axis)this).SubAxisName );
					break;
			}

			// There aren't data series connected with this axis.
			if( dataSeries.Count == 0 )
			{
				return;
			}

            //Let's convert the ArrayList of the series names into to string[]
            string[] dataSeriesNames = new string[dataSeries.Count];
            for (int i = 0; i < dataSeries.Count; i++)
                dataSeriesNames[i] = (string)dataSeries[i];

			// Check if series X values all set to zeros
            bool seriesXValuesZeros = ChartHelper.SeriesXValuesZeros(this.Common, dataSeriesNames);

            // Check if series is indexed (All X values zeros or IsXValueIndexed flag set)
            bool indexedSeries = true;
            if (!seriesXValuesZeros)
            {
                indexedSeries = ChartHelper.IndexedSeries(this.Common, dataSeriesNames);
            }

			// Show End Labels
			int endLabels = 0;
			if( labelStyle.IsEndLabelVisible )
			{
				endLabels = 1;
			}

			// Get chart type of the first series
			IChartType	chartType = Common.ChartTypeRegistry.GetChartType( ChartArea.GetFirstSeries().ChartTypeName );
			bool		fromSeries = false;
			if( !chartType.RequireAxes )
			{
				return;
			}
			else if( axisType == AxisName.Y || axisType == AxisName.Y2 )
			{
				fromSeries = false;
			}
			else
			{
				fromSeries = true;
			}

			// X values from data points are not 0.
            if (fromSeries && !ChartHelper.SeriesXValuesZeros(this.Common, dataSeries.ToArray()))
			{
				fromSeries = false;
			}

			// X values from data points are not 0.
			if( fromSeries && ( labelStyle.GetIntervalOffset() != 0 || labelStyle.GetInterval() != 0 ) )
			{
				fromSeries = false;
			}

			// Get value type
			ChartValueType valueType;
			if( axisType == AxisName.X || axisType == AxisName.X2 )
			{
				// If X value is indexed the type is always String. So we use indexed type instead
				valueType = Common.DataManager.Series[dataSeries[0]].indexedXValueType;
			}
			else
			{
				valueType = Common.DataManager.Series[dataSeries[0]].YValueType;
			}

			if( labelStyle.GetIntervalType() != DateTimeIntervalType.Auto && 
                labelStyle.GetIntervalType() != DateTimeIntervalType.Number )
			{
                if (valueType != ChartValueType.Time && 
                    valueType != ChartValueType.Date && 
                    valueType != ChartValueType.DateTimeOffset)
				{
					valueType = ChartValueType.DateTime;
				}
			}

			// ***********************************
			// Pre calculate some values
			// ***********************************
			double viewMaximum = this.ViewMaximum;
			double viewMinimum = this.ViewMinimum;

			// ***********************************
			// Labels are filled from data series.
			// ***********************************
			if( fromSeries )
			{
				int numOfPoints;
				numOfPoints = Common.DataManager.GetNumberOfPoints( dataSeries.ToArray() );

				// Show end labels
				if( endLabels == 1 )
				{
					// min position
					CustomLabels.Add( - 0.5, 0.5, ValueConverter.FormatValue(
						this.Common.Chart,
						this,
                        null,
						0.0, 
						this.LabelStyle.Format, 
						valueType,
						ChartElementType.AxisLabels), 
						false);
				}

				// Labels from point position
				for( int point = 0; point < numOfPoints; point++ )
				{
					CustomLabels.Add( ((double)point)+ 0.5, ((double)point)+ 1.5, 
						ValueConverter.FormatValue(
							this.Common.Chart,
							this,
                            null,
							point + 1, 
							this.LabelStyle.Format, 
							valueType,
							ChartElementType.AxisLabels), 
							false);
				}

				// Show end labels
				if( endLabels == 1 )
				{
					// max position
					CustomLabels.Add( ((double)numOfPoints)+ 0.5, ((double)numOfPoints)+ 1.5, 
						ValueConverter.FormatValue(
							this.Common.Chart,
							this,
                            null,
                            numOfPoints + 1, 
							this.LabelStyle.Format, 
							valueType,
							ChartElementType.AxisLabels), 
							false);
				}

				int pointIndx;
				foreach( string seriesIndx in dataSeries )
				{
					// End labels enabled
					if( endLabels == 1 )
						pointIndx = 1;
					else
						pointIndx = 0;

					// Set labels from data points labels
					foreach( DataPoint dataPoint in Common.DataManager.Series[ seriesIndx ].Points )
					{
						// Find first row of labels
						while( CustomLabels[pointIndx].RowIndex > 0 )
						{
							pointIndx++;
						}

						// Add X labels
						if( axisType == AxisName.X || axisType == AxisName.X2 )
						{
							if( dataPoint.AxisLabel.Length > 0 )
							{
								CustomLabels[pointIndx].Text = dataPoint.AxisLabel;
							}
						}
	
						pointIndx++;
					}
				}
			}
			// ***********************************
			// Labels are filled from axis scale.
			// ***********************************
			else
			{
				if( viewMinimum == viewMaximum )
					return;

				double labValue; // Value, which will be converted to text and used for, labels.
				double beginPosition; // Begin position for a label
				double endPosition; // End position for a label
				double start; // Start position for all labels

				// Get first series attached to this axis
				Series	axisSeries = null;
				if(axisType == AxisName.X || axisType == AxisName.X2)
				{
					List<string> seriesArray = ChartArea.GetXAxesSeries((axisType == AxisName.X) ? AxisType.Primary : AxisType.Secondary, ((Axis)this).SubAxisName);
					if(seriesArray.Count > 0)
					{
						axisSeries = Common.DataManager.Series[seriesArray[0]];
						if(axisSeries != null && !axisSeries.IsXValueIndexed)
						{
							axisSeries = null;
						}
					}
				}

                // ***********************************
                // Check if the AJAX zooming and scrolling mode is enabled.
                // Labels are filled slightly different in this case.
                // ***********************************
                DateTimeIntervalType offsetType = (labelStyle.GetIntervalOffsetType() == DateTimeIntervalType.Auto) ? labelStyle.GetIntervalType() : labelStyle.GetIntervalOffsetType();

				// By default start is equal to minimum
				start = viewMinimum; 

				// Adjust start position depending on the interval type
				if(!this.ChartArea.chartAreaIsCurcular ||
					this.axisType == AxisName.Y || 
					this.axisType == AxisName.Y2 )
				{
                    start = ChartHelper.AlignIntervalStart(start, labelStyle.GetInterval(), labelStyle.GetIntervalType(), axisSeries);
				}
				
				// Move start if there is start position
				if( labelStyle.GetIntervalOffset() != 0 && axisSeries == null)
				{
                    start += ChartHelper.GetIntervalSize(start, labelStyle.GetIntervalOffset(), 
						offsetType, axisSeries, 0, DateTimeIntervalType.Number, true, false);
				}

				// ***************************************
				// Date type
				// ***************************************
				if( valueType == ChartValueType.DateTime || 
					valueType == ChartValueType.Date ||
					valueType == ChartValueType.Time ||
                    valueType == ChartValueType.DateTimeOffset ||
					axisSeries != null)
				{
					double position = start;
					double dateInterval;

					// Too many labels
                    if ((viewMaximum - start) / ChartHelper.GetIntervalSize(start, labelStyle.GetInterval(), labelStyle.GetIntervalType(), axisSeries, 0, DateTimeIntervalType.Number, true) > ChartHelper.MaxNumOfGridlines)
						return;

					int	counter = 0;
                    double endLabelMaxPosition = viewMaximum - ChartHelper.GetIntervalSize(viewMaximum, labelStyle.GetInterval(), labelStyle.GetIntervalType(), axisSeries, labelStyle.GetIntervalOffset(), offsetType, true) / 2f;
                    double endLabelMinPosition = viewMinimum + ChartHelper.GetIntervalSize(viewMinimum, labelStyle.GetInterval(), labelStyle.GetIntervalType(), axisSeries, labelStyle.GetIntervalOffset(), offsetType, true) / 2f;
					while( (decimal)position <= (decimal)viewMaximum )
					{
                        dateInterval = ChartHelper.GetIntervalSize(position, labelStyle.GetInterval(), labelStyle.GetIntervalType(), axisSeries, labelStyle.GetIntervalOffset(), offsetType, true);
						labValue = position;

						// For IsLogarithmic axes
						if( this.IsLogarithmic )
						{
							labValue = Math.Pow( this.logarithmBase, labValue );
						}

                        // Check if we do not exceed max number of elements
                        if (counter++ > ChartHelper.MaxNumOfGridlines)
                        {
                            break;
                        }

                        if (endLabels == 0 && position >= endLabelMaxPosition)
                        {
                            break;
                        }

						beginPosition = position - dateInterval * 0.5;
						endPosition = position + dateInterval * 0.5;

						if(endLabels == 0 && position <=  endLabelMinPosition)
						{
							position += dateInterval;
							continue;
						}
						
						if( (decimal)beginPosition > (decimal)viewMaximum )
						{
							position += dateInterval;
							continue;
						}

                        // NOTE: Fixes issue #6466
                        // Following code is removed due to the issues caused by the rounding error

                        //if( (((decimal)beginPosition + (decimal)endPosition) / 2.0m) < (decimal)viewMinimum )
                        //{
                        //    position += dateInterval;
                        //    continue;
                        //}
                        //if ((decimal)viewMaximum < (((decimal)beginPosition + (decimal)endPosition) / 2m))
                        //{
                        //    position += dateInterval;
                        //    continue;
                        //}

						string pointLabel = GetPointLabel( dataSeries, labValue, !seriesXValuesZeros, indexedSeries );
						if( pointLabel.Length == 0 )
						{
							// Do not draw last label for indexed series
							if( position <= this.maximum )
							{
								// Add a label to the collection
								if( position != this.maximum || !Common.DataManager.Series[ dataSeries[0] ].IsXValueIndexed )
								{
									CustomLabels.Add( beginPosition, 
										endPosition, 
										ValueConverter.FormatValue(
											this.Common.Chart,
											this,
                                            null,
											labValue, 
											this.LabelStyle.Format, 
											valueType,
											ChartElementType.AxisLabels),
										false);
								}
							}
						}
						else
						{
							// Add a label to the collection
							CustomLabels.Add( beginPosition, 
								endPosition, 
								pointLabel,
								false);
						}
						position += dateInterval;
					}
				}
				else
				{
					// ***************************************
					// Scale value type
					// ***************************************

					// Show First label if Start Label position is used
					if( start != viewMinimum )
						endLabels = 1;

					// Set labels
					int labelCounter = 0;
                    for (double position = start - endLabels * labelStyle.GetInterval(); position < viewMaximum - 1.5 * labelStyle.GetInterval() * (1 - endLabels); position = (double)((decimal)position + (decimal)labelStyle.GetInterval()))
					{
						// Prevent endless loop that may be caused by very small interval
						// and double/decimal rounding errors
						++labelCounter;
						if(labelCounter > ChartHelper.MaxNumOfGridlines)
						{
							break;
						}

						labValue = (double)((decimal)position + (decimal)labelStyle.GetInterval());

						// This line is introduce because sometimes 0 value will appear as 
						// very small value close to zero.
						double inter = Math.Log(labelStyle.GetInterval());
						double valu = Math.Log(Math.Abs(labValue));
						int digits = (int)Math.Abs(inter)+5;

						if( digits > 15 )
						{
							digits = 15;
						}

						if( Math.Abs(inter) < Math.Abs(valu)-5 )
						{
							labValue = Math.Round(labValue,digits);
						}

						// Too many labels
						if( ( viewMaximum - start ) / labelStyle.GetInterval() > ChartHelper.MaxNumOfGridlines )
						{
							return;
						}

						// For IsLogarithmic axes
						if( this.IsLogarithmic )
							labValue = Math.Pow( this.logarithmBase, labValue );

						beginPosition = (double)((decimal)position + (decimal)labelStyle.GetInterval() * 0.5m);
						endPosition = (double)((decimal)position + (decimal)labelStyle.GetInterval() * 1.5m);
						
						if( (decimal)beginPosition > (decimal)viewMaximum )
						{
							continue;
						}

						// Show End label if Start Label position is used
						// Use decimal type to solve rounding issues
						if( (decimal)(( beginPosition + endPosition )/2.0) > (decimal)viewMaximum )
						{
							continue;
						}

						string pointLabel = GetPointLabel( dataSeries, labValue, !seriesXValuesZeros, indexedSeries  );
						if( pointLabel.Length > 15 && labValue < 0.000001)
						{
							labValue = 0.0;
						}

						if( pointLabel.Length == 0 )
						{
							// Do not draw last label for indexed series
							if( !(Common.DataManager.Series[ dataSeries[0] ].IsXValueIndexed && position > this.maximum) )
							{
								// Add a label to the collection
								CustomLabels.Add( beginPosition, 
									endPosition, 
									ValueConverter.FormatValue(
										this.Common.Chart,
										this,
                                        null,
										labValue, 
										this.LabelStyle.Format, 
										valueType,
										ChartElementType.AxisLabels),
									false);
							}
						}
						else
						{
							// Add a label to the collection
							CustomLabels.Add( beginPosition, 
								endPosition, 
								pointLabel,
								false);
						}
					}
				}
			}
		}

19 View Source File : SynchronizeMouseAcrossChartsViewModel.cs
License : MIT License
Project Creator : ABTSoftware

private IDataSeries CreateDataSeries()
        {
            const int count = 1000;

            var ds = new UniformXyDataSeries<double>();

            for (int i = 0; i < count; i++)
            {
                ds.Append(count * Math.Sin(Math.Round(i * Math.PI, 3) * 0.1) / i);
            }

            return ds;
        }

19 View Source File : JobBase.cs
License : Apache License 2.0
Project Creator : anjoy8

public async Task<string> ExecuteJob(IJobExecutionContext context, Func<Task> func)
        {
            //记录Job时间
            Stopwatch stopwatch = new Stopwatch();
            //JOBID
            int jobid = context.JobDetail.Key.Name.ObjToInt();
            //JOB组名
            string groupName = context.JobDetail.Key.Group;
            //日志
            string jobHistory = $"【{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}】【执行开始】【Id:{jobid},组别:{groupName}】";
            //耗时
            double taskSeconds = 0;
            try
            {
                stopwatch.Start();
                await func();//执行任务
                stopwatch.Stop();
                jobHistory += $",【{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}】【执行成功】";
            }
            catch (Exception ex)
            {
                JobExecutionException e2 = new JobExecutionException(ex);
                //true  是立即重新执行任务 
                e2.RefireImmediately = true;
                jobHistory += $",【{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}】【执行失败:{ex.Message}】";
            }
            finally
            {
                taskSeconds = Math.Round(stopwatch.Elapsed.TotalSeconds, 3);
                jobHistory += $",【{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}】【执行结束】(耗时:{taskSeconds}秒)";
                if (_tasksQzServices != null)
                {
                    var model = await _tasksQzServices.QueryById(jobid);
                    if (model != null)
                    {
                        model.RunTimes += 1;
                        var separator = "<br>";
                        // 这里注意数据库字段的长度问题,超过限制,会造成数据库remark不更新问题。
                        model.Remark =
                            $"{jobHistory}{separator}" + string.Join(separator, StringHelper.GetTopDataBySeparator(model.Remark, separator, 9));
                        await _tasksQzServices.Update(model);
                    }
                }
            }

            Console.Out.WriteLine(jobHistory);
            return jobHistory;
        }

19 View Source File : CheckWantsView.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick

private void checkArticle(string idProduct, System.Collections.Generic.List<string> idLanguages, string minCondition, string isFoil,
        string isSigned, string isAltered, string isPlayset, string matchingArticle,
        float maxAllowedPrice, float shippingAddition, float percentBelowOthers, bool checkTrend)
    {
      var sUrl = "https://api.cardmarket.com/ws/v2.0/articles/" + idProduct +
                 "?minCondition=" + minCondition +
                 "&start=0&maxResults=50";

      if (isFoil != "")
      {
        sUrl += "&isFoil=" + isFoil;
      }

      if (isSigned != "")
      {
        sUrl += "&isSigned=" + isSigned;
      }

      if (isAltered != "")
      {
        sUrl += "&isAltered=" + isAltered;
      }

      if (isPlayset != "")
      {
        sUrl += "&isPlayset=" + isPlayset;
      }

      if (idLanguages.Count == 1 && idLanguages[0] != "") // if there is exactly one language specified, fetch only articles in that one language, otherwise get all
      {
        sUrl += "&idLanguage=" + idLanguages[0];
      }

      XmlDoreplacedent doc2;
      try
      {
        doc2 = MKMInteract.RequestHelper.MakeRequest(sUrl, "GET");
      }
      catch (Exception eError)
      {
        MKMHelpers.LogError("checking article id " + idProduct, eError.Message, false, sUrl);
        return;
      }

      var node2 = doc2.GetElementsByTagName("article");

      var counter = 0;

      var noBestPrice = true;

      var aPrices = new float[4];

      var bestPriceArticle = "";

      float bestPriceInternational = 0;

      foreach (XmlNode offer in node2)
      {
        /*
            * Want states:
            * Empty    = n/a
            * true     = yes
            * false    = no
            */

        if (offer["seller"]["address"]["country"].InnerText != MainView.Instance.Config.MyCountryCode
            && domesticCheck.Checked)
          continue;

        bool languageOk = true;
        if (idLanguages.Count > 1) // only some languages were specified, filter
        {
          languageOk = false;
          foreach (string lang in idLanguages)
          {
            if (lang == offer["language"]["idLanguage"].InnerText)
            {
              languageOk = true;
              break;
            }
          }
        }
        if (!languageOk)
          continue;

        // save cheapest price found anywhere
        float price = Convert.ToSingle(MKMHelpers.GetPriceFromXml(offer), CultureInfo.InvariantCulture);
        if (price < 0)
          continue;
        aPrices[counter] = price;
        if (noBestPrice)
        {
          bestPriceInternational = aPrices[counter];
          noBestPrice = false;
        }


        if (aPrices[0] + shippingAddition > maxAllowedPrice)
        {
          //frm1.logBox.Invoke(new Form1.logboxAppendCallback(frm1.logBoxAppend), "Price higher than Max Price\n");
          continue;
        }

        if (counter == 0)
        {
          bestPriceArticle = offer["idArticle"].InnerText;
          // if looking for matching article, no point to continue if it is not the cheapest - perhaps could be modified to pick things that are among matching?
          if (matchingArticle != "" && matchingArticle != bestPriceArticle)
            break;
        }

        counter++;

        if (counter == 3)
        {
          float factor = percentBelowOthers;

          factor = factor / 100 + 1;

          MainView.Instance.LogMainWindow("Price 1: " + aPrices[0] + " Price 2: " + aPrices[1]);
          MainView.Instance.LogMainWindow(
              "Factor Price 1: " + Math.Round(aPrices[0] * factor + shippingAddition, 2)
              + " Factor Price 2: " + Math.Round(aPrices[1] * factor + shippingAddition, 2));

          //X% under others
          if (
              (aPrices[0] * factor + shippingAddition < aPrices[1])
              && (aPrices[0] * factor + shippingAddition < aPrices[2])
              )
          {
            float fTrendprice = 100000; // fictive price 

            if (checkTrend)
            {
              //check Trend Price
              try
              {
                var doc3 = MKMInteract.RequestHelper.MakeRequest(
                        "https://api.cardmarket.com/ws/v2.0/products/" + idProduct, "GET");

                fTrendprice =
                    Convert.ToSingle(doc3.GetElementsByTagName("TREND")[0].InnerText.Replace(".", ","));

                MainView.Instance.LogMainWindow("Trend: " + fTrendprice);
              }
              catch (Exception eError)
              {
                MKMHelpers.LogError("checking trend price for " + offer["product"]["locName"].InnerText, eError.Message, false);
              }
            }

            //only relevant if we search domestic
            if (domesticCheck.Checked)
            {
              // is best price international (+/-5%)?
              if (!(aPrices[0] * 0.95 <= bestPriceInternational))
              {
                break;
              }
            }

            // X% under TREND
            if (aPrices[0] * factor < fTrendprice)
            {
              MainView.Instance.LogMainWindow("Found cheap offer, ID " + bestPriceArticle);
              try
              {
                var sRequestXML = MKMInteract.RequestHelper.AddCartBody(bestPriceArticle);

                sRequestXML = MKMInteract.RequestHelper.GetRequestBody(sRequestXML);

                MKMInteract.RequestHelper.MakeRequest("https://api.cardmarket.com/ws/v2.0/shoppingcart",
                    "PUT", sRequestXML);
              }
              catch (Exception eError)
              {
                MKMHelpers.LogError("adding article " + offer["product"]["locName"].InnerText + " to cart", eError.Message, false);
              }
            }
          }

          break;
        }
      }
    }

19 View Source File : PointInfoOverlay.cs
License : Apache License 2.0
Project Creator : anmcgrath

public void Render(DicomPanelModel model, IRenderContext context)
        {
            poiOverlay.Position = Position;
            Position.CopyTo(textOverlay.Position);
            textOverlay.Position = Position - (model.Camera.RowDir * 25 / model.Camera.Scale);

            List<string> overlayStrings = new List<string>();
            if (model?.PrimaryImage != null)
                overlayStrings.Add($"Primary Image: {Math.Round((float)(model?.PrimaryImage.Grid.Interpolate(Position).Value*model?.PrimaryImage.Grid.Scaling),2)} {model?.PrimaryImage.Grid.ValueUnit}");
            if (model?.SecondaryImage != null)
                overlayStrings.Add($"Secondary Image: {Math.Round((float)(model?.SecondaryImage.Grid.Interpolate(Position).Value*model?.PrimaryImage.Grid.Scaling),2)} {model?.SecondaryImage.Grid.ValueUnit}");
            foreach (var img in model?.AdditionalImages)
                overlayStrings.Add($"{Math.Round(img.Grid.Interpolate(Position).Value*img.Grid.Scaling,2)} {img.Grid.ValueUnit} [{Math.Round(((1.0/100.0)*img.Grid.Interpolate(Position).Value/img.Grid.GetNormalisationAmount()))}]% [{img.Grid.Name}]");

            int i = 0;

            foreach(var str in overlayStrings)
            {
                textOverlay.Text = str;
                textOverlay.Position = Position - i*(model.Camera.RowDir * 20 / model.Camera.Scale);
                textOverlay.Render(model, context);
                i++;
            }
            

            //textOverlay.Text = "";

            /*if (HU != null)
                textOverlay.Text = Math.Round(HU.Value) + " HU";
            if (doseVoxel != null)
            {
                textOverlay.Text += "\n" + Math.Round(100*(doseVoxel.Value / (double)doseNorm), 2) + "%";
            }*/

            textOverlay.Text = "("+Math.Round(Position.X,2)+", "+Math.Round(Position.Y,2)+", "+Math.Round(Position.Z,2)+") (mm)";
            textOverlay.Position -= (model.Camera.RowDir * 20 / model.Camera.Scale);
            textOverlay.Render(model, context);

            //poiOverlay.Render(model, context);
            //Use the poi fractin of oriignal size to set opacity of text
            //textOverlay.Opacity = poiOverlay.Fraction;


        }

19 View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd

public void CalculateDirectional(AccelChartData[] dataByAngle, ManagedAccel accel, Profile settings, IReadOnlyCollection<IReadOnlyCollection<SimulatedMouseInput>> simulatedInputData)
        {
            double maxRatio = 0.0;
            double minRatio = Double.MaxValue;
            double maxSlope = 0.0;
            double minSlope = Double.MaxValue;

            int angleIndex = 0;

            foreach (var simulatedInputDataAngle in simulatedInputData)
            {
                double log = -2;
                int index = 0;
                int logIndex = 0;
                double lastInputMagnitude = 0;
                double lastOutputMagnitude = 0;

                var data = dataByAngle[angleIndex];

                foreach (var simulatedInputDatum in simulatedInputDataAngle)
                {
                    if (simulatedInputDatum.velocity <= 0)
                    {
                        continue;
                    }

                    var output = accel.Accelerate(simulatedInputDatum.x, simulatedInputDatum.y, 1, simulatedInputDatum.time);
                    var magnitude = DecimalCheck(Velocity(output.Item1, output.Item2, simulatedInputDatum.time));
                    var inDiff = Math.Round(simulatedInputDatum.velocity - lastInputMagnitude, 5);
                    var outDiff = Math.Round(magnitude - lastOutputMagnitude, 5);

                    if (inDiff == 0)
                    {
                        continue;
                    }

                    if (!data.VelocityPoints.ContainsKey(simulatedInputDatum.velocity))
                    {
                        data.VelocityPoints.Add(simulatedInputDatum.velocity, magnitude);
                    }
                    else
                    {
                        continue;
                    }

                    while (Math.Pow(10, log) < magnitude && logIndex < data.LogToIndex.Length)
                    {
                        data.LogToIndex[logIndex] = index;
                        log += 0.01;
                        logIndex++;
                    }

                    var ratio = DecimalCheck(magnitude / simulatedInputDatum.velocity);
                    var slope = DecimalCheck(inDiff > 0 ? outDiff / inDiff : settings.sensitivity);

                    bool indexToMeasureExtrema = (angleIndex == 0) || (angleIndex == (Constants.AngleDivisions - 1));
                    
                    if (angleIndex == 0 && double.IsNaN(ratio))
                    {
                        Console.WriteLine("oops");
                    }

                    if (indexToMeasureExtrema && (ratio > maxRatio))
                    {
                        maxRatio = ratio;
                    }

                    if (indexToMeasureExtrema && (ratio < minRatio))
                    {
                        minRatio = ratio;
                    }

                    if (indexToMeasureExtrema && (slope > maxSlope))
                    {
                        maxSlope = slope;
                    }

                    if (indexToMeasureExtrema && (slope < minSlope))
                    {
                        minSlope = slope;
                    }

                    if (!data.AccelPoints.ContainsKey(simulatedInputDatum.velocity))
                    {
                        data.AccelPoints.Add(simulatedInputDatum.velocity, ratio);
                    }

                    if (!data.GainPoints.ContainsKey(simulatedInputDatum.velocity))
                    {
                        data.GainPoints.Add(simulatedInputDatum.velocity, slope);
                    }

                    lastInputMagnitude = simulatedInputDatum.velocity;
                    lastOutputMagnitude = magnitude;
                    index += 1;
                }

                index--;

                while (log <= 5.0)
                {
                    data.LogToIndex[logIndex] = index;
                    log += 0.01;
                    logIndex++;
                }

                angleIndex++;
            }

            dataByAngle[0].MaxAccel = maxRatio;
            dataByAngle[0].MinAccel = minRatio;
            dataByAngle[0].MaxGain = maxSlope;
            dataByAngle[0].MinGain = minSlope;
        }

19 View Source File : NavMeshExporter.cs
License : MIT License
Project Creator : AnotherEnd15

private static float GetDistance(float deltaX, float deltaZ)
        {
            return (float) Math.Round(Math.Sqrt((double) deltaX * (double) deltaX + (double) deltaZ * (double) deltaZ), 2);
        }

19 View Source File : LogarithmicAxis.cs
License : MIT License
Project Creator : AlexGyver

public override void GetTickValues(
            out IList<double> majorLabelValues, out IList<double> majorTickValues, out IList<double> minorTickValues)
        {
            if (this.ActualMinimum <= 0)
            {
                this.ActualMinimum = 0.1;
            }

            double logBase = Math.Log(this.Base);
            var e0 = (int)Math.Floor(Math.Log(this.ActualMinimum) / logBase);
            var e1 = (int)Math.Ceiling(Math.Log(this.ActualMaximum) / logBase);

            // find the min & max values for the specified base
            // round to max 10 digits
            double p0 = Math.Pow(this.Base, e0);
            double p1 = Math.Pow(this.Base, e1);
            double d0 = Math.Round(p0, 10);
            double d1 = Math.Round(p1, 10);
            if (d0 <= 0)
            {
                d0 = p0;
            }

            double d = d0;
            majorTickValues = new List<double>();
            minorTickValues = new List<double>();

            double epsMin = this.ActualMinimum * 1e-6;
            double epsMax = this.ActualMaximum * 1e-6;

            while (d <= d1 + epsMax)
            {
                // d = RemoveNoiseFromDoubleMath(d);
                if (d >= this.ActualMinimum - epsMin && d <= this.ActualMaximum + epsMax)
                {
                    majorTickValues.Add(d);
                }

                for (int i = 1; i < this.Base; i++)
                {
                    double d2 = d * (i + 1);
                    if (d2 > d1 + double.Epsilon)
                    {
                        break;
                    }

                    if (d2 > this.ActualMaximum)
                    {
                        break;
                    }

                    if (d2 >= this.ActualMinimum && d2 <= this.ActualMaximum)
                    {
                        minorTickValues.Add(d2);
                    }
                }

                d *= this.Base;
                if (double.IsInfinity(d))
                {
                    break;
                }

                if (d < double.Epsilon)
                {
                    break;
                }

                if (double.IsNaN(d))
                {
                    break;
                }
            }

            if (majorTickValues.Count < 2)
            {
                base.GetTickValues(out majorLabelValues, out majorTickValues, out minorTickValues);
            }
            else
            {
                majorLabelValues = majorTickValues;
            }
        }

19 View Source File : OutlineTextBlock.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

protected override void OnRender(
            DrawingContext drawingContext)
        {
            this.EnsureGeometry();

            var thickness = Math.Round(this.StrokeThickness, 1);
            var strokePen = new Pen(this.Stroke, thickness);

            // アウトラインを描画する
            drawingContext.DrawGeometry(
                null,
                strokePen,
                this.textGeometry);

            // テキスト本体を上書きする
            drawingContext.DrawGeometry(
                this.Fill,
                null,
                this.textGeometry);
        }

19 View Source File : DimTracePaletteProvider.cs
License : MIT License
Project Creator : ABTSoftware

public Color? OverrideStrokeColor(IRenderableSeries rSeries, int index, IPointMetadata metadata)
        {
            var defaultColor = rSeries.Stroke;

            if (rSeries.DataSeries == null)
                return defaultColor;

            var xyzSeries = ((XyzDataSeries<double, double, double>)rSeries.DataSeries);

            double actualTime = xyzSeries.ZValues[index];
            double latestTime = (double) xyzSeries.Tag;

            // how old is the sample? 1.0 = New, 0.0 = Oldest
            double sampleAge = (actualTime - latestTime) / 10.0;

            // Clamp in ten steps, e.g.  0.1, 0.2 .... 0.9, 1.0
            // Why? Creating a new Pen for each single sample will slow down SciChart significantly
            sampleAge = Math.Round(sampleAge * 10.0, 0) * 0.1;

            // Ensure in the range 0.3 ... 1.0 always 
            sampleAge = Math.Max(0.3, sampleAge);
            sampleAge = Math.Min(1.0, sampleAge);

            // Compute the Alpha based on sample age
            var modifiedColor = Color.FromArgb((byte)(sampleAge * 0xFF), defaultColor.R, defaultColor.G, defaultColor.B);
            return modifiedColor;
        }

19 View Source File : DownloaderSizeConverter.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return String.Empty;

            double l_val;
            double.TryParse(value.ToString(), out l_val);

            if (l_val > 1000000000)
            {
                return Math.Round(l_val / (1024 * 1024 * 1024), 3).ToString("#0.000") + " GB";
            }
            else if (l_val > 1000000)
            {
                return Math.Round(l_val / (1024 * 1024), 2).ToString("#0.00") + " MB";
            }
            else if (l_val > 1024)
            {
                return Math.Round(l_val / 1024, 0).ToString() + " KB";
            }
            else if (l_val > 0)
            {
                return l_val.ToString() + " B";
            }
            else
            {
                return String.Empty;
            }
        }

19 View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : alonsoalon

public static double ToDouble(this object s, int? digits = null)
        {
            if (s == null || s == DBNull.Value)
                return 0d;

            double.TryParse(s.ToString(), out double result);

            if (digits == null)
                return result;

            return Math.Round(result, digits.Value);
        }

19 View Source File : GameRoot.cs
License : MIT License
Project Creator : Apostolique

protected override void Update(GameTime gameTime) {
            GuiHelper.UpdateSetup();

            if (_quit.Pressed())
                Exit();

            _ui.UpdateAll(gameTime);

            Panel.Push().XY = new Vector2(100, 100);
            if (_menu == Menu.Main) {
                Label.Put("Main Menu");
                Label.Put($"Your name is '{_name}'");
                if (Button.Put("Settings").Clicked) _menu = Menu.Settings;
                if (Button.Put("Quit").Clicked) _menu = Menu.Quit;
            } else if (_menu == Menu.Settings) {
                Label.Put("What is your name?");
                Textbox.Put(ref _name);
                Slider.Put(ref _slider, 0f, 1f, 0.1f);
                Label.Put($"{Math.Round(_slider, 3)}");
                Icon.Put(_apos);
                if (Button.Put("Back").Clicked) _menu = Menu.Main;
            } else if (_menu == Menu.Quit) {
                Label.Put("Quit Menu");
                if (Button.Put("Yes").Clicked) Exit();
                if (Button.Put("No").Clicked) _menu = Menu.Main;
            }
            Panel.Pop();

            GuiHelper.UpdateCleanup();
            base.Update(gameTime);
        }

19 View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH

public static double ToDouble(this object s, int? digits = null)
    {
        if (s == null || s == DBNull.Value)
            return 0d;

        double.TryParse(s.ToString(), out double result);

        if (digits == null)
            return result;

        return Math.Round(result, digits.Value);
    }

19 View Source File : ExcelDrawingBase.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal int GetPixelHeight()
        {
            ExcelWorksheet ws = _drawings.Worksheet;

            int pix = -(From.RowOff / EMU_PER_PIXEL);
            for (int row = From.Row + 1; row <= To.Row; row++)
            {
                pix += (int)(GetRowHeight(row) / 0.75);
            }
            pix += Convert.ToInt32(Math.Round(Convert.ToDouble(To.RowOff) / EMU_PER_PIXEL, 0));
            return pix;
        }

19 View Source File : DoubleExtension.cs
License : MIT License
Project Creator : AlphaYu

public static double ToMoney(this double @this) => Math.Round(@this, 2);

19 View Source File : MapTile.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public void DetermineCost()
        {
            cost = 0;
            sqMeters = 0;
            for (int i = 0; i < width; i++)
                for (int j = 0; j < height; j++) {
                    if (floor[i * width + j] is Water == false && map[i * width + j].Solid == false) {
                        cost += .05F;
                        sqMeters += 1;
                    }
                    if (map[i * width + j] is DownStair)
                        cost += 100F;
                }
            cost = Math.Round(cost, 2);
        }

19 View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH

public static float ToFloat(this object s, int? decimals = null)
    {
        if (s == null || s == DBNull.Value)
            return 0f;

        float.TryParse(s.ToString(), out float result);

        if (decimals == null)
            return result;

        return (float)Math.Round(result, decimals.Value);
    }

19 View Source File : UINT.cs
License : MIT License
Project Creator : 944095635

public static string ToSize(UINTYPE fromtype,double size,int count = 2)
        {
            double temp = size;
            double mod = 1024.0;
            switch (fromtype)
            {
                case UINTYPE.KB:
                    temp = size * mod;
                    break;
                case UINTYPE.MB:
                    temp = size * mod * mod;
                    break;
                case UINTYPE.GB:
                    temp = size * mod * mod * mod;
                    break;
            }

            string[] units = new string[] { "B", "KB", "MB", "GB", "TB"};
            int i = 0;
            while (temp >= mod)
            {
                temp /= mod;
                i++;
            }
            return Math.Round(temp,count) + units[i];
        }

19 View Source File : UniformHeatmapAndPaletteProvider.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private IDataSeries CreateSeries()
        {
            double angle = Math.Round(Math.PI * 2 * 1 / 30, 3);
            int w = 300, h = 200;
            var data = new double[h, w];
            for (int x = 0; x < w; x++)
                for (int y = 0; y < h; y++)
                {
                    var v = (1 + Math.Round(Math.Sin(x * 0.04 + angle), 3)) * 50 + (1 + Math.Round(Math.Sin(y * 0.1 + angle), 3)) * 50 * (1 + Math.Round(Math.Sin(angle * 2), 3));
                    var cx = 150; var cy = 100;
                    var r = Math.Sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
                    var exp = Math.Max(0, 1 - r * 0.008);
                    data[y, x] = (v * exp + _random.NextDouble() * 50);
                }

            var xStart = new DateTime(2017, 1, 13, 0, 0, 0);
            var xStep = DateTime.MinValue.AddDays(1).AddHours(6).AddMinutes(30);
            return new UniformHeatmapDataSeries<DateTime, int, double>(data, xStart, xStep, 0, 2) { SeriesName = "UniformHeatmap" };
        }

19 View Source File : ProcessMonitor.cs
License : MIT License
Project Creator : ahydrax

private double ComputeCpuUsage(TimeSpan current, TimeSpan next)
        {
            var totalMilliseconds = (next - current).TotalMilliseconds;
            var totalCpuPercentUsage = (totalMilliseconds / _checkInterval.TotalMilliseconds) * 100;
            var cpuPercentUsage = totalCpuPercentUsage / _processorCount;
            return Math.Round(cpuPercentUsage, 1);
        }

19 View Source File : GUIWindow.cs
License : GNU General Public License v3.0
Project Creator : AndrasMumm

public void Label(string text, float value, int decimals = 2)
        {
            Label(string.Format("{0}{1}", text, Math.Round(value, 2).ToString()));
        }

See More Examples