public void Test_IComparable() { Percentage first = new Percentage(100); Assert.AreEqual(0, first.CompareTo(first)); Percentage second = new Percentage(100); Assert.AreEqual(0, first.CompareTo(second)); Assert.IsTrue(first == second); Assert.IsFalse(first < second); Assert.IsTrue(first <= second); Assert.IsFalse(first > second); Assert.IsTrue(first >= second); second = new Percentage(101); Assert.AreEqual(-1, first.CompareTo(second)); Assert.IsFalse(first == second); Assert.IsTrue(first < second); Assert.IsTrue(first <= second); Assert.IsFalse(first > second); Assert.IsFalse(first >= second); second = new Percentage(50); Assert.AreEqual(1, first.CompareTo(second)); Assert.IsFalse(first == second); Assert.IsFalse(first < second); Assert.IsFalse(first <= second); Assert.IsTrue(first > second); Assert.IsTrue(first >= second); }
public void PercentageRoundsUpToTwoDecimalPlaces(double value, double expected) { var decimalValue = (decimal)value; var decimalExpected = (decimal)expected; var result = new Percentage(decimalValue); Assert.Equal(decimalExpected, result.Value); }
public void Test_IEquatable() { Percentage first = new Percentage(50.0); Percentage second = new Percentage(50); Assert.IsTrue(first == second); Assert.IsTrue(first.Equals(second)); Assert.IsTrue(first.Equals((object)second)); }
public WasteRecovery(Guid notificationId, Percentage percentageRecoverable, EstimatedValue estimatedValue, RecoveryCost recoveryCost) { NotificationId = notificationId; PercentageRecoverable = percentageRecoverable; EstimatedValue = estimatedValue; RecoveryCost = recoveryCost; }
public void Update(Percentage percentageRecoverable, EstimatedValue estimatedValue, RecoveryCost recoveryCost) { PercentageRecoverable = percentageRecoverable; EstimatedValue = estimatedValue; RecoveryCost = recoveryCost; RaiseEvent(new PercentageChangedEvent(this.NotificationId, percentageRecoverable)); }
public void Test_Constructor() { Percentage percentage = new Percentage(); Assert.AreEqual("0%", percentage.ToString()); percentage = new Percentage(50); Assert.AreEqual("50%", percentage.ToString()); percentage = new Percentage(200.0); Assert.AreEqual("200%", percentage.ToString()); percentage = new Percentage(-25); Assert.AreEqual("-25%", percentage.ToString()); }
/// <summary>Subtracts the specified percentage to the Int16.</summary> /// <param name="d"> /// The value to Subtract a percentage from. /// </param> /// <param name="p"> /// The percentage to Subtract. /// </param> public static Int64 Subtract(this Int64 d, Percentage p) { return d - d.Multiply(p); }
public async Task RecordWeatherDataAsync(string tileName, Temperature temperature, Percentage humidity, DateTimeOffset?dateOfChange, CancellationToken token) { var weatherData = new WeatherData(temperature, humidity, dateOfChange ?? DateTimeOffsetProvider.Now); if (await _weatherRepository.AddDataAsync(tileName, weatherData, token)) { await _eventDispatcher.PublishAsync(new NewDataEvent(new TileId(tileName, TileType.Weather), new { Temperature = weatherData.Temperature.GetRoundedValue(), Humidity = weatherData.Humidity.GetRoundedValue(), weatherData.AddedOn }), token); } }
/// <summary>Subtracts the specified percentage to the Decimal.</summary> /// <param name="d"> /// The value to Subtract a percentage from. /// </param> /// <param name="p"> /// The percentage to Subtract. /// </param> public static Decimal Subtract(this Decimal d, Percentage p) { return d - d.Multiply(p); }
private void UpdateFromNormStrength( int normStrength ) { // upper/lower limit of the normalized strength int limit = myNeutralSignalsOffset + Percentage.Hundred.Value; // due to "zero" the limits of the following ranges are overlapping. in this case always // take the worst signal (neutral instead of buy, sell instead of neutral) if ( -limit <= normStrength && normStrength <= -myNeutralSignalsOffset ) { Strength = new Percentage( ( normStrength * -1 ) - myNeutralSignalsOffset ); Type = SignalType.Sell; } else if ( -myNeutralSignalsOffset <= normStrength && normStrength <= myNeutralSignalsOffset ) { Strength = new Percentage( (int)( ( normStrength + myNeutralSignalsOffset ) / myNeutralSignalsWeight ) ); Type = SignalType.Neutral; } else if ( myNeutralSignalsOffset <= normStrength && normStrength <= limit ) { Strength = new Percentage( normStrength - myNeutralSignalsOffset ); Type = SignalType.Buy; } else { throw new NotSupportedException(); } }
public void ToInt32_ZeroPointFour_ReturnsZero() { Percentage percentage = new Percentage(0.4); Assert.AreEqual(0, percentage.ToInt32()); }
public static UInt64 Add(this UInt64 d, Percentage p) { return d + d.Multiply(p); }
///<summary> /// Initializes a new instance of the MagickGeometry class using the specified width and /// height. ///</summary> ///<param name="percentageWidth">The percentage of the width.</param> ///<param name="percentageHeight">The percentage of the height.</param> public MagickGeometry(Percentage percentageWidth, Percentage percentageHeight) { Throw.IfNegative("percentageWidth", percentageWidth); Throw.IfNegative("percentageHeight", percentageHeight); Initialize(0, 0, (int)percentageWidth, (int)percentageHeight, true); }
public void SetContrast(byte value) { Contrast = new Percentage(value); }
/// <summary> /// Changes the volume. /// </summary> /// <param name="volume">The volume.</param> public void ChangeVolume(Percentage volume) { this.amplifierLogger.Write(this.logEventLevel, $"{MethodBase.GetCurrentMethod()!.Name.FromCamelCaseToSentenceCase()}: {{volume}}", volume); }
/// <summary> /// Initializes a new instance of the <see cref="DrawableFillOpacity"/> class. /// </summary> /// <param name="opacity">The opacity.</param> public DrawableFillOpacity(Percentage opacity) { Opacity = opacity; }
#pragma warning restore SA1516 // Elements should be separated by blank line /// <inheritdoc/> internal override MagickImage GenerateToonLitImage() { using (var disposables = new CompositeDisposable()) { var main = CompositeMainImage(); if (DecalEnable) { var decal = CompositeDecalImage(); disposables.Add(decal); MagickImageUtility.ResizeForLarger(main, decal); var decalScaleToAspectFill = main.Width / (float)Math.Min(decal.Width, decal.Height); var decalPercentageX = new Percentage(decalScaleToAspectFill * DecalScaleX * 100.0); var decalPercentageY = new Percentage(decalScaleToAspectFill * DecalScaleY * 100.0); decal.Scale(decalPercentageX, decalPercentageY); decal.BackgroundColor = MagickColors.Transparent; decal.Rotate(DecalRotation); var decalX = Mathf.RoundToInt(main.Width * DecalPositionX - decal.Width / 2); var decalY = main.Height - Mathf.RoundToInt(main.Height * DecalPositionY + decal.Height / 2); // Draw basic decal as decalCanvas with mirror mode var decalCanvas = new MagickImage(MagickColors.Transparent, main.Width, main.Height); disposables.Add(decalCanvas); switch (DecalMirrorMode) { case SunaoDecalMirrorMode.Normal: // 仕様上、ミラー側をコントロールすることができないので通常と同じにする case SunaoDecalMirrorMode.Fixed: case SunaoDecalMirrorMode.Mirror1: decalCanvas.Composite(decal, decalX, decalY, CompositeOperator.Over); break; // ミラー側のデカールを反転させることが設定の意図なので、反転させる case SunaoDecalMirrorMode.Mirror2: decal.Flop(); decalCanvas.Composite(decal, decalX, decalY, CompositeOperator.Over); break; case SunaoDecalMirrorMode.CopyMirror: using (var halfDecal = new MagickImage(MagickColors.Transparent, main.Width, main.Height)) { var leftIsNormal = DecalPositionX < 0.5; halfDecal.Composite(decal, decalX, decalY, CompositeOperator.Over); var crop = new MagickGeometry { X = leftIsNormal ? 0 : decalCanvas.Width / 2, Y = 0, Width = decalCanvas.Width / 2, Height = decalCanvas.Height, }; halfDecal.Crop(crop); var normalX = leftIsNormal ? 0 : decalCanvas.Width / 2; var copyX = leftIsNormal ? decalCanvas.Width / 2 : 0; decalCanvas.Composite(halfDecal, normalX, 0, CompositeOperator.Over); halfDecal.Flop(); decalCanvas.Composite(halfDecal, copyX, 0, CompositeOperator.Over); } break; case SunaoDecalMirrorMode.CopyFixed: using (var leftDecal = new MagickImage(MagickColors.Transparent, main.Width / 2, main.Height)) { if (DecalPositionX < 0.5) { leftDecal.Composite(decal, decalX, decalY, CompositeOperator.Over); } else { using (var mirror = decal.Clone()) { mirror.Flop(); leftDecal.Composite(mirror, Mathf.RoundToInt(main.Width * (1 - DecalPositionX) - decal.Width / 2), decalY, CompositeOperator.Over); } } decalCanvas.Composite(leftDecal, 0, 0, CompositeOperator.Over); } using (var rightDecal = new MagickImage(MagickColors.Transparent, main.Width, main.Height)) { if (DecalPositionX < 0.5) { rightDecal.Composite(decal, Mathf.RoundToInt(main.Width * (1 - DecalPositionX) - decal.Width / 2), 0, CompositeOperator.Over); } else { using (var mirror = decal.Clone()) { mirror.Flop(); rightDecal.Composite(mirror, decalX, decalY, CompositeOperator.Over); } } rightDecal.Crop(new MagickGeometry { X = main.Width / 2, Y = 0, Width = decalCanvas.Width / 2, Height = decalCanvas.Height, }); decalCanvas.Composite(rightDecal, main.Width / 2, 0, CompositeOperator.Over); } break; default: throw new Exception($"Unhandled DecalMirrorMode: {DecalMirrorMode}"); } // Apply decal switch (DecalMode) { case SunaoDecalMode.Override: main.Composite(decalCanvas, CompositeOperator.Over); break; case SunaoDecalMode.Add: main.Composite(decalCanvas, CompositeOperator.Plus); break; case SunaoDecalMode.Multiply: main.Composite(decalCanvas, CompositeOperator.Multiply); break; case SunaoDecalMode.MultiplyMono: using (var mono = CompositeMainForMultiplyMonoDecalMode()) { decalCanvas.Composite(mono, CompositeOperator.Multiply); } main.Composite(decalCanvas, CompositeOperator.Over); break; case SunaoDecalMode.EmissiveAdd: using (var pc = decalCanvas.GetPixels()) { var values = pc.GetValues(); var channels = pc.Channels; Parallel.For(0, values.Length / channels, (index) => { var baseIndex = index * channels; var r = (float)values[baseIndex + 0]; var g = (float)values[baseIndex + 1]; var b = (float)values[baseIndex + 2]; var a = (float)values[baseIndex + 3]; var mono = (0.2126f * r) + (0.7152f * g) + (0.0722f * b); values[baseIndex + 0] = Saturate(r * a / Quantum.Max); values[baseIndex + 1] = Saturate(g * a / Quantum.Max); values[baseIndex + 2] = Saturate(b * a / Quantum.Max); values[baseIndex + 3] = Saturate(a); }); pc.SetPixels(values); } main.Composite(decalCanvas, CompositeOperator.Plus); break; case SunaoDecalMode.EmissiveOverride: main.Composite(decalCanvas, CompositeOperator.Over); using (var pc = decalCanvas.GetPixels()) { var values = pc.GetValues(); var channels = pc.Channels; var intensity = DecalEmissionIntensity; Parallel.For(0, values.Length / channels, (index) => { var baseIndex = index * channels; var r = (float)values[baseIndex + 0]; var g = (float)values[baseIndex + 1]; var b = (float)values[baseIndex + 2]; var a = (float)values[baseIndex + 3]; values[baseIndex + 0] = Saturate(r * a * intensity / Quantum.Max); values[baseIndex + 1] = Saturate(g * a * intensity / Quantum.Max); values[baseIndex + 2] = Saturate(b * a * intensity / Quantum.Max); }); pc.SetPixels(values); } main.Composite(decalCanvas, CompositeOperator.Plus); break; default: throw new Exception($"Unhandled DecalMode: {DecalMode}"); } } // Apply emission if (EmissionEnable) { var emission = CompositeEmissionImage(); disposables.Add(emission); MagickImageUtility.ResizeForLarger(main, emission); switch (EmissionMode) { case SunaoEmissionMode.Add: main.Composite(emission, CompositeOperator.Plus); break; case SunaoEmissionMode.Multiply: using (var multiply = new MagickImage(MagickColors.White, emission.Width, emission.Height)) using (var emi = main.Clone()) using (var reflectionOffset = new MagickImage(MagickColor.FromRgb(13, 13, 13), multiply.Width, multiply.Height)) { multiply.Composite(emission, CompositeOperator.MinusSrc); emi.Composite(reflectionOffset, CompositeOperator.Plus); emi.Composite(emission, CompositeOperator.Multiply); main.Composite(multiply, CompositeOperator.Multiply); main.Composite(emi, CompositeOperator.Plus); } break; case SunaoEmissionMode.Minus: main.Composite(emission, CompositeOperator.MinusSrc); break; default: throw new Exception($"Unhandled EmissionMode: {EmissionMode}"); } } // Apply gamma if (GammaFixEnable) { var powR = 1.0f / (1.0f / Mathf.Max(GammaR, 0.00001f)); var powG = 1.0f / (1.0f / Mathf.Max(GammaG, 0.00001f)); var powB = 1.0f / (1.0f / Mathf.Max(GammaB, 0.00001f)); using (var pc = main.GetPixels()) { var values = pc.GetValues(); var channels = pc.Channels; Parallel.For(0, values.Length / channels, (index) => { var baseIndex = index * channels; var r = Mathf.Pow(values[baseIndex + 0] / (float)Quantum.Max, powR) * Quantum.Max; var g = Mathf.Pow(values[baseIndex + 1] / (float)Quantum.Max, powG) * Quantum.Max; var b = Mathf.Pow(values[baseIndex + 2] / (float)Quantum.Max, powB) * Quantum.Max; values[baseIndex + 0] = Saturate(r); values[baseIndex + 1] = Saturate(g); values[baseIndex + 2] = Saturate(b); }); pc.SetPixels(values); } } // Apply brightness if (BrightnessFixEnable) { using (var pc = main.GetPixels()) { var offset = BrightnessOffset * Quantum.Max; var values = pc.GetValues(); var channels = pc.Channels; var brightness = OutputBrightness; Parallel.For(0, values.Length / channels, (index) => { var baseIndex = index * channels; var r = values[baseIndex + 0] * brightness + offset; var g = values[baseIndex + 1] * brightness + offset; var b = values[baseIndex + 2] * brightness + offset; values[baseIndex + 0] = Saturate(r); values[baseIndex + 1] = Saturate(g); values[baseIndex + 2] = Saturate(b); }); pc.SetPixels(values); } } // Apply limitter if (OutputLimitterEnable) { using (var pc = main.GetPixels()) { var limit = LimitterMax; var values = pc.GetValues(); var channels = pc.Channels; Parallel.For(0, values.Length / channels, (index) => { // OUT.rgb = min(OUT.rgb , _LimitterMax) の詳細が分からない // hsv化してv^2を制限するとそれっぽくなる var baseIndex = index * channels; var r = values[baseIndex + 0]; var g = values[baseIndex + 1]; var b = values[baseIndex + 2]; var c = new Color( r / (float)Quantum.Max, g / (float)Quantum.Max, b / (float)Quantum.Max); Color.RGBToHSV(c, out float h, out float s, out float v); var limitedV2 = Mathf.Min(limit, v * v); var limited = Color.HSVToRGB(h, s, (float)Math.Sqrt(limitedV2)); values[baseIndex + 0] = (ushort)(limited.r * Quantum.Max); values[baseIndex + 1] = (ushort)(limited.g * Quantum.Max); values[baseIndex + 2] = (ushort)(limited.b * Quantum.Max); });
///////////////////////----Mix Low Click Product Into The 1st page----/////////////////////// public PartialViewResult View(int?page, int?category) { var PageNumber = page ?? 1; //?? null colesen paramiter if it's null it will take 1st page other wise it will take the current page number var PageSize = 12; //page a product koita rakhbo int middle = 0; int top = 0; var t = db.products.OrderByDescending(x => x.click).Take(1); Percentage per = new Percentage(); var H = db.Percentages.Where(p => p.percentageId == 1).Select(x => x.percentage1); var temp = H.First(); int perc = (temp * PageSize) / 100; foreach (product p in t) { top = (int)p.click; middle = (int)(p.click) / 2; break; } if (category != null) { ViewBag.category = category; List <product> lowest = db.products.OrderBy(x => x.click).Take(perc).ToList <product>(); //aikhan theke perc ar theke j pabo sei koita product rakhbo List <product> highest = db.products.OrderByDescending(x => x.click).ToList <product>(); // sb product rakhbo aitar foreach (product z in lowest) { foreach (product p in highest) { if (p.productId == z.productId) { Random r = new Random(); int i = r.Next(highest.Count / 2); int j = highest.IndexOf(p); //lowest clicked product er index..... for (int k = j; k > i; k--) { highest[k] = highest[k - 1]; } highest[i] = z; break; } } } var ProductList = highest.Where(x => x.categoryId == category).ToPagedList(PageNumber, PageSize); return(PartialView(ProductList)); } else { { List <product> lowest = db.products.OrderBy(x => x.click).Take(perc).ToList <product>(); List <product> highest = db.products.OrderByDescending(x => x.click).ToList <product>(); foreach (product z in lowest) { foreach (product p in highest) { if (p.productId == z.productId) { Random r = new Random(); int i = r.Next(highest.Count / 2); int j = highest.IndexOf(p); //lowest clicked product er index..... for (int k = j; k > i; k--) { highest[k] = highest[k - 1]; } highest[i] = z; break; } } } //var click_list = db.products.Select(x => x.click); var ProductList = highest.ToPagedList(PageNumber, PageSize); return(PartialView(ProductList)); } } }
//--------------------------------------------------------------------- /// <summary> /// Reads harvest implementations: which prescriptions are applied to /// which management areas. /// </summary> protected void ReadHarvestImplementations(ManagementAreaDataset mgmtAreas, List <Prescription> prescriptions) { ReadName(Names.HarvestImplementations); InputVar <ushort> mgmtAreaMapCode = new InputVar <ushort>("Mgmt Area"); InputVar <string> prescriptionName = new InputVar <string>("Prescription"); InputVar <int> beginTimeVar = new InputVar <int>("Begin Time"); InputVar <int> endTimeVar = new InputVar <int>("End Time"); InputVar <Percentage> areaToHarvest = new InputVar <Percentage>("Area To Harvest"); while (!AtEndOfInput && CurrentName != Names.PrescriptionMaps) { StringReader currentLine = new StringReader(CurrentLine); // Mgmt Area column ReadValue(mgmtAreaMapCode, currentLine); ushort mapCode = mgmtAreaMapCode.Value.Actual; ManagementArea mgmtArea = mgmtAreas.Find(mapCode); if (mgmtArea == null) { //add the management area, and add it to the collection of management areas mgmtArea = new ManagementArea(mapCode); mgmtAreas.Add(mgmtArea); } // Prescription column ReadValue(prescriptionName, currentLine); string name = prescriptionName.Value.Actual; Prescription prescription = prescriptions.Find(new MatchName(name).Predicate); if (prescription == null) { throw new InputValueException(prescriptionName.Value.String, prescriptionName.Value.String + " is an unknown prescription name"); } // Area to Harvest column ReadValue(areaToHarvest, currentLine); //get percentage to harvest (type Percentage ensures that it is in percent format) Percentage percentageToHarvest = areaToHarvest.Value.Actual; //check for valid percentage if (percentageToHarvest <= 0.0 || percentageToHarvest > 1.0) { throw new InputValueException(areaToHarvest.Value.String, "Percentage must be between 0% and 100%"); } // Begin Time and End Time columns // They are optional, so the possibilities are: // // Begin Time End Time // ---------- -------- // 1) present present // 2) present missing // 3) missing missing // The default values for the starting and ending times for // an applied prescription. int beginTime = scenarioStart; int endTime = scenarioEnd; TextReader.SkipWhitespace(currentLine); if (currentLine.Peek() != -1) { ReadValue(beginTimeVar, currentLine); beginTime = beginTimeVar.Value.Actual; if (beginTime < scenarioStart) { throw new InputValueException(beginTimeVar.Value.String, string.Format("Year {0} is before the scenario start year ({1})", beginTimeVar.Value.String, scenarioStart)); } if (beginTime > scenarioEnd) { throw new InputValueException(beginTimeVar.Value.String, string.Format("Year {0} is after the scenario' end year ({1})", beginTimeVar.Value.String, scenarioEnd)); } TextReader.SkipWhitespace(currentLine); if (currentLine.Peek() != -1) { ReadValue(endTimeVar, currentLine); endTime = endTimeVar.Value.Actual; if (endTime < beginTime) { throw new InputValueException(endTimeVar.Value.String, string.Format("Year {0} is before the Begin Time ({1})", endTimeVar.Value.String, beginTimeVar.Value.String)); } if (endTime > scenarioEnd) { throw new InputValueException(endTimeVar.Value.String, string.Format("Year {0} is after the scenario' end year ({1})", endTimeVar.Value.String, scenarioEnd)); } CheckNoDataAfter("the " + endTimeVar.Name + " column", currentLine); } } //if the perscription has already been applied to this management area //NOTE: .IsApplied has been modified, and this has been moved to AFTER the //begin and end times are founded. if (mgmtArea.IsApplied(prescriptionName.Value.String, beginTime, endTime)) { throw new InputValueException(prescriptionName.Value.String, "Prescription {0} has already been applied to management area {1} with begin time = {2} and end time = {3}", prescriptionName.Value.String, mgmtArea.MapCode, beginTime, endTime); } //begin applying prescription to this management area mgmtArea.ApplyPrescription(prescription, percentageToHarvest, beginTime, endTime); CheckNoDataAfter("the " + prescriptionName.Name + " column", currentLine); GetNextLine(); } }
public void ShouldReturnOneForZeroPointFive() { var percentage = new Percentage(0.5); Assert.Equal(1, percentage.ToInt32()); }
public static UInt32 Subtract(this UInt32 d, Percentage p) { return d - d.Multiply(p); }
/// <summary> /// Initializes a new instance of the <see cref="AUserCommand"/> class. /// </summary> /// <param name="pTimeout">The timeout of the command.</param> protected AUserCommand(Time pTimeout) { this.Timeout = pTimeout; this.mCompletion = new Percentage(0.0); }
/// <summary>Adds the specified percentage to the Int32.</summary> /// <param name="d"> /// The value to add a percentage to. /// </param> /// <param name="p"> /// The percentage to add. /// </param> public static Int32 Add(this Int32 d, Percentage p) { return d + d.Multiply(p); }
/// <summary> /// Sets the completion of the commande. /// </summary> /// <param name="pCompletion">The command completion.</param> protected void SetCompletion(Percentage pCompletion) { this.mCompletion = pCompletion; }
public void ShouldReturnZeroForZeroPointFour() { var percentage = new Percentage(0.4); Assert.Equal(0, percentage.ToInt32()); }
public override Percentage AdjustSharpness(Percentage sharpness) { return(sharpness > 70 ? new Percentage(70) : base.AdjustSharpness(sharpness)); }
/// <summary> /// Initializes a new instance of the <see cref="ColorCMYK"/> class. /// </summary> /// <param name="cyan">Cyan component value of this color.</param> /// <param name="magenta">Magenta component value of this color.</param> /// <param name="yellow">Yellow component value of this color.</param> /// <param name="key">Key (black) component value of this color.</param> /// <param name="alpha">Alpha component value of this color.</param> public ColorCMYK(Percentage cyan, Percentage magenta, Percentage yellow, Percentage key, Percentage alpha) : base(new MagickColor(cyan.ToQuantum(), magenta.ToQuantum(), yellow.ToQuantum(), key.ToQuantum(), alpha.ToQuantum())) { }
public override Percentage AdjustBrightness(Percentage brightness) { return(brightness > 50 ? new Percentage(30) : base.AdjustBrightness(brightness)); }
public StunTest(Percentage percentage) { Percentage = percentage; }
public Color(Hue hue, Percentage saturation) { Hue = hue; Saturation = saturation; }
/// <summary> /// Changes the volume. /// </summary> /// <param name="newVolumePercentage">The new volume percentage.</param> public void ChangeVolume(Percentage newVolumePercentage) { this.log.Debug($"{MethodBase.GetCurrentMethod()!.Name.FromCamelCaseToSentenceCase()} {{{nameof(newVolumePercentage)}}}", newVolumePercentage); }
public void ShouldReturnFalseWhenInstanceIsNull() { Percentage percentage = default; Assert.False(percentage.Equals(null)); }
public void ToInt32_ZeroPointFive_ReturnsOne() { Percentage percentage = new Percentage(0.5); Assert.AreEqual(1, percentage.ToInt32()); }
public void ShouldReturnTrueWhenInstanceIsTheSame() { Percentage percentage = default; Assert.True(percentage.Equals(percentage)); }
/// <summary>Subtracts the specified percentage to the Single.</summary> /// <param name="d"> /// The value to Subtract a percentage from. /// </param> /// <param name="p"> /// The percentage to Subtract. /// </param> public static Single Subtract(this Single d, Percentage p) { return d - d.Multiply(p); }
//--------------------------------------------------------------------- static SpecificAgesCohortSelector() { defaultPercentage = Percentage.Parse("100%"); }
/// <summary>Adds the specified percentage to the Single.</summary> /// <param name="d"> /// The value to add a percentage to. /// </param> /// <param name="p"> /// The percentage to add. /// </param> public static Single Add(this Single d, Percentage p) { return d + d.Multiply(p); }
// Use this for initialization void Start() { Application.targetFrameRate = 60; loaded = false; offBeatObjects = new GameObject[2]; offBeatObjects[0] = Instantiate(offbeat); offBeatObjects[1] = Instantiate(offbeat); offBeatObjects[0].SetActive(false); offBeatObjects[1].SetActive(false); offBeatCounter = 0; nextPermittedBeat = 0; GlobalData.GOButtonsReady = false; touches = new Vector3[2]; screenHeight = Camera.main.orthographicSize * 2.0f; screenWidth = Camera.main.aspect * screenHeight; effect = Camera.main.GetComponent<effects>(); cameraMiss = Camera.main.GetComponent<MissFrame>(); cameraShake = Camera.main.GetComponent<Shake>(); latestTouch = 0; lastTouchPosition = new Vector2(100, 100); fxParticles = new GameObject[2]; fxParticles[0] = Instantiate(FXParticles); fxParticles[1] = Instantiate(FXParticles); fxParticlesControl = new CustomParticles[2]; fxParticlesControl[0] = fxParticles[0].GetComponent<CustomParticles>(); fxParticlesControl[1] = fxParticles[1].GetComponent<CustomParticles>(); UpdateColors(); fxPointer = 0; wrongClicks = 0; beat = GlobalData.beat; wiggleSpace = GlobalData.wiggleSpace; time = 0; god = GameObject.Find("God").GetComponent<GodDeath>(); /* PAUSE READY pause = GameObject.Find("Pause").GetComponent<Pause>(); */ bool missed = false; uint oneInXMissing = 3; float distanceCoef = (700.0f / 500.0f); float expectedBunnyLifetime = GetJumpTimeFromLinearTime((350.0f / (250.0f)) * distanceCoef, beat) / (0.48f / beat); realDuration = 0; if (audio.clip) realDuration = audio.clip.length; if (percentage) { percentageS = percentage.GetComponent<Percentage>(); percentageS.realDuration = Mathf.Floor((realDuration - expectedBunnyLifetime) / beat) * beat + expectedBunnyLifetime; } if (GOPercentage) { GOPercentageS = GOPercentage.GetComponent<Percentage>(); GOPercentageS.realDuration = Mathf.Floor((realDuration - expectedBunnyLifetime) / beat) * beat + expectedBunnyLifetime; } float[] angles = new float[5] { Mathf.PI / 2.0f, 4.6f, 2.65f, 5.6f, 1.4f }; if (beat == 0.375f) { oneInXMissing = 5; } effectObject = GameObject.Find("Offbeat"); GameObject bunnObject = GameObject.Find("Bunnies"); if (bunnObject) { bunz = bunnObject.GetComponent<Bunnies>(); } GameObject screen = GameObject.Find("Screen"); int latestColor = 0; Color[] colorsRhino = new Color[3]{ new Color(0,1.0f,91.0f / 255.0f), new Color(0,1.0f,187.0f / 255.0f), new Color(144.0f / 255.0f,0,1), }; Color[] colorsBear = new Color[3]{ new Color(1,0,0), new Color(1,212.0f / 255.0f,0), new Color(1,0,110.0f / 255.0f), }; Color[] colorsBull = new Color[3]{ new Color(1.0f,0,238 / 255.0f), new Color(0,206 / 255.0f,229 / 255.0f), new Color(144 / 255.0f,0,1), }; Color[] colors = null; switch (GlobalData.selectedGod) { case GlobalData.Gods.RHINO: colors = colorsRhino; break; case GlobalData.Gods.BEAR: colors = colorsBear; break; case GlobalData.Gods.BULL: colors = colorsBull; break; } for (int i = 0; i < maxCount; i++) { float endTime = 0; if (missing && (Random.Range(0, oneInXMissing)) == 0 && !missed && i > 2 && endTime < 50.0f) { missed = true; } else if (missed) { missed = false; } if (!missed) { GameObject bunny = null; if (bunz) { bunny = bunz.bunnies[i]; bunny.SetActive(true); } else { bunny = Instantiate(bunnyPrefab); bunny.GetComponent<BunnyJump>().Startingu(); bunny.SetActive(true); } bunny.transform.parent = null; BunnyJump bunnyJumpS = bunny.GetComponent<BunnyJump>(); bunnyJumpS.parentTransform = screen.transform; bunnyJumpS.startTime = i * beat; endTime = i * beat + expectedBunnyLifetime; bunnyJumpS.expectedBunnyLifetime = expectedBunnyLifetime; bunnyJumpS.beat = beat; bunnyJumpS.god = god; int randomColor = Random.Range(0, 3); while (randomColor == latestColor) { randomColor = Random.Range(0, 3); } latestColor = randomColor; bunnyJumpS.color = colors[randomColor]; bunnyJumpS.wiggleSpace = wiggleSpace; if (!randomSpawn) { bunnyJumpS.angle = angles[i]; } float scale = Random.Range(0.8f, 1.4f); bunny.GetComponent<Transform>().localScale = new Vector3(scale, scale, 1); bunnyJumpS.Init(); bunnyCount++; bunnies.Add(bunnyJumpS); } if (endTime + beat > realDuration) { break; } } freq = 1.0f / audio.clip.frequency; startTime = AudioSettings.dspTime; minOffset = 0.0f; maxOffset = 0.0f; }
public static UInt16 Subtract(this UInt16 d, Percentage p) { return (UInt16)(d - d.Multiply(p)); }
/// <summary> /// Initializes a new instance of the <see cref="MagickGeometry"/> class using the specified offsets, width and height. /// </summary> /// <param name="x">The X offset from origin.</param> /// <param name="y">The Y offset from origin.</param> /// <param name="percentageWidth">The percentage of the width.</param> /// <param name="percentageHeight">The percentage of the height.</param> public MagickGeometry(int x, int y, Percentage percentageWidth, Percentage percentageHeight) { Throw.IfNegative(nameof(percentageWidth), percentageWidth); Throw.IfNegative(nameof(percentageHeight), percentageHeight); Initialize(x, y, (int)percentageWidth, (int)percentageHeight, true); }
/// <summary>Adds the specified percentage to the Int64.</summary> /// <param name="d"> /// The value to add a percentage to. /// </param> /// <param name="p"> /// The percentage to add. /// </param> public static Int16 Add(this Int16 d, Percentage p) { return (Int16)(d + d.Multiply(p)); }
public static void IfNegative(string paramName, Percentage value) { if ((double)value < 0.0) throw new ArgumentException("Value should be greater then zero.", paramName); }
public void ShouldReturnTrueWhenObjectIsTheSame() { Percentage percentage = default; Assert.True(percentage.Equals((object)percentage)); }
public void FromAmount_ZeroTotal_Exception() { Assert.That(() => Percentage.FromAmounts(10, 0), Throws.ArgumentException); }
internal ProgressEventArgs(string origin, int offset, int extent) { Origin = origin; Progress = new Percentage(((offset + 1) / (double)extent) * 100); }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { const string WindSeverities = "WindSeverities"; const string EcoregionTable = "EcoregionModifiers"; ReadLandisDataVar(); InputParameters parameters = new InputParameters(PlugIn.ModelCore.Ecoregions.Count); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; //Read in the number of events mean InputVar <double> numEventsMean = new InputVar <double>("NumEventsMean"); ReadVar(numEventsMean); parameters.NumEventsMean = numEventsMean.Value; //Read in the number of events stdev InputVar <double> numEventsStDev = new InputVar <double>("NumEventsStDev"); ReadVar(numEventsStDev); parameters.NumEventsStDev = numEventsStDev.Value; //Read in the tornado length lambda InputVar <double> tornadoLengthLambda = new InputVar <double>("TornadoLengthLambda"); ReadVar(tornadoLengthLambda); parameters.TornadoLengthLambda = tornadoLengthLambda.Value; //Read in the tornado length alpha InputVar <double> tornadoLengthAlpha = new InputVar <double>("TornadoLengthAlpha"); ReadVar(tornadoLengthAlpha); parameters.TornadoLengthAlpha = tornadoLengthAlpha.Value; //Read in the tornado width InputVar <double> tornadoWidth = new InputVar <double>("TornadoWidth"); ReadVar(tornadoWidth); parameters.TornadoWidth = tornadoWidth.Value; // Read table of wind intensity percentages InputVar <double> tornadoWindIntPct = new InputVar <double>("Intensity Percent"); ReadName("TornadoIntensityTable"); int windIntIndex = 0; double cumulativeIntPct = 0; while (!AtEndOfInput && CurrentName != "TornadoProp") { StringReader currentLine = new StringReader(CurrentLine); ReadValue(tornadoWindIntPct, currentLine); cumulativeIntPct += tornadoWindIntPct.Value; parameters.TornadoWindIntPct.Add(cumulativeIntPct); windIntIndex++; GetNextLine(); } if (!(cumulativeIntPct == 100)) { throw new InputValueException(tornadoWindIntPct.Value.String, "TornadoIntensityTable percentages do not sum to 100"); } //Read in the tornado proportion InputVar <double> tornadoProp = new InputVar <double>("TornadoProp"); ReadVar(tornadoProp); parameters.TornadoProp = tornadoProp.Value; //Read in the derecho length lambda InputVar <double> derechoLengthLambda = new InputVar <double>("DerechoLengthLambda"); ReadVar(derechoLengthLambda); parameters.DerechoLengthLambda = derechoLengthLambda.Value; //Read in the derecho length alpha InputVar <double> derechoLengthAlpha = new InputVar <double>("DerechoLengthAlpha"); ReadVar(derechoLengthAlpha); parameters.DerechoLengthAlpha = derechoLengthAlpha.Value; //Read in the derecho width InputVar <double> derechoWidth = new InputVar <double>("DerechoWidth"); ReadVar(derechoWidth); parameters.DerechoWidth = derechoWidth.Value; // Read table of wind intensity percentages InputVar <double> derechoWindIntPct = new InputVar <double>("Intensity Percent"); ReadName("DerechoIntensityTable"); windIntIndex = 0; cumulativeIntPct = 0; while (!AtEndOfInput && CurrentName != "PropIntensityVar") { StringReader currentLine = new StringReader(CurrentLine); ReadValue(derechoWindIntPct, currentLine); cumulativeIntPct += derechoWindIntPct.Value; parameters.DerechoWindIntPct.Add(cumulativeIntPct); windIntIndex++; GetNextLine(); } if (!(cumulativeIntPct == 100)) { throw new InputValueException(derechoWindIntPct.Value.String, "DerechoIntensityTable percentages do not sum to 100"); } //Read in the proportion of intensity variability InputVar <double> propIntensityVar = new InputVar <double>("PropIntensityVar"); ReadVar(propIntensityVar); parameters.PropIntensityVar = propIntensityVar.Value; // Read table of wind direction percentages InputVar <double> windDirPct = new InputVar <double>("Direction Percent"); //List<double> windDirPctList = new List<double>(4); ReadName("WindDirectionTable"); int windDirIndex = 0; double cumulativePct = 0; while (!AtEndOfInput && CurrentName != EcoregionTable && CurrentName != WindSeverities) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(windDirPct, currentLine); cumulativePct += windDirPct.Value; parameters.WindDirPct.Add(cumulativePct); windDirIndex++; GetNextLine(); } if (!(cumulativePct == 100)) { throw new InputValueException(windDirPct.Value.String, "WindDirectionTable percentages do not sum to 100"); } if (CurrentName == EcoregionTable) //Ecoregion modifiers are optional { //--------- Read In Ecoreigon Table --------------------------------------- ReadName(EcoregionTable); PlugIn.ModelCore.UI.WriteLine("Begin parsing ECOREGION table."); InputVar <string> ecoName = new InputVar <string>("Ecoregion Name"); InputVar <double> ecoModifier = new InputVar <double>("Ecoregion Modifier"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); while (!AtEndOfInput && CurrentName != WindSeverities) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(ecoName, currentLine); IEcoregion ecoregion = EcoregionsDataset[ecoName.Value.Actual]; if (ecoregion == null) { throw new InputValueException(ecoName.Value.String, "{0} is not an ecoregion name.", ecoName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(ecoregion.Name, out lineNumber)) { throw new InputValueException(ecoName.Value.String, "The ecoregion {0} was previously used on line {1}", ecoName.Value.String, lineNumber); } else { lineNumbers[ecoregion.Name] = LineNumber; } IEcoParameters ecoParms = new EcoParameters(); ReadValue(ecoModifier, currentLine); ecoParms.EcoModifier = ecoModifier.Value; parameters.EcoParameters[ecoregion.Index] = ecoParms; CheckNoDataAfter("the " + ecoModifier.Name + " column", currentLine); GetNextLine(); } } // Read table of wind severities. // Severities are in decreasing order. ReadName(WindSeverities); InputVar <byte> number = new InputVar <byte>("Severity Number"); InputVar <Percentage> minAge = new InputVar <Percentage>("Min Age"); InputVar <Percentage> maxAge = new InputVar <Percentage>("Max Age"); InputVar <float> mortalityThreshold = new InputVar <float>("Mortality Threshold"); const string IntensityMapNames = "IntensityMapNames"; const string SeverityMapNames = "SeverityMapNames"; const string LogFile = "LogFile"; byte previousNumber = 6; Percentage previousMaxAge = null; while (!AtEndOfInput && CurrentName != SeverityMapNames && CurrentName != IntensityMapNames && CurrentName != LogFile && previousNumber != 1) { StringReader currentLine = new StringReader(CurrentLine); ISeverity severity = new Severity(); parameters.WindSeverities.Add(severity); ReadValue(number, currentLine); severity.Number = number.Value; // Check that the current severity's number is 1 less than // the previous number (numbers are must be in decreasing // order). if (number.Value.Actual != previousNumber - 1) { throw new InputValueException(number.Value.String, "Expected the severity number {0}", previousNumber - 1); } previousNumber = number.Value.Actual; ReadValue(minAge, currentLine); severity.MinAge = (double)minAge.Value.Actual; if (parameters.WindSeverities.Count == 1) { // Minimum age for this severity must be equal to 0% if (minAge.Value.Actual != 0) { throw new InputValueException(minAge.Value.String, "It must be 0% for the first severity"); } } else { // Minimum age for this severity must be equal to the // maximum age of previous severity. if (minAge.Value.Actual != (double)previousMaxAge) { throw new InputValueException(minAge.Value.String, "It must equal the maximum age ({0}) of the preceeding severity", previousMaxAge); } } TextReader.SkipWhitespace(currentLine); string word = TextReader.ReadWord(currentLine); if (word != "to") { StringBuilder message = new StringBuilder(); message.AppendFormat("Expected \"to\" after the minimum age ({0})", minAge.Value.String); if (word.Length > 0) { message.AppendFormat(", but found \"{0}\" instead", word); } throw NewParseException(message.ToString()); } ReadValue(maxAge, currentLine); severity.MaxAge = (double)maxAge.Value.Actual; if (number.Value.Actual == 1) { // Maximum age for the last severity must be 100% if (maxAge.Value.Actual != 1) { throw new InputValueException(minAge.Value.String, "It must be 100% for the last severity"); } } previousMaxAge = maxAge.Value.Actual; ReadValue(mortalityThreshold, currentLine); severity.MortalityThreshold = mortalityThreshold.Value; CheckNoDataAfter("the " + mortalityThreshold.Name + " column", currentLine); GetNextLine(); } if (parameters.WindSeverities.Count == 0) { throw NewParseException("No severities defined."); } if (previousNumber != 1) { throw NewParseException("Expected wind severity {0}", previousNumber - 1); } InputVar <string> intensityMapNames = new InputVar <string>(IntensityMapNames); if (ReadOptionalVar(intensityMapNames)) { parameters.IntensityMapNamesTemplate = intensityMapNames.Value; } InputVar <string> severityMapNames = new InputVar <string>(SeverityMapNames); if (ReadOptionalVar(severityMapNames)) { parameters.MapNamesTemplate = severityMapNames.Value; } InputVar <string> logFile = new InputVar <string>("LogFile"); ReadVar(logFile); parameters.LogFileName = logFile.Value; CheckNoDataAfter(string.Format("the {0} parameter", logFile.Name)); return(parameters); //.GetComplete(); }
public PercentageChangedEvent(Guid notificationId, Percentage newPercentage) { NotificationId = notificationId; NewPercentage = newPercentage; }
/// <summary> /// Initializes a new instance of the <see cref="DrawableStrokeOpacity"/> class. /// </summary> /// <param name="opacity">The opacity.</param> public DrawableStrokeOpacity(Percentage opacity) { Opacity = opacity; }
///<summary> /// Creates a new DrawableFillOpacity instance. ///</summary> ///<param name="opacity">The opacity.</param> public DrawableFillOpacity(Percentage opacity) { Opacity = opacity; }
//--------------------------------------------------------------------- /// <summary> /// Reads a percentage for partial thinning of a cohort age or age /// range. /// </summary> /// <remarks> /// The percentage is bracketed by parentheses. /// </remarks> public static InputValue <Percentage> ReadPercentage(StringReader reader, out int index) { TextReader.SkipWhitespace(reader); index = reader.Index; int nextChar = reader.Peek(); if (nextChar == -1) { throw new InputValueException(); // Missing value } if (nextChar != '(') { throw MakeInputValueException(TextReader.ReadWord(reader), "Value does not start with \"(\""); } StringBuilder valueAsStr = new StringBuilder(); valueAsStr.Append((char)(reader.Read())); // Read whitespace between '(' and percentage valueAsStr.Append(ReadWhitespace(reader)); // Read percentage string word = ReadWord(reader, ')'); if (word == "") { throw MakeInputValueException(valueAsStr.ToString(), "No percentage after \"(\""); } valueAsStr.Append(word); Percentage percentage; try { percentage = Percentage.Parse(word); } catch (System.FormatException exc) { throw MakeInputValueException(valueAsStr.ToString(), exc.Message); } if (percentage.Value < 0.0 || percentage.Value > 1) { throw MakeInputValueException(valueAsStr.ToString(), string.Format("{0} is not between 0% and 100%.", word)); } // Read whitespace and ')' valueAsStr.Append(ReadWhitespace(reader)); char?ch = TextReader.ReadChar(reader); if (!ch.HasValue) { throw MakeInputValueException(valueAsStr.ToString(), "Missing \")\""); } valueAsStr.Append(ch.Value); if (ch != ')') { throw MakeInputValueException(valueAsStr.ToString(), string.Format("Value ends with \"{0}\" instead of \")\"", ch)); } return(new InputValue <Percentage>(percentage, valueAsStr.ToString())); }
// Use this for initialization void Start() { GameObject bunn = GameObject.Find("Bunnies"); if(bunn) { bunnies = bunn.GetComponent<Bunnies>(); } cameraShake = Camera.main.GetComponent<Shake>(); cR = GetComponent<SpriteRenderer>(); timeOfDeath = 0; ingameUI = GameObject.FindGameObjectsWithTag("IngameUI"); ingameRends = new SpriteRenderer[ingameUI.Length]; for(int i =0; i < ingameUI.Length; ++i) { ingameRends[i] = ingameUI[i].GetComponent<SpriteRenderer>(); } gameoverUI = GameObject.FindGameObjectsWithTag("GameOverUI"); goRends = new SpriteRenderer[gameoverUI.Length]; for(int i =0; i < gameoverUI.Length; ++i) { goRends[i] = gameoverUI[i].GetComponent<SpriteRenderer>(); gameoverUI[i].SetActive(false); } if(GOPercentage) { GOPercentageS = GOPercentage.GetComponent<Percentage>(); } t = 0; gameOverAudio = GetComponent<AudioSource>(); }
public CalculateFeeHandler(Percentage transactionPercentageFee) { _transactionPercentageFee = transactionPercentageFee ?? throw new ApplicationException("Transaction percentage cannot be null"); }
/// <summary> /// Initializes a new instance of the <see cref="ColorCMYK"/> class. /// </summary> /// <param name="cyan">Cyan component value of this color.</param> /// <param name="magenta">Magenta component value of this color.</param> /// <param name="yellow">Yellow component value of this color.</param> /// <param name="key">Key (black) component value of this color.</param> public ColorCMYK(Percentage cyan, Percentage magenta, Percentage yellow, Percentage key) : base(new MagickColor(cyan.ToQuantum(), magenta.ToQuantum(), yellow.ToQuantum(), key.ToQuantum(), Quantum.Max)) { }
public void ShouldDefaultToZero() { Percentage percentage = default; Assert.Equal("0%", percentage.ToString()); }
private void CalculateQuality() { int combinedQuality = (int)Signals.Average( s => s.Quality.Value ); Quality = new Percentage( combinedQuality ); }
public void ShouldSetValue() { var percentage = new Percentage(50); Assert.Equal("50%", percentage.ToString()); }
public StatusConditionTest(StatusConditionType type, Percentage percentage) { Type = type; Percentage = percentage; }
public void ShouldHandleValueAbove100() { var percentage = new Percentage(200.0); Assert.Equal("200%", percentage.ToString()); }
public void ShouldHandleNegativeValue() { var percentage = new Percentage(-25); Assert.Equal("-25%", percentage.ToString()); }