System.Math.Ceiling(double)

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

2819 Examples 7

19 View Source File : CeilingDoubleConverter.cs
License : MIT License
Project Creator : Actipro

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
		#endif
			if(value is double)
				return Math.Ceiling((double)value);

			return value;
		}

19 View Source File : RatingBar.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void CreateRatingButtons()
      {
         this.RatingButtonsInternal.Clear();
         for (var i = this.Minimum; i <= this.Maximum; i++)
         {
            RatingBarButton button = new RatingBarButton()
            {
               Content = i,
               Value = i,
               IsSelected = i <= Math.Ceiling(this.Value),
               IsHalf = this.IsInt(this.Value) ? false : Math.Ceiling(this.Value) == i,
               ContentTemplate = this.ValueItemTemplate,
               Style = this.ValueItemStyle
            };
            button.ItemMouseEnter += (o, n) =>
            {
               this.mOldValue = this.Value;
               this.Value = button.Value;
               this.mIsConfirm = false;
            };
            button.ItemMouseLeave += (o, n) =>
            {
               if (!this.mIsConfirm)
               {
                  this.Value = this.mOldValue;
                  this.mIsConfirm = false;
               }
            };

            this.RatingButtonsInternal.Add(button);
         }
         this.RatingButtons = this.RatingButtonsInternal;
      }

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

public override string FormatLabel(IComparable dataValue)
            {
                var h = (int) Math.Ceiling(dataValue.ToDouble());
                var dt = new DateTime(2000, 1, 1, 1, 0, 0);
                try
                {
                    dt = dt.AddHours(h);
                }
                catch (ArgumentOutOfRangeException)
                {
                    dt = h < 0 ? DateTime.MinValue : DateTime.MaxValue;
                }
                return dt.ToString("hh:mm tt", new CultureInfo("en-US"));
            }

19 View Source File : Player_Crafting.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public int TryAddSalvage(WorldObject salvageBag, WorldObject item, int tryAmount)
        {
            var maxStructure = salvageBag.MaxStructure ?? 100;
            var structure = salvageBag.Structure ?? 0;

            var space = maxStructure - structure;

            var amount = Math.Min(tryAmount, space);

            salvageBag.Structure = (ushort)(structure + amount);

            // add workmanship
            var item_numItems = item.StackSize ?? 1;
            var workmanship_bag = salvageBag.ItemWorkmanship ?? 0;
            var workmanship_item = item.ItemWorkmanship ?? 0;

            salvageBag.ItemWorkmanship = workmanship_bag + workmanship_item * item_numItems;

            // increment # of items that went into this salvage bag
            if (item.ItemType == ItemType.TinkeringMaterial)
            {
                item_numItems = item.NumItemsInMaterial ?? 1;

                // handle overflows when combining bags
                if (tryAmount > space)
                {
                    var scalar = (float)space / tryAmount;
                    var newItems = (int)Math.Ceiling(item_numItems * scalar);
                    scalar = (float)newItems / item_numItems;
                    var prevNumItems = item_numItems;
                    item_numItems = newItems;

                    salvageBag.ItemWorkmanship -= (int)Math.Round(workmanship_item * (1.0 - scalar));

                    // and for the next bag...
                    if (prevNumItems == newItems)
                        newItems--;

                    var itemWorkmanship = item.Workmanship;
                    item.NumItemsInMaterial -= newItems;
                    //item.ItemWorkmanship -= (int)Math.Round(workmanship_item * scalar);
                    item.ItemWorkmanship = (int)Math.Round(item.NumItemsInMaterial.Value * (float)itemWorkmanship);
                }
            }
            salvageBag.NumItemsInMaterial = (salvageBag.NumItemsInMaterial ?? 0) + item_numItems;

            salvageBag.Name = $"Salvage ({salvageBag.Structure})";

            if (item.ItemType == ItemType.TinkeringMaterial)
            {
                if (!PropertyManager.GetBool("salvage_handle_overages").Item)
                    return tryAmount;
                else
                    return amount;
            }
            else
                return amount;
        }

19 View Source File : LootGenerationFactory_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static int RollSpellcraft(WorldObject wo)
        {
            var maxSpellPower = GetMaxSpellPower(wo);

            (float min, float max) range = (1.0f, 1.0f);

            switch (wo.ItemType)
            {
                case ItemType.Armor:
                case ItemType.Clothing:
                case ItemType.Jewelry:

                case ItemType.MeleeWeapon:
                case ItemType.MissileWeapon:
                case ItemType.Caster:

                    range = (0.9f, 1.1f);
                    break;
            }

            var rng = ThreadSafeRandom.Next(range.min, range.max);

            var spellcraft = (int)Math.Ceiling(maxSpellPower * rng);

            // retail was capped at 370
            spellcraft = Math.Min(spellcraft, 370);

            return spellcraft;
        }

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 : DropDownGlyphPanel.cs
License : MIT License
Project Creator : Actipro

protected override Size MeasureOverride(Size availableSize) {
			var desiredWidth = 0.0;
			var desiredHeight = 0.0;

			var availableWidth = availableSize.Width;
			var availableHeight = availableSize.Height;

			var internalChildren = base.InternalChildren;
			if (internalChildren.Count == 2) {
				// Glyph
				internalChildren[1].Measure(new Size(availableWidth, availableHeight));
				availableWidth = Math.Max(0, availableWidth - internalChildren[1].DesiredSize.Width);

				// Text
				internalChildren[0].Measure(new Size(availableWidth, availableHeight));
				
				// Calculate size
				desiredWidth = Math.Ceiling(internalChildren[0].DesiredSize.Width + internalChildren[1].DesiredSize.Width);
				desiredHeight = Math.Max(internalChildren[0].DesiredSize.Height, internalChildren[1].DesiredSize.Height).Round(RoundMode.CeilingToEven);
			}

			return new Size(desiredWidth, desiredHeight);
		}

19 View Source File : SolarHalfYear.cs
License : MIT License
Project Creator : 6tail

public int getIndex()
        {
            return (int)Math.Ceiling(month * 1D / MONTH_COUNT);
        }

19 View Source File : ButterflyFamiliar.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private Buff GetBuff()
        {
            int buffAmount = (int)Math.Ceiling(Math.Sqrt(exp) / 10f);
            int which = Game1.random.Next(10);
            int[] buffs = new int[10];
            for(int i = 0; i < 10; i++)
            {
                buffs[i] = which == i ? buffAmount : 0;

            }

            Buff buff = new Buff(buffs[0], buffs[1], buffs[2], buffs[3], buffs[4], buffs[5], buffs[6], 0, 0, buffs[7], buffs[8], buffs[9], BuffDuration(), "ButterflyFamiliar", ModEntry.SHelper.Translation.Get("butterfly-familiar"));
            buff.which = 4200 + which;
            return buff;
        }

19 View Source File : Mathd.cs
License : MIT License
Project Creator : 734843327

public static double Ceil(double d) {
            return Math.Ceiling(d);
        }

19 View Source File : Transition.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public bool FindPlacementPos()
        {
            // refactor me
            SpherePath.SetCheckPos(SpherePath.CurPos, SpherePath.CurCell);

            CollisionInfo.SlidingNormalValid = false;
            CollisionInfo.ContactPlaneValid = false;
            CollisionInfo.ContactPlaneIsWater = false;

            var transitionState = TransitionalInsert(3);

            var redo = 0;
            transitionState = ValidatePlacementTransition(transitionState, ref redo);

            if (transitionState == TransitionState.OK)
                return true;

            if (!SpherePath.PlacementAllowsSliding)
                return false;

            var adjustDist = 4.0f;
            var adjustRad = adjustDist;
            var sphereRad = SpherePath.LocalSphere[0].Radius;

            var fakeSphere = false;

            if (sphereRad < 0.125f)
            {
                fakeSphere = true;
                adjustRad = 2.0f;
            }
            else if (sphereRad < 0.48f)
            {
                sphereRad = 0.48f;
            }

            var movementDelta = sphereRad;

            var fNumSteps = 4.0f / movementDelta;

            if (fakeSphere)
                fNumSteps *= 0.5f;

            if (fNumSteps <= 1.0f)
                return false;

            var numSteps = (int)Math.Ceiling(fNumSteps);
            var distPerStep = adjustRad / numSteps;
            var radiansPerStep = (float)(Math.PI * distPerStep / sphereRad);

            var totalDist = 0.0f;
            var totalRad = 0.0f;

            for (var i = 0; i < numSteps; i++)
            {
                totalDist += distPerStep;
                totalRad += radiansPerStep;

                var rad = (int)Math.Ceiling(totalRad);
                rad *= 2;
                var angle = 360.0f / rad;

                var frame = new AFrame();

                for (var j = 0; j < rad; j++)
                {
                    SpherePath.SetCheckPos(SpherePath.CurPos, SpherePath.CurCell);
                    frame.set_heading(angle * j);
                    var offset = frame.get_vector_heading() * totalDist;
                    SpherePath.GlobalOffset = AdjustOffset(offset);
                    if (SpherePath.GlobalOffset.Length() >= PhysicsGlobals.EPSILON)
                    {
                        SpherePath.AddOffsetToCheckPos(SpherePath.GlobalOffset);

                        // possibly reset by AdjustOffset
                        CollisionInfo.SlidingNormalValid = false;
                        CollisionInfo.ContactPlaneValid = false;
                        CollisionInfo.ContactPlaneIsWater = false;

                        transitionState = TransitionalInsert(3);
                        transitionState = ValidatePlacementTransition(transitionState, ref redo);

                        if (transitionState == TransitionState.OK)
                            return true;
                    }
                }
            }
            return false;
        }

19 View Source File : HousePayment.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public List<WorldObjectInfo<int>> GetConsumeItems_Inner(List<WorldObject> items)
        {
            var consumeItems = new List<WorldObjectInfo<int>>();

            var remaining = Remaining;

            foreach (var item in items)
            {
                var stackSize = item.StackSize ?? 1;

                var stackValue = item.Value ?? 0;
                var baseValue = item.StackUnitValue ?? 0;

                var amount = item.IsTradeNote ? stackValue : stackSize;

                if (amount <= remaining)
                {
                    consumeItems.Add(new WorldObjectInfo<int>(item, stackSize));
                    remaining -= amount;
                }
                else
                {
                    var consumeAmount = item.IsTradeNote ? (int)Math.Ceiling((float)remaining / baseValue) : remaining;

                    consumeItems.Add(new WorldObjectInfo<int>(item, consumeAmount));
                    remaining = 0;
                }

                if (remaining <= 0)
                    break;
            }

            return consumeItems;
        }

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

public ReadOnlyCollection<SimulatedMouseInput> GetSimulatInputX()
        {
            var magnitudes = new List<SimulatedMouseInput>();

            foreach (var slowMovement in SlowMovements)
            {
                var ceil = (int)Math.Ceiling(slowMovement);
                var timeFactor = ceil / slowMovement;
                SimulatedMouseInput mouseInputData;
                mouseInputData.x = ceil;
                mouseInputData.y = 0;
                mouseInputData.time = MeasurementTime*timeFactor;
                mouseInputData.velocity = Velocity(ceil, 0, mouseInputData.time);
                mouseInputData.angle = 0;
                magnitudes.Add(mouseInputData);
            }

            for (double i = 5; i < MaxVelocity; i+=Increment)
            {
                SimulatedMouseInput mouseInputData;
                var ceil = (int)Math.Ceiling(i);
                var timeFactor = ceil / i;
                mouseInputData.x = ceil;
                mouseInputData.y = 0;
                mouseInputData.time = MeasurementTime*timeFactor;
                mouseInputData.velocity = DecimalCheck(Velocity(ceil, 0, mouseInputData.time));
                mouseInputData.angle = 0;
                magnitudes.Add(mouseInputData);
            }

            return magnitudes.AsReadOnly();
        }

19 View Source File : TextureCache.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

private static Microsoft.Xna.Framework.Color[] LoadPaletteColors(uint paletteID, out int width, out int height)
        {
            var palette = DatManager.PortalDat.ReadFromDat<Palette>(paletteID);

            var numColors = palette.Colors.Count;

            width = Math.Min(numColors, PaletteWidth);
            height = (int)Math.Ceiling((float)numColors / PaletteWidth);

            var colors = new Microsoft.Xna.Framework.Color[width * height];

            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    var colorNum = x + y * PaletteWidth;

                    if (colorNum >= numColors)
                    {
                        colors[colorNum] = new Microsoft.Xna.Framework.Color(0, 0, 0, 0);
                        continue;
                    }

                    var c = palette.Colors[colorNum];

                    var color = new Microsoft.Xna.Framework.Color();
                    color.A = (byte)(c >> 24);
                    color.R = (byte)(c >> 16 & 0xFF);
                    color.G = (byte)(c >> 8 & 0xFF);
                    color.B = (byte)(c & 0xFF);

                    colors[colorNum] = color;
                }
            }
            return colors;
        }

19 View Source File : SolarUtil.cs
License : MIT License
Project Creator : 6tail

public static int getWeeksOfMonth(int year, int month, int start)
        {
            int days = getDaysOfMonth(year, month);
            DateTime firstDay = ExactDate.fromYmd(year, month, 1);
            int week = Convert.ToInt32(firstDay.DayOfWeek.ToString("d"));
            return (int)Math.Ceiling((days + week - start) * 1D / WEEK.Length);
        }

19 View Source File : TickIntervalConverter.cs
License : MIT License
Project Creator : Actipro

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
		#endif
			var doubleValue = Math.Ceiling(System.Convert.ToDouble(value));
			int intValue = System.Convert.ToInt32(doubleValue);

			if (intValue == 0)
				return 1;
			if (intValue == 1)
				return 2;
			if(intValue == 2)
				return 4;
			if (intValue == 3)
				return 6;
			if (intValue == 4)
				return 8;

			return 10;
		}

19 View Source File : Win32.cs
License : MIT License
Project Creator : Abdesol

public static bool CreateCaret(Visual owner, Size size)
		{
			if (owner == null)
				throw new ArgumentNullException("owner");
			HwndSource source = PresentationSource.FromVisual(owner) as HwndSource;
			if (source != null) {
				Vector r = owner.PointToScreen(new Point(size.Width, size.Height)) - owner.PointToScreen(new Point(0, 0));
				return SafeNativeMethods.CreateCaret(source.Handle, IntPtr.Zero, (int)Math.Ceiling(r.X), (int)Math.Ceiling(r.Y));
			} else {
				return false;
			}
		}

19 View Source File : ODataQueryOptionExtensions.cs
License : MIT License
Project Creator : Adoxio

private static Fetch Apply(this Fetch fetch, SkipQueryOption skipQueryOption)
		{
			if (!fetch.PageSize.HasValue)
			{
				return fetch;
			}

			if (skipQueryOption != null)
			{
				fetch.PageNumber = skipQueryOption.Value > 0 ? (int)Math.Ceiling(skipQueryOption.Value / (double)fetch.PageSize.Value) + 1 : 1;
			}

			return fetch;
		}

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
			int view = Interlocked.Increment(ref _view);
			StringBuilder sb = new StringBuilder();
			IDictionary options_copy = new Hashtable();
			foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
			sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}

//namespace TplDynamicCodeGenerate {{
	public clreplaced TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
		public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
			FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ? 
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
			Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
			Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
			int[] TPL__blocks_stack_peek;
			List<IDictionary> TPL__forc = new List<IDictionary>();
			Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
				IDictionary nEwoPtIoNs = new Hashtable();
				foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
					nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
				foreach (IDictionary TPL__forc_dIc in TPL__forc)
					foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
						nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
				return nEwoPtIoNs;
			}});
			FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
				if (exp is bool) return (bool)exp;
				if (exp == null) return false;
				if (exp is int && (int)exp == 0) return false;
				if (exp is string && (string)exp == string.Empty) return false;
				if (exp is long && (long)exp == 0) return false;
				if (exp is short && (short)exp == 0) return false;
				if (exp is byte && (byte)exp == 0) return false;
				if (exp is double && (double)exp == 0) return false;
				if (exp is float && (float)exp == 0) return false;
				if (exp is decimal && (decimal)exp == 0) return false;
				return true;
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
				if (pArMs == null || pArMs.Length == 0) return;
				foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");

			#region {miss}...{/miss}块内容将不被解析
			string[] tmp_content_arr = _reg_miss.Split(tplcode);
			if (tmp_content_arr.Length > 1) {
				sb.AppendFormat(@"
			string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
				int miss_len = -1;
				for (int a = 1; a < tmp_content_arr.Length; a += 2) {
					sb.Append(string.Concat(@"
			TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
					tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			#region 扩展语法如 <div @if="表达式"></div>
			tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
											  //处理 {% %} 块 c#代码
			tmp_content_arr = _reg_code.Split(tplcode);
			if (tmp_content_arr.Length == 1) {
				tplcode = Utils.GetConstString(tplcode)
					.Replace("{%", "{$TEMPLATE__CODE}")
					.Replace("%}", "{/$TEMPLATE__CODE}");
			} else {
				tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
				for (int a = 1; a < tmp_content_arr.Length; a += 4) {
					tmp_content_arr[a] = "{$TEMPLATE__CODE}";
					tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
					tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			sb.Append(@"
			tOuTpUt.Append(""");

			string error = null;
			int tpl_tmpid = 0;
			int forc_i = 0;
			string extends = null;
			Stack<string> codeTree = new Stack<string>();
			Stack<string> forEndRepl = new Stack<string>();
			sb.Append(_reg.Replace(tplcode, delegate (Match m) {
				string _0 = m.Groups[0].Value;
				if (!string.IsNullOrEmpty(error)) return _0;

				string _1 = m.Groups[1].Value.Trim(' ', '\t');
				string _2 = m.Groups[2].Value
					.Replace("\\\\", "\\")
					.Replace("\\\"", "\"");
				_2 = Utils.ReplaceSingleQuote(_2);

				switch (_1) {
					#region $TEMPLATE__CODE--------------------------------------------------
					case "$TEMPLATE__CODE":
						codeTree.Push(_1);
						return @""");
";
					case "/$TEMPLATE__CODE":
						string pop = codeTree.Pop();
						if (pop != "$TEMPLATE__CODE") {
							codeTree.Push(pop);
							error = "编译出错,{% 与 %} 并没有配对";
							return _0;
						}
						return @"
			tOuTpUt.Append(""";
					#endregion
					case "include":
						return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
			tOuTpUt.Append(""", _2);
					case "import":
						return _0;
					case "module":
						return _0;
					case "/module":
						return _0;
					case "extends":
						//{extends ../inc/layout.html}
						if (string.IsNullOrEmpty(extends) == false) return _0;
						extends = _2;
						return string.Empty;
					case "block":
						codeTree.Push("block");
						return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
					case "/block":
						codeTreeEnd(codeTree, "block");
						return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";

					#region ##---------------------------------------------------------
					case "#":
						if (_2[0] == '#')
							return string.Format(@""");
			try {{ Print({0}); }} catch {{ }}
			tOuTpUt.Append(""", _2.Substring(1));
						return string.Format(@""");
			Print({0});
			tOuTpUt.Append(""", _2);
					#endregion
					#region for--------------------------------------------------------
					case "for":
						forc_i++;
						int cur_tpl_tmpid = tpl_tmpid;
						string sb_endRepl = string.Empty;
						StringBuilder sbfor = new StringBuilder();
						sbfor.Append(@""");");
						Match mfor = _reg_forin.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{1} != null)
	foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = TPL__tmp{2};
		{0} = TPL__tmp{2};
		tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_foron.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							if (!string.IsNullOrEmpty(mfor3)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor3, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
								if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{2} != null)
	foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
		{0} = TPL__tmp{1}.Key;
		TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		{0} = TPL__tmp{1}.Value;
		TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor3))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		tOuTpUt.Append(""");
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_forab.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {5};
	{5} = {3} - 1;
	if ({5} == null) {5} = 0;
	var TPL__tmp{2} = {4} + 1;
	while (++{5} < TPL__tmp{2}) {{
		TPL__tmp{0}[""{5}""] = {5};
		tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						return _0;
					case "/for":
						if (--forc_i < 0) return _0;
						codeTreeEnd(codeTree, "for");
						return string.Format(@""");
	}}{0}
	TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
			tOuTpUt.Append(""", forEndRepl.Pop());
					#endregion
					#region if---------------------------------------------------------
					case "if":
						codeTree.Push("if");
						return string.Format(@""");
			if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "elseif":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return string.Format(@""");
			}} else if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "else":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return @""");
			} else {
			tOuTpUt.Append(""";
					case "/if":
						codeTreeEnd(codeTree, "if");
						return @""");
			}
			tOuTpUt.Append(""";
						#endregion
				}
				return _0;
			}));

			sb.Append(@""");");
			if (string.IsNullOrEmpty(extends) == false) {
				sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
	if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
		int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
		int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
		foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
			if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
			int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
			if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
				eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
		}}
		eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
	}}
}}
return eXtEnDs_ReT;
", extends);
			} else {
				sb.Append(@"
return rTn;");
			}
			sb.Append(@"
		}
	}
//}
");
			var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
			int dim_idx = sb.ToString().IndexOf(str) + str.Length;
			foreach (string dic_name in options_copy.Keys) {
				sb.Insert(dim_idx, string.Format(@"
			dynamic {0} = oPtIoNs[""{0}""];", dic_name));
			}
			//Console.WriteLine(sb.ToString());
			return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
		}

19 View Source File : ButterflyFamiliar.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private int Buff()
        {
            return (int)Math.Ceiling(Math.Sqrt(exp / 10f));
        }

19 View Source File : LootGenerationFactory_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static int RollItemMaxMana_New(WorldObject wo, TreasureRoll roll, int maxSpellMana)
        {
            // verified matches up with magloot eor logs

            var workmanship = WorkmanshipChance.GetModifier(wo.ItemWorkmanship - 1);

            (int min, int max) range;

            if (roll.IsClothing || roll.IsArmor || roll.IsWeapon || roll.IsDinnerware)
            {
                range.min = 6;
                range.max = 15;
            }
            else if (roll.IsJewelry)
            {
                // includes crowns
                range.min = 12;
                range.max = 20;
            }
            else if (roll.IsGem)
            {
                range.min = 1;
                range.max = 1;
            }
            else
            {
                log.Error($"RollItemMaxMana({wo.Name}, {roll.ItemType}, {maxSpellMana}) - unknown item type");
                return 1;
            }

            var rng = ThreadSafeRandom.Next(range.min, range.max);

            return (int)Math.Ceiling(maxSpellMana * workmanship * rng);
        }

19 View Source File : LootGenerationFactory_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static float CalculateManaRate(int maxBaseMana)
        {
            if (maxBaseMana <= 0)
                maxBaseMana = 1;

            // verified with eor data
            return -1.0f / (float)Math.Ceiling(1200.0f / maxBaseMana);
        }

19 View Source File : Arc.cs
License : MIT License
Project Creator : 3RD-Dimension

public override IEnumerable<Motion> Split(double length)
		{
			int divisions = (int)Math.Ceiling(Length / length);

			if (divisions < 1)
				divisions = 1;

			Vector3 lastEnd = Start;

			for (int i = 1; i <= divisions; i++)
			{
				Vector3 end = Interpolate(((double)i) / divisions);

				Arc immediate = new Arc();
				immediate.Start = lastEnd;
				immediate.End = end;
				immediate.Feed = Feed;
				immediate.Direction = Direction;
				immediate.Plane = Plane;
				immediate.U = U;
				immediate.V = V;

				yield return immediate;

				lastEnd = end;
			}
		}

19 View Source File : LootGenerationFactory_Magic.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static int RollSpellcraft(WorldObject wo, TreasureRoll roll)
        {
            var maxSpellPower = GetMaxSpellPower(wo);

            (float min, float max) range = (1.0f, 1.0f);

            if (roll.IsClothing || roll.IsArmor || roll.IsWeapon || roll.IsJewelry || roll.IsDinnerware)
            {
                range.min = 0.9f;
                range.max = 1.1f;
            }
            else if (!roll.IsGem)
            {
                log.Error($"RollSpellcraft({wo.Name}, {roll.ItemType}) - unknown item type");
            }

            var rng = ThreadSafeRandom.Next(range.min, range.max);

            var spellcraft = (int)Math.Ceiling(maxSpellPower * rng);

            // retail was capped at 370
            spellcraft = Math.Min(spellcraft, 370);

            return spellcraft;
        }

19 View Source File : Mathd.cs
License : MIT License
Project Creator : 734843327

public static int CeilToInt(double d) {
            return (int)Math.Ceiling(d);
        }

19 View Source File : Transition.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public bool FindPlacementPos()
        {
            // refactor me
            SpherePath.SetCheckPos(SpherePath.CurPos, SpherePath.CurCell);

            CollisionInfo.SlidingNormalValid = false;
            CollisionInfo.ContactPlaneValid = false;
            CollisionInfo.ContactPlaneIsWater = false;

            var transitionState = TransitionalInsert(3);

            var redo = 0;
            transitionState = ValidatePlacementTransition(transitionState, ref redo);

            if (transitionState == TransitionState.OK)
                return true;

            if (!SpherePath.PlacementAllowsSliding)
                return false;

            var adjustDist = 4.0f;
            var adjustRad = adjustDist;
            var sphereRad = SpherePath.LocalSphere[0].Radius;

            var fakeSphere = false;

            if (sphereRad < 0.125f)
            {
                fakeSphere = true;
                adjustRad = 2.0f;
            }
            else if (sphereRad < 0.48f)
            {
                sphereRad = 0.48f;
            }

            var movementDelta = sphereRad;

            var fNumSteps = 4.0f / movementDelta;

            if (fakeSphere)
                fNumSteps *= 0.5f;

            if (fNumSteps <= 1.0f)
                return false;

            var numSteps = (int)Math.Ceiling(fNumSteps);
            var distPerStep = adjustRad / numSteps;
            var radiansPerStep = (float)(Math.PI * distPerStep / sphereRad);

            var totalDist = 0.0f;
            var totalRad = 0.0f;

            for (var i = 0; i < numSteps; i++)
            {
                totalDist += distPerStep;
                totalRad += radiansPerStep;

                var rad = (int)Math.Ceiling(totalRad);
                rad *= 2;
                var angle = 360.0f / rad;

                var frame = new AFrame();

                for (var j = 0; j < rad; j++)
                {
                    SpherePath.SetCheckPos(SpherePath.CurPos, SpherePath.CurCell);
                    frame.set_heading(angle * j);
                    var offset = frame.get_vector_heading() * totalDist;
                    SpherePath.GlobalOffset = AdjustOffset(offset);
                    if (SpherePath.GlobalOffset.Length() >= PhysicsGlobals.EPSILON)
                    {
                        SpherePath.AddOffsetToCheckPos(SpherePath.GlobalOffset);

                        // possibly reset by AdjustOffset
                        CollisionInfo.SlidingNormalValid = false;
                        CollisionInfo.ContactPlaneValid = false;
                        CollisionInfo.ContactPlaneIsWater = false;

                        transitionState = TransitionalInsert(3);
                        transitionState = ValidatePlacementTransition(transitionState, ref redo);

                        if (transitionState == TransitionState.OK)
                            return true;
                    }
                }
            }
            return false;
        }

19 View Source File : MovementSystem.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static int JumpStaminaCost(float power, float burden, bool pk)
        {
            if (pk)
                return (int)((power + 1.0f) * 100.0f);
            else
                return (int)Math.Ceiling((burden + 0.5f) * power * 8.0f + 2.0f);
        }

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

private ExtentInfo GetExtentInfo(Size viewPortSize)
        {
            if (_itemsControl == null)
            {
                return new ExtentInfo();
            }

            var itemsPerLine = Math.Max((int)Math.Floor(viewPortSize.Width / ItemWidth), 1);
            var totalLines = (int)Math.Ceiling((double)_itemsControl.Items.Count / itemsPerLine);
            var extentHeight = Math.Max(totalLines * ItemHeight, viewPortSize.Height);

            return new ExtentInfo
            {
                ItemsPerLine = itemsPerLine,
                TotalLines = totalLines,
                ExtentHeight = extentHeight,
                MaxVerticalOffset = extentHeight - viewPortSize.Height,
            };
        }

19 View Source File : Gem.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void ActOnUse(WorldObject activator, bool confirmed)
        {
            if (!(activator is Player player))
                return;

            if (player.IsBusy || player.Teleporting || player.suicideInProgress)
            {
                player.SendWeenieError(WeenieError.YoureTooBusy);
                return;
            }

            if (player.IsJumping)
            {
                player.SendWeenieError(WeenieError.YouCantDoThatWhileInTheAir);
                return;
            }

            if (!string.IsNullOrWhiteSpace(UseSendsSignal))
            {
                player.CurrentLandblock?.EmitSignal(player, UseSendsSignal);
                return;
            }

            // handle rare gems
            if (RareId != null && player.GetCharacterOption(CharacterOption.ConfirmUseOfRareGems) && !confirmed)
            {
                var msg = $"Are you sure you want to use {Name}?";
                var confirm = new Confirmation_Custom(player.Guid, () => ActOnUse(activator, true));
                if (!player.ConfirmationManager.EnqueueSend(confirm, msg))
                    player.SendWeenieError(WeenieError.ConfirmationInProgress);
                return;
            }

            if (RareUsesTimer)
            {
                var currentTime = Time.GetUnixTime();

                var timeElapsed = currentTime - player.LastRareUsedTimestamp;

                if (timeElapsed < RareTimer)
                {
                    // TODO: get retail message
                    var remainTime = (int)Math.Ceiling(RareTimer - timeElapsed);
                    player.Session.Network.EnqueueSend(new GameMessageSystemChat($"You may use another timed rare in {remainTime}s", ChatMessageType.Broadcast));
                    return;
                }
            }

            if (UseUserAnimation != MotionCommand.Invalid)
            {
                // some gems have UseUserAnimation and UseSound, similar to food
                // eg. 7559 - Condensed Dispel Potion

                // the animation is also weird, and differs from food, in that it is the full animation
                // instead of stopping at the 'eat/drink' point... so we preplaced 0.5 here?

                var animMod = (UseUserAnimation == MotionCommand.MimeDrink || UseUserAnimation == MotionCommand.MimeEat) ? 0.5f : 1.0f;

                player.ApplyConsumable(UseUserAnimation, () => UseGem(player), animMod);
            }
            else
                UseGem(player);
        }

19 View Source File : MainWindow.xaml.MachineStatus.cs
License : MIT License
Project Creator : 3RD-Dimension

private void Machine_FileChanged()
		{
			try
			{
				ToolPath = GCodeFile.FromList(machine.File);
				GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); // prevents considerable increase in memory usage
			}
			catch (Exception ex)
			{
				MessageBox.Show("Could not parse GCode File, no preview/editing available\nrun this file at your own risk\n" + ex.Message + "\n\n\ninternal:\n" + ex.StackTrace);
			}

			if (ToolPath.Warnings.Count > 0)
			{
                if (Properties.Settings.Default.ShowWarningWindow) // If ShowWarningWindow == True, Display when file loaded
                { 
				WarningWindow ww = new WarningWindow(@"Parsing this file resulted in some warnings!
Do not use GCode Sender's edit functions unless you are sure that these warnings can be ignored!
If you use edit functions, check the output file for errors before running the gcode!
Be aware that the affected lines will likely move when using edit functions." + "\n\n" + "The warning is only applicable to what will be displayed in the viewer, " +
"and will not affect the normal running of the code." + "\n\n", ToolPath.Warnings);

				ww.ShowDialog();
			    }
            }

            if (Properties.Settings.Default.EnableCodePreview)
				ToolPath.GetModel(ModelLine, ModelRapid, ModelArc);

			RunFileLength.Text = machine.File.Count.ToString();
			FileRunTime = TimeSpan.Zero;
			RunFileDuration.Text = ToolPath.TotalTime.ToString(@"hh\:mm\:ss");
			RunFileRunTime.Text = "00:00:00";

			int digits = (int)Math.Ceiling(Math.Log10(machine.File.Count));

			string format = "D" + digits;


			ListViewFile.Items.Clear();

			for (int line = 0; line < machine.File.Count; line++)
			{
				TextBlock tb = new TextBlock() { Text = $"{(line + 1).ToString(format)} : {machine.File[line]}" };

				if (machine.PauseLines[line])
					tb.Background = Brushes.YellowGreen;

				ListViewFile.Items.Add(tb);
			}

			TextBlock tbFinal = new TextBlock() { Text = "-- FILE END --" };
			ListViewFile.Items.Add(tbFinal);

			if (ToolPath.ContainsMotion)
			{
				ModelFileBoundary.Points.Clear();
				Point3DCollection boundary = new Point3DCollection();

				Vector3 MinPoint = ToolPath.MinFeed;
				Vector3 MaxPoint = ToolPath.MaxFeed;

				for (int ax = 0; ax < 3; ax++)
				{
					for (int mask = 0; mask < 4; mask++)
					{
						Vector3 point = MinPoint;

						for (int i = 0; i < 2; i++)
						{
							// binary integer logic? hell yeah!
							if (((mask >> i) & 0x01) == 1)
							{
								point[(ax + i + 1) % 3] = MaxPoint[(ax + i + 1) % 3];
							}
						}

						boundary.Add(point.ToPoint3D());

						point[ax] = MaxPoint[ax];
						boundary.Add(point.ToPoint3D());
					}
				}

				ModelFileBoundary.Points = boundary;

				ModelTextMinPoint.Text = string.Format(Constants.DecimalOutputFormat, "(-X {0:0.###}, -Y {1:0.###}, -Z {2:0.###})", MinPoint.X, MinPoint.Y, MinPoint.Z);
				ModelTextMaxPoint.Text = string.Format(Constants.DecimalOutputFormat, "(+X {0:0.###}, +Y {1:0.###}, +Z {2:0.###})", MaxPoint.X, MaxPoint.Y, MaxPoint.Z);
				ModelTextMinPoint.Position = MinPoint.ToPoint3D();
				ModelTextMaxPoint.Position = MaxPoint.ToPoint3D();
				ModelFileBoundaryPoints.Points.Clear();
				ModelFileBoundaryPoints.Points.Add(MinPoint.ToPoint3D());
				ModelFileBoundaryPoints.Points.Add(MaxPoint.ToPoint3D());
			}
			else
			{
				ModelFileBoundary.Points.Clear();
				ModelFileBoundaryPoints.Points.Clear();
				ModelTextMinPoint.Text = "";
				ModelTextMaxPoint.Text = "";
			}
		}

19 View Source File : Vendor.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private uint GetSellCost(int? value, ItemType? itemType)
        {
            var sellRate = SellPrice ?? 1.0;
            if (itemType == ItemType.PromissoryNote)
                sellRate = 1.15;

            var cost = Math.Max(1, (uint)Math.Ceiling(((float)sellRate * (value ?? 0)) - 0.1));
            return cost;
        }

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

public ReadOnlyCollection<SimulatedMouseInput> GetSimulatedInputY()
        {
            var magnitudes = new List<SimulatedMouseInput>();

            foreach (var slowMovement in SlowMovements)
            {
                var ceil = (int)Math.Ceiling(slowMovement);
                var timeFactor = ceil / slowMovement;
                SimulatedMouseInput mouseInputData;
                mouseInputData.x = 0;
                mouseInputData.y = ceil;
                mouseInputData.time = MeasurementTime*timeFactor;
                mouseInputData.velocity = DecimalCheck(Velocity(0, ceil, mouseInputData.time));
                mouseInputData.angle = 0;
                magnitudes.Add(mouseInputData);
            }

            for (double i = 5; i < MaxVelocity; i+=Increment)
            {
                SimulatedMouseInput mouseInputData;
                var ceil = (int)Math.Ceiling(i);
                var timeFactor = ceil / i;
                mouseInputData.x = 0;
                mouseInputData.y = ceil;
                mouseInputData.time = MeasurementTime*timeFactor;
                mouseInputData.velocity = DecimalCheck(Velocity(0, ceil, mouseInputData.time));
                mouseInputData.angle = Math.PI / 2;
                magnitudes.Add(mouseInputData);
            }

            return magnitudes.AsReadOnly();
        }

19 View Source File : FileContainerHttpClient.cs
License : MIT License
Project Creator : actions

[EditorBrowsable(EditorBrowsableState.Never)]
        public async Task<HttpResponseMessage> UploadFileAsync(
            Int64 containerId,
            String itemPath,
            Stream fileStream,
            byte[] contentId,
            Int64 fileLength,
            Boolean isGzipped,
            Guid scopeIdentifier,
            CancellationToken cancellationToken = default(CancellationToken),
            int chunkSize = c_defaultChunkSize,
            int chunkRetryTimes = c_defaultChunkRetryTimes,
            bool uploadFirstChunk = false,
            Object userState = null)
        {
            if (containerId < 1)
            {
                throw new ArgumentException(WebApiResources.ContainerIdMustBeGreaterThanZero(), "containerId");
            }

            if (chunkSize > c_maxChunkSize)
            {
                chunkSize = c_maxChunkSize;
            }

            // if a contentId is specified but the chunk size is not a 2mb multiple error
            if (contentId != null && (chunkSize % c_ContentChunkMultiple) != 0)
            {
                throw new ArgumentException(FileContainerResources.ChunksizeWrongWithContentId(c_ContentChunkMultiple), "chunkSize");
            }

            ArgumentUtility.CheckForNull(fileStream, "fileStream");

            ApiResourceVersion gzipSupportedVersion = new ApiResourceVersion(new Version(1, 0), 2);
            ApiResourceVersion requestVersion = await NegotiateRequestVersionAsync(FileContainerResourceIds.FileContainer, s_currentApiVersion, userState, cancellationToken).ConfigureAwait(false);

            if (isGzipped
                && (requestVersion.ApiVersion < gzipSupportedVersion.ApiVersion
                    || (requestVersion.ApiVersion == gzipSupportedVersion.ApiVersion && requestVersion.ResourceVersion < gzipSupportedVersion.ResourceVersion)))
            {
                throw new ArgumentException(FileContainerResources.GzipNotSupportedOnServer(), "isGzipped");
            }

            if (isGzipped && fileStream.Length >= fileLength)
            {
                throw new ArgumentException(FileContainerResources.BadCompression(), "fileLength");
            }

            HttpRequestMessage requestMessage = null;
            List<KeyValuePair<String, String>> query = AppendItemQueryString(itemPath, scopeIdentifier);

            if (fileStream.Length == 0)
            {
                // zero byte upload
                FileUploadTrace(itemPath, $"Upload zero byte file '{itemPath}'.");
                requestMessage = await CreateRequestMessageAsync(HttpMethod.Put, FileContainerResourceIds.FileContainer, routeValues: new { containerId = containerId }, version: s_currentApiVersion, queryParameters: query, userState: userState, cancellationToken: cancellationToken).ConfigureAwait(false);
                return await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
            }

            bool multiChunk = false;
            int totalChunks = 1;
            if (fileStream.Length > chunkSize)
            {
                totalChunks = (int)Math.Ceiling(fileStream.Length / (double)chunkSize);
                FileUploadTrace(itemPath, $"Begin chunking upload file '{itemPath}', chunk size '{chunkSize} Bytes', total chunks '{totalChunks}'.");
                multiChunk = true;
            }
            else
            {
                FileUploadTrace(itemPath, $"File '{itemPath}' will be uploaded in one chunk.");
                chunkSize = (int)fileStream.Length;
            }

            StreamParser streamParser = new StreamParser(fileStream, chunkSize);
            SubStream currentStream = streamParser.GetNextStream();
            HttpResponseMessage response = null;

            Byte[] dataToSend = new Byte[chunkSize];
            int currentChunk = 0;
            Stopwatch uploadTimer = new Stopwatch();
            while (currentStream.Length > 0 && !cancellationToken.IsCancellationRequested)
            {
                currentChunk++;

                for (int attempt = 1; attempt <= chunkRetryTimes && !cancellationToken.IsCancellationRequested; attempt++)
                {
                    if (attempt > 1)
                    {
                        TimeSpan backoff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
                        FileUploadTrace(itemPath, $"Backoff {backoff.TotalSeconds} seconds before attempt '{attempt}' chunk '{currentChunk}' of file '{itemPath}'.");
                        await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
                        currentStream.Seek(0, SeekOrigin.Begin);
                    }

                    FileUploadTrace(itemPath, $"Attempt '{attempt}' for uploading chunk '{currentChunk}' of file '{itemPath}'.");

                    // inorder for the upload to be retryable, we need the content to be re-readable
                    // to ensure this we copy the chunk into a byte array and send that
                    // chunk size ensures we can convert the length to an int
                    int bytesToCopy = (int)currentStream.Length;
                    using (MemoryStream ms = new MemoryStream(dataToSend))
                    {
                        await currentStream.CopyToAsync(ms, bytesToCopy, cancellationToken).ConfigureAwait(false);
                    }

                    // set the content and the Content-Range header
                    HttpContent byteArrayContent = new ByteArrayContent(dataToSend, 0, bytesToCopy);
                    byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    byteArrayContent.Headers.ContentLength = currentStream.Length;
                    byteArrayContent.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(currentStream.StartingPostionOnOuterStream,
                                                                                                             currentStream.EndingPostionOnOuterStream,
                                                                                                             streamParser.Length);
                    FileUploadTrace(itemPath, $"Generate new HttpRequest for uploading file '{itemPath}', chunk '{currentChunk}' of '{totalChunks}'.");

                    try
                    {
                        if (requestMessage != null)
                        {
                            requestMessage.Dispose();
                            requestMessage = null;
                        }

                        requestMessage = await CreateRequestMessageAsync(
                            HttpMethod.Put,
                            FileContainerResourceIds.FileContainer,
                            routeValues: new { containerId = containerId },
                            version: s_currentApiVersion,
                            content: byteArrayContent,
                            queryParameters: query,
                            userState: userState,
                            cancellationToken: cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to create HttpRequest. Error: {ex.ToString()}.");
                        continue;
                    }

                    if (isGzipped)
                    {
                        //add gzip header info
                        byteArrayContent.Headers.ContentEncoding.Add("gzip");
                        byteArrayContent.Headers.Add("x-tfs-filelength", fileLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    if (contentId != null)
                    {
                        byteArrayContent.Headers.Add("x-vso-contentId", Convert.ToBase64String(contentId)); // Base64FormattingOptions.None is default when not supplied
                    }

                    FileUploadTrace(itemPath, $"Start uploading file '{itemPath}' to server, chunk '{currentChunk}'.");
                    uploadTimer.Restart();

                    try
                    {
                        if (response != null)
                        {
                            response.Dispose();
                            response = null;
                        }

                        response = await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to send request to server. Error: {ex.ToString()}.");
                        continue;
                    }

                    uploadTimer.Stop();
                    FileUploadTrace(itemPath, $"Finished upload chunk '{currentChunk}' of file '{itemPath}', elapsed {uploadTimer.ElapsedMilliseconds} (ms), response code '{response.StatusCode}'.");

                    if (multiChunk)
                    {
                        FileUploadProgress(itemPath, currentChunk, (int)Math.Ceiling(fileStream.Length / (double)chunkSize));
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        break;
                    }
                    else if (IsFastFailResponse(response))
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request and cannot continue.");
                        break;
                    }
                    else
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request.");
                        continue;
                    }
                }

                // if we don't have success then bail and return the failed response
                if (!response.IsSuccessStatusCode)
                {
                    break;
                }

                if (contentId != null && response.StatusCode == HttpStatusCode.Created)
                {
                    // no need to keep uploading since the server said it has all the content
                    FileUploadTrace(itemPath, $"Stop chunking upload the rest of the file '{itemPath}', since server already has all the content.");
                    break;
                }

                currentStream = streamParser.GetNextStream();
                if (uploadFirstChunk)
                {
                    break;
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            return response;
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private unsafe string PrepareCroppedLayers(InputMode inputMode, RectangleF cropRect)
        {
            if (inputMode == InputMode.NoInput)
            {
                return string.Empty;
            }

            IReadOnlyList<GmicLayer> layers = GetRequestedLayers(inputMode);

            if (layers.Count == 0)
            {
                return string.Empty;
            }

            if (memoryMappedFiles.Capacity < layers.Count)
            {
                memoryMappedFiles.Capacity = layers.Count;
            }

            StringBuilder reply = new StringBuilder();

            foreach (GmicLayer layer in layers)
            {
                Surface surface = layer.Surface;
                bool disposeSurface = false;
                int destinationImageStride = surface.Stride;

                if (cropRect != WholeImageCropRect)
                {
                    int cropX = (int)Math.Floor(cropRect.X * layer.Width);
                    int cropY = (int)Math.Floor(cropRect.Y * layer.Height);
                    int cropWidth = (int)Math.Min(layer.Width - cropX, 1 + Math.Ceiling(cropRect.Width * layer.Width));
                    int cropHeight = (int)Math.Min(layer.Height - cropY, 1 + Math.Ceiling(cropRect.Height * layer.Height));

                    try
                    {
                        surface = layer.Surface.CreateWindow(cropX, cropY, cropWidth, cropHeight);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        throw new InvalidOperationException(string.Format("Surface.CreateWindow bounds invalid, cropRect={0}", cropRect.ToString()), ex);
                    }
                    disposeSurface = true;
                    destinationImageStride = cropWidth * ColorBgra.SizeOf;
                }

                string mapName = "pdn_" + Guid.NewGuid().ToString();

                try
                {
                    MemoryMappedFile file = MemoryMappedFile.CreateNew(mapName, surface.Scan0.Length);
                    memoryMappedFiles.Add(file);

                    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                    {
                        byte* destination = null;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref destination);

                            for (int y = 0; y < surface.Height; y++)
                            {
                                ColorBgra* src = surface.GetRowAddressUnchecked(y);
                                byte* dst = destination + (y * destinationImageStride);

                                Buffer.MemoryCopy(src, dst, destinationImageStride, destinationImageStride);
                            }
                        }
                        finally
                        {
                            if (destination != null)
                            {
                                accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                            }
                        }
                    }
                }
                finally
                {
                    if (disposeSurface)
                    {
                        surface.Dispose();
                    }
                }

                reply.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "{0},{1},{2},{3}\n",
                    mapName,
                    surface.Width.ToString(CultureInfo.InvariantCulture),
                    surface.Height.ToString(CultureInfo.InvariantCulture),
                    destinationImageStride.ToString(CultureInfo.InvariantCulture));
            }

            return reply.ToString();
        }

19 View Source File : DoubleToIntConverter.cs
License : MIT License
Project Creator : Actipro

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
		#endif
			if (value is double) {
				var intValue = (int) Math.Ceiling((double) value);
				return twelveDivisors[intValue];
			}

			return value;
		}

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

public ReadOnlyCollection<SimulatedMouseInput> GetSimulatedInput()
        {
            var magnitudes = new List<SimulatedMouseInput>();

            foreach (var slowMoveX in SlowMovements)
            {
                var slowMoveY = 0.0;
                var ceilX = (int)Math.Round(slowMoveX*50);
                var ceilY = (int)Math.Round(slowMoveY*50);
                var ceilMagnitude = Magnitude(ceilX, ceilY);
                var timeFactor = ceilMagnitude / Magnitude(slowMoveX, slowMoveY);

                SimulatedMouseInput mouseInputData;
                mouseInputData.x = ceilX;
                mouseInputData.y = ceilY;
                mouseInputData.time = MeasurementTime*timeFactor;
                mouseInputData.velocity = DecimalCheck(Velocity(ceilX, ceilY, mouseInputData.time));
                mouseInputData.angle = Math.Atan2(ceilY, ceilX);
                magnitudes.Add(mouseInputData);
            }

            for (double i = 5; i < MaxVelocity; i+=Increment)
            {
                SimulatedMouseInput mouseInputData;
                var ceil = (int)Math.Ceiling(i);
                var timeFactor = ceil / i;
                mouseInputData.x = ceil;
                mouseInputData.y = 0;
                mouseInputData.time = MeasurementTime * timeFactor;
                mouseInputData.velocity = DecimalCheck(Velocity(ceil, 0, mouseInputData.time));
                mouseInputData.angle = Math.Atan2(ceil, 0);
                magnitudes.Add(mouseInputData);
            }

            magnitudes.Sort((m1, m2) => m1.velocity.CompareTo(m2.velocity));

            return magnitudes.AsReadOnly();
        }

19 View Source File : CustomMargin.cs
License : MIT License
Project Creator : Actipro

private void OnViewTextAreaLayout(object sender, TextViewTextAreaLayoutEventArgs e) {
			if (this.Visibility == Visibility.Visible) {
				// Determine min width
				int digitCount = view.CurrentSnapshot.Length.ToString(CultureInfo.CurrentCulture).Length;

				// Get typeface
				Typeface typeface = new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, this.FontStretch);
				double fontSize = this.FontSize;

				// Get the formatted text
				FormattedText text = new FormattedText(new string('0', digitCount) + " chars", CultureInfo.CurrentCulture, 
					FlowDirection.LeftToRight, typeface, fontSize, this.Foreground, VisualTreeHelper.GetDpi(view.VisualElement).PixelsPerDip);

				// Update the min width to ensure all digits will fit when on the last line
				double minWidth = Math.Max(42, Math.Ceiling(text.WidthIncludingTrailingWhitespace) + this.Padding.Left + this.Padding.Right);
				if (this.MinWidth != minWidth)
					this.MinWidth = minWidth;
			}
		}

19 View Source File : Solar.cs
License : MIT License
Project Creator : 6tail

public List<string> getFestivals()
        {
            List<string> l = new List<string>();
            //获取几月几日对应的节日
            try
            {
                l.Add(SolarUtil.FESTIVAL[month + "-" + day]);
            }
            catch { }
            //计算几月第几个星期几对应的节日
            int weeks = (int)Math.Ceiling(day / 7D);
            //星期几,0代表星期天
            int week = getWeek();
            try
            {
                l.Add(SolarUtil.WEEK_FESTIVAL[month + "-" + weeks + "-" + week]);
            }
            catch { }
            return l;
        }

19 View Source File : PrimeFactory.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static BigInteger GetApproximateValueFromIndex(UInt64 n)
		{
			if (n < 6)
			{
				return primes[(int)n];
			}

			double fn = (double)n;
			double flogn = Math.Log(n);
			double flog2n = Math.Log(flogn);

			double upper;

			if (n >= 688383)    /* Dusart 2010 page 2 */
			{
				upper = fn * (flogn + flog2n - 1.0 + ((flog2n - 2.00) / flogn));
			}
			else if (n >= 178974)    /* Dusart 2010 page 7 */
			{
				upper = fn * (flogn + flog2n - 1.0 + ((flog2n - 1.95) / flogn));
			}
			else if (n >= 39017)    /* Dusart 1999 page 14 */
			{
				upper = fn * (flogn + flog2n - 0.9484);
			}
			else                    /* Modified from Robin 1983 for 6-39016 _only_ */
			{
				upper = fn * (flogn + 0.6000 * flog2n);
			}

			if (upper >= (double)UInt64.MaxValue)
			{
				throw new OverflowException($"{upper} > {UInt64.MaxValue}");
			}

			return new BigInteger((UInt64)Math.Ceiling(upper));
		}

19 View Source File : CommitLogServer.cs
License : MIT License
Project Creator : abdullin

async Task ScheduleStore() {
            var next = TimeSpan.FromSeconds(Math.Ceiling(_env.Time.TotalSeconds * 2) / 2);
            if (_scheduled != next) {
                _scheduled = next;
                await _env.Delay(_scheduled - _env.Time);
                if (_buffer.Count > 0) {
                    await _env.SimulateWork((5 * _buffer.Count + 10).Ms());
                    _stored.AddRange(_buffer);

                    _env.Debug($"Store {_buffer.Count} events");
                    _buffer.Clear();
                }
            }
        }

19 View Source File : SearchController.cs
License : MIT License
Project Creator : Adoxio

[HttpPost]
		[JsonHandlerError]
		[AjaxValidateAntiForgeryToken]
		public ActionResult Search(Dictionary<string, string> parameters, string query, string logicalNames, string filter, int pageNumber, int pageSize = DefaultPageSize,
			FacetConstraints[] facetConstraints = null, string sortingOption = "Relevance", int initialConstraintsToLocalize = DefaultInitialConstraintsToLocalize)
		{
			if (pageSize < 0)
			{
				pageSize = DefaultPageSize;
			}

			if (pageSize > DefaultMaxPageSize)
			{
				pageSize = DefaultMaxPageSize;
			}

			var queryText = GetQueryText(query, parameters);
			var filterText = GetFilterText(filter, parameters);
			ContextLanguageInfo contextLanguage;
			var multiLanguageEnabled = TryGetLanguageCode(out contextLanguage);

			if (string.IsNullOrWhiteSpace(queryText) && string.IsNullOrWhiteSpace(filterText))
			{
				return new JObjectResult(new JObject
				{
					{ "itemCount", 0 },
					{ "pageNumber", pageNumber },
					{ "pageSize", pageSize },
					{ "pageCount", 0 },
					{ "items", new JArray() }
				});
			}

			var provider = SearchManager.Provider;

			if (facetConstraints != null)
			{
				facetConstraints =
					facetConstraints.Select(
						x =>
						new FacetConstraints
						{
							FacetName = x.FacetName,
							Constraints = x.Constraints.SelectMany(c => c.Split(','))
						}).ToArray();
			}

			string searchTerm = parameters.ContainsKey("Query") ? parameters["Query"] : string.Empty; // This is needed for Notes/Attachement Search
			// If they specify facet constraints, we'll do a faceted search 
			// TODO this doesn't work, facetConstraints is never null
			var enreplacedyQuery = new CrmEnreplacedyQuery(queryText, pageNumber, pageSize, getLogicalNamesAsEnumerable(logicalNames), contextLanguage.ContextLanguage, multiLanguageEnabled, filterText, facetConstraints, sortingOption, searchTerm);

			var searcher = this.GetSearcher(provider);

			using (searcher)
			{
				var results = searcher.Search(enreplacedyQuery);
				var itemCount = results.ApproximateTotalHits;
				var pageCount = itemCount > 0 ? (int)Math.Ceiling(itemCount / (double)results.PageSize) : 0;

				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Search term:{0}, length: {1}, results contain {2} items", searchTerm, searchTerm.Length, itemCount));

				var jsonResult = new JObject {
					{ "itemCount", itemCount },
					{ "pageNumber", results.PageNumber },
					{ "pageSize", results.PageSize },
					{ "pageCount", pageCount },
					{ "items", new JArray(results.Select(GetSearchResultJson)) }
				};

				if (results.FacetViews != null)
				{
					jsonResult.Add("facetViews", GetFacetViewsJson(results.FacetViews, logicalNames, initialConstraintsToLocalize));

					if (results.SortingOptions != null)
					{
						//todo: add calculation for sort options: searchOrder
						jsonResult.Add("sortingOptions", GetSortingOptionsJson(results.SortingOptions));
					}
				}
				return new JObjectResult(jsonResult);
			}
		}

19 View Source File : CelesteNetRenderHelperComponent.cs
License : MIT License
Project Creator : 0x0ade

public void Rect(float x, float y, float width, float height, Color color) {
            int xi = (int) Math.Floor(x);
            int yi = (int) Math.Floor(y);
            int wi = (int) Math.Ceiling(x + width) - xi;
            int hi = (int) Math.Ceiling(y + height) - yi;

            Rectangle rect = new(xi, yi, wi, hi);

            MDraw.SpriteBatch.Draw(
                BlurRT,
                rect, rect,
                Color.White * Math.Min(1f, color.A / 255f * 2f)
            );

            MDraw.Rect(xi, yi, wi, hi, color);
        }

19 View Source File : IconHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

internal static int AlignToBytes(double original, int nBytesCount)
      {
         var nBitsCount = 8 << (nBytesCount - 1);
         return ((int)Math.Ceiling(original) + (nBitsCount - 1)) / nBitsCount * nBitsCount;
      }

19 View Source File : SpellProperties.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public int GetNumTicks(float heartbeat = 5.0f)
        {
            if (DotDuration == 0)
                return 0;

            // see explanation of Duration, and why it sets Duration to DotDuration + 5

            // For spell like Surge of Regeneration, which is listed as 19 seconds,
            // this would be the equivalent of 20 seconds, ie. Ceil((19 + 5) / 5) = 5 ticks

            return (int)Math.Ceiling(Duration / heartbeat);
        }

19 View Source File : SolarWeek.cs
License : MIT License
Project Creator : 6tail

public int getIndex()
        {
            DateTime firstDay = ExactDate.fromYmd(year, month, 1);
            int firstDayWeek = Convert.ToInt32(firstDay.DayOfWeek.ToString("d"));
            if (firstDayWeek == 0)
            {
                firstDayWeek = 7;
            }
            return (int)Math.Ceiling((day + firstDayWeek - start) * 1D / SolarUtil.WEEK.Length);
        }

19 View Source File : ChatCMDHelp.cs
License : MIT License
Project Creator : 0x0ade

public string GetCommandPage(ChatCMDEnv env, int page = 0) {
            const int pageSize = 8;

            string prefix = Chat.Settings.CommandPrefix;
            StringBuilder builder = new();

            int pages = (int) Math.Ceiling(Chat.Commands.All.Count / (float) pageSize);
            if (page < 0 || pages <= page)
                throw new Exception("Page out of range.");

            for (int i = page * pageSize; i < (page + 1) * pageSize && i < Chat.Commands.All.Count; i++) {
                ChatCMD cmd = Chat.Commands.All[i];
                builder
                    .Append(prefix)
                    .Append(cmd.ID)
                    .Append(" ")
                    .Append(cmd.Args)
                    .AppendLine();
            }

            builder
                .Append("Page ")
                .Append(page + 1)
                .Append("/")
                .Append(pages);

            return builder.ToString().Trim();
        }

19 View Source File : ChatCMDChannel.cs
License : MIT License
Project Creator : 0x0ade

public override void ParseAndRun(ChatCMDEnv env) {
            CelesteNetPlayerSession? session = env.Session;
            if (session == null)
                return;

            Channels channels = env.Server.Channels;

            Channel? c;

            if (int.TryParse(env.Text, out int page) ||
                string.IsNullOrWhiteSpace(env.Text)) {

                if (channels.All.Count == 0) {
                    env.Send($"No channels. See {Chat.Settings.CommandPrefix}{ID} on how to create one.");
                    return;
                }

                const int pageSize = 8;

                StringBuilder builder = new();

                page--;
                int pages = (int) Math.Ceiling(channels.All.Count / (float) pageSize);
                if (page < 0 || pages <= page)
                    throw new Exception("Page out of range.");

                if (page == 0)
                    builder
                        .Append("You're in ")
                        .Append(session.Channel.Name)
                        .AppendLine();

                for (int i = page * pageSize; i < (page + 1) * pageSize && i < channels.All.Count; i++) {
                    c = channels.All[i];
                    builder
                        .Append(c.PublicName)
                        .Append(" - ")
                        .Append(c.Players.Count)
                        .Append(" players")
                        .AppendLine();
                }

                builder
                    .Append("Page ")
                    .Append(page + 1)
                    .Append("/")
                    .Append(pages);

                env.Send(builder.ToString().Trim());

                return;
            }

            Tuple<Channel, Channel> tuple = channels.Move(session, env.Text);
            if (tuple.Item1 == tuple.Item2) {
                env.Send($"Already in {tuple.Item2.Name}");
            } else {
                env.Send($"Moved to {tuple.Item2.Name}");
            }
        }

19 View Source File : Line.cs
License : MIT License
Project Creator : 3RD-Dimension

public override IEnumerable<Motion> Split(double length)
		{
			if (Rapid || PositionValid.Any(isValid => !isValid))  //don't split up rapid or not fully defined motions
			{
				yield return this;
				yield break;
			}

			int divisions = (int)Math.Ceiling(Length / length);

			if (divisions < 1)
				divisions = 1;

			Vector3 lastEnd = Start;

			for (int i = 1; i <= divisions; i++)
			{
				Vector3 end = Interpolate(((double)i) / divisions);

				Line immediate = new Line();
				immediate.Start = lastEnd;
				immediate.End = end;
				immediate.Feed = Feed;
				immediate.PositionValid = new bool[] { true, true, true };

				yield return immediate;

				lastEnd = end;
			}
		}

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

private ItemLayoutInfo GetLayoutInfo(Size availableSize, double itemHeight, ExtentInfo extentInfo)
        {
            if (_itemsControl == null)
            {
                return new ItemLayoutInfo();
            }

            // we need to ensure that there is one realized item prior to the first visible item, and one after the last visible item,
            // so that keyboard navigation works properly. For example, when focus is on the first visible item, and the user
            // navigates up, the ListBox selects the previous item, and the scrolls that into view - and this triggers the loading of the rest of the items 
            // in that row

            var firstVisibleLine = (int)Math.Floor(VerticalOffset / itemHeight);

            var firstRealizedIndex = Math.Max(extentInfo.ItemsPerLine * firstVisibleLine - 1, 0);
            var firstRealizedItemLeft = firstRealizedIndex % extentInfo.ItemsPerLine * ItemWidth - HorizontalOffset;
            // ReSharper disable once PossibleLossOfFraction
            var firstRealizedItemTop = firstRealizedIndex / extentInfo.ItemsPerLine * itemHeight - VerticalOffset;

            var firstCompleteLineTop = (firstVisibleLine == 0 ? firstRealizedItemTop : firstRealizedItemTop + ItemHeight);
            var completeRealizedLines = (int)Math.Ceiling((availableSize.Height - firstCompleteLineTop) / itemHeight);

            var lastRealizedIndex = Math.Min(firstRealizedIndex + completeRealizedLines * extentInfo.ItemsPerLine + 2, _itemsControl.Items.Count - 1);

            return new ItemLayoutInfo
            {
                FirstRealizedItemIndex = firstRealizedIndex,
                FirstRealizedItemLeft = firstRealizedItemLeft,
                FirstRealizedLineTop = firstRealizedItemTop,
                LastRealizedItemIndex = lastRealizedIndex,
            };
        }

19 View Source File : Transition.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void CalcNumSteps(ref Vector3 offset, ref Vector3 offsetPerStep, ref int numSteps)
        {
            if (SpherePath.BeginPos == null)
            {
                offset = Vector3.Zero;
                offsetPerStep = Vector3.Zero;
                numSteps = 1;
                return;
            }
            offset = SpherePath.BeginPos.GetOffset(SpherePath.EndPos);
            var dist = offset.Length();
            var step = dist / SpherePath.LocalSphere[0].Radius;

            if (!ObjectInfo.State.HasFlag(ObjectInfoState.IsViewer))
            {
                if (step > 1.0f)
                {
                    numSteps = (int)Math.Ceiling(step);
                    offsetPerStep = offset * (1.0f / numSteps);
                }
                else if (!offset.Equals(Vector3.Zero))
                {
                    offsetPerStep = offset;
                    numSteps = 1;
                }
                else
                {
                    offsetPerStep = Vector3.Zero;
                    numSteps = 0;
                }
                return;
            }

            if (dist <= PhysicsGlobals.EPSILON)
            {
                offsetPerStep = Vector3.Zero;
                numSteps = 0;
            }
            else
            {
                offsetPerStep = offset * (1.0f / step);
                numSteps = (int)Math.Floor(step) + 1;
            }
        }

See More Examples