public void ConfigureChannelDutyCycle(uint channel, double dutyCycle)
        {
            if (dutyCycle >= 1.0)
            {
                SetFullOn(channel);
                return;
            }
            if (dutyCycle <= 0.0)
            {
                SetFullOff(channel);
                return;
            }
            uint onCount  = 0;
            var  offCount = (uint)Math.Floor(PwmCounterCycle * dutyCycle);

            if (offCount <= onCount)
            {
                offCount = onCount + 1; // The two counts may not be the same value
            }
            var registerOffset = (byte)(Pca9685.Channel0OnLow + (4 * channel));

            WriteConsecutiveRegisters(
                registerOffset,
                (byte)onCount,
                (byte)(onCount >> 8),
                (byte)offCount,
                (byte)(offCount >> 8));
        }
        private static void AlignToGrid(ref Vector2 point)
        {
            Vector2 floorPoint  = new Vector2((float)MathF.Floor(point.X), (float)MathF.Floor(point.Y));
            Vector2 decimalPart = point - floorPoint;

            if (decimalPart.X < 0.5)
            {
                decimalPart.X = 0;
            }
            else
            {
                decimalPart.X = 1;
            }

            if (decimalPart.Y < 0.5)
            {
                decimalPart.Y = 0;
            }
            else
            {
                decimalPart.Y = 1f;
            }

            point = floorPoint + decimalPart;
        }
Example #3
0
 public IEnumerable <double> GetVisibleXPoints()
 {
     for (var x = M.Ceiling(MinimalVisibleX); x <= M.Floor(MaximalVisibleX); x++)
     {
         yield return(x);
     }
 }
    //Reduction
    public static string Reduction_0(double costs)
    {
        string ret = "Over";

        if (notation == 0)
        {
            if (costs < 1000)
            {
                ret = costs.ToString("N0");
            }
            else
            {
                if (costs < 999999)
                {
                    ret = Math.Floor(costs).ToString();
                }
                else
                {
                    //ret = costs.ToString("g3"); 1.000e6 = 1 000 000
                    double prov   = 1000000;
                    int    prov_n = 0;
                    for (int i = 0; costs > prov; i++)
                    {
                        prov  *= 10;
                        prov_n = i;
                    }

                    ret = (Math.Floor(costs / (prov / 10000d)) / 1000d) + "e" + (prov_n + 6);
                }
            }
        }


        return(ret);
    }
Example #5
0
        public double GetSmoothedNoise(Vec3 p_point)
        {
            var u = p_point.X - Math.Floor(p_point.X);
            var v = p_point.Y - Math.Floor(p_point.Y);
            var w = p_point.Z - Math.Floor(p_point.Z);

            var i = (int)Math.Floor(p_point.X);
            var j = (int)Math.Floor(p_point.Y);
            var k = (int)Math.Floor(p_point.Z);

            var c = new Vec3[2, 2, 2];

            for (var di = 0; di < 2; ++di)
            {
                for (var dj = 0; dj < 2; ++dj)
                {
                    for (var dk = 0; dk < 2; ++dk)
                    {
                        c[di, dj, dk] =
                            RandomVector
                            [PermutateX[(i + di) & 255] ^ PermutateY[(j + dj) & 255] ^ PermutateZ[(k + dk) & 255]];
                    }
                }
            }

            return(PerlinInterpolate(c, u, v, w));
        }
Example #6
0
 public IEnumerable <double> GetVisibleYPoints()
 {
     for (var y = M.Ceiling(MinimalVisibleY); y <= M.Floor(MaximalVisibleY); y++)
     {
         yield return(y);
     }
 }
Example #7
0
        public static float LinearInterpolate(Vector2 position, MapData[,] map, ScalarFieldType fieldType)
        {
            float x  = position.X;
            float y  = position.Y;
            float x1 = (int)MathFunctions.Clamp((float)Math.Ceiling(x), 0, map.GetLength(0) - 2);
            float y1 = (int)MathFunctions.Clamp((float)Math.Ceiling(y), 0, map.GetLength(1) - 2);
            float x2 = (int)MathFunctions.Clamp((float)Math.Floor(x), 0, map.GetLength(0) - 2);
            float y2 = (int)MathFunctions.Clamp((float)Math.Floor(y), 0, map.GetLength(1) - 2);

            if (Math.Abs(x1 - x2) < 0.5f)
            {
                x1 = x1 + 1;
            }

            if (Math.Abs(y1 - y2) < 0.5f)
            {
                y1 = y1 + 1;
            }


            float q11 = map[(int)x1, (int)y1].GetValue(fieldType);
            float q12 = map[(int)x1, (int)y2].GetValue(fieldType);
            float q21 = map[(int)x2, (int)y1].GetValue(fieldType);
            float q22 = map[(int)x2, (int)y2].GetValue(fieldType);

            return(MathFunctions.LinearCombination(x, y, x1, y1, x2, y2, q11, q12, q21, q22));
        }
Example #8
0
        public Point GetClosestPointOnTile(Point position, out bool success)
        {
            lock (_threadLocker)
            {
                float[] extents = new Point(20.0f, 2000.0f, 20.0f).ToFloatArray();
                float[] center  = position.ToRecast().ToFloatArray();

                float tx, ty;
                GetTileByLocation(position, out tx, out ty);
                int x = (int)Math.Floor(tx);
                int y = (int)Math.Floor(ty);
                LoadTile(x, y);

                dtPolyRef startRef = _query.FindNearestPolygon(center, extents, Filter);
                if (startRef == 0)
                {
                    success = false;
                    return(new Point());
                }
                float[]      result;
                DetourStatus status = _query.closestPointOnPolyBoundary(startRef, center, out result);
                if (status.HasFailed())
                {
                    success = false;
                    return(new Point());
                }
                success = true;
                return(new Point(result.ToWoW()));
            }
        }
            public void CachesTheApiResultsInMemorySoTheApiIsNotCalledTwiceForTheSameProjects(
                NonEmptyArray <NonNegativeInt> projectIds)
            {
                var actualProjectIds = projectIds.Get.Select(i => (long)i.Get).Distinct().ToArray();
                var idCount          = actualProjectIds.Length;

                if (idCount < 2)
                {
                    return;
                }
                var dbProjectCount  = (int)Math.Floor((float)idCount / 2);
                var apiProjectCount = idCount - dbProjectCount;
                var projectsInDb    = actualProjectIds.Take(dbProjectCount).ToArray();
                var projectsInApi   = actualProjectIds.TakeLast(apiProjectCount).ToArray();
                var summaries       = getSummaryList(actualProjectIds);

                apiProjectsSummary.ProjectsSummaries.Returns(summaries);
                configureRepositoryToReturn(projectsInDb, projectsInApi);
                configureApiToReturn(projectsInApi);

                GetInteractor(workspaceId, DateTimeOffset.Now.AddDays(-7), DateTimeOffset.Now).Execute().Wait();
                GetInteractor(workspaceId, DateTimeOffset.Now.AddDays(-7), DateTimeOffset.Now).Execute().Wait();

                ProjectsApi.Received(1)
                .Search(workspaceId, Arg.Is <long[]>(
                            calledIds => ensureExpectedIdsAreReturned(calledIds, projectsInApi)));
            }
Example #10
0
        public float GetZ(Point position, bool strict = false)
        {
            lock (_threadLocker)
            {
                float[] extents = strict ? new Point(0.5f, 2000.0f, 0.5f).ToFloatArray() : new Point(1.5f, 2000.0f, 1.5f).ToFloatArray();
                float[] center  = position.ToRecast().ToFloatArray();

                float tx, ty;
                GetTileByLocation(position, out tx, out ty);
                int x = (int)Math.Floor(tx);
                int y = (int)Math.Floor(ty);
                LoadTile(x, y);

                dtPolyRef startRef = _query.FindNearestPolygon(center, extents, Filter);
                if (startRef == 0)
                {
                    Logging.WriteDebug("There is no polygon in this location (Tile " + x + "," + y + "), coord: X:" +
                                       position.X + ", Y:" + position.Y);
                    return(0);
                }
                float z = _query.GetPolyHeight(startRef, center);
                if (z == 0 && !strict) // it failed but we are not strict, then search around
                {
                    float[]      result;
                    DetourStatus status = _query.closestPointOnPolyBoundary(startRef, center, out result);
                    z = status.HasFailed() ? 0 : result[1];
                }
                return(z);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageBrushApplicator"/> class.
 /// </summary>
 /// <param name="target">The target image.</param>
 /// <param name="image">The image.</param>
 /// <param name="region">The region.</param>
 /// <param name="options">The options</param>
 public ImageBrushApplicator(ImageFrame <TPixel> target, ImageFrame <TPixel> image, RectangleF region, GraphicsOptions options)
     : base(target, options)
 {
     this.source  = image;
     this.xLength = image.Width;
     this.yLength = image.Height;
     this.offsetY = (int)MathF.Max(MathF.Floor(region.Top), 0);
     this.offsetX = (int)MathF.Max(MathF.Floor(region.Left), 0);
 }
Example #12
0
        /// <summary>
        /// Reduces a given angle to a value between π and -π.
        /// </summary>
        /// <param name="radians"></param>
        /// <returns></returns>
        public static double WrapAngle(double radians)
        {
            int    revolutions  = (int)NMath.Floor(radians / Numbers.TwoPi);
            double wrappedAngle = radians - revolutions * Numbers.TwoPi;

            if (NMath.Abs(wrappedAngle) > Numbers.Pi)
            {
                return(-NMath.Sign(wrappedAngle) * (Numbers.TwoPi - NMath.Abs(wrappedAngle)));
            }
            return(wrappedAngle);
        }
Example #13
0
        /// <summary>
        /// Tworzy tekst statyczny ale string zostanie automatycznie podzielony na nowe linie tak aby pasowal do okienka w ktorym ma byc wyswietlony
        /// </summary>
        /// <param name="D"></param>
        /// <param name="T"></param>
        /// <returns></returns>
        public OverlayContainer createStaticTextAutoSplit(Vector4 D, String T)
        {
            uint    h           = this.mGUI.mFontSize; // margin and font size
            Font    font        = (Font)(Mogre.FontManager.Singleton.GetByName(this.mGUI.mFont).Target);
            Vector2 averageSize = ViewHelper.GetTextAverageSize(T, font, h);


            int    charsPerLine = (int)Math.Floor((D.z - 2 * h) / averageSize.x);
            string multiline    = LanguageResources.SplitInsertingNewLinesByLength(T, charsPerLine);

            return(createStaticText(D, multiline, ColourValue.White));
        }
Example #14
0
        public double GetNoise(Vec3 p_point)
        {
            var u = p_point.X - Math.Floor(p_point.X);
            var v = p_point.Y - Math.Floor(p_point.Y);
            var w = p_point.Z - Math.Floor(p_point.Z);

            var i = (int)(4 * p_point.X) & 255;
            var j = (int)(4 * p_point.Y) & 255;
            var k = (int)(4 * p_point.Z) & 255;

            return(RandomDouble[PermutateX[i] ^ PermutateY[j] ^ PermutateZ[k]]);
        }
            public void Estimate1D(decimal min, decimal max, decimal step)
            {
                var param = new OptimizationStepParameter("ema-fast", min, max, step);
                var set   = new HashSet <OptimizationParameter>()
                {
                    param
                };

                _strategy.Initialize(new Target("Profit", new Maximization(), null), new List <Constraint>(), set, new StepBaseOptimizationStrategySettings());

                Assert.AreEqual(Math.Floor(Math.Abs(max - min) / Math.Abs(step)) + 1, _strategy.GetTotalBacktestEstimate());
            }
        public static void OnNPCRecruited(NPCBase npc)
        {
            if (npc.GetTempValues().TryGet(ISSETTLER, out bool settler) && settler)
            {
                return;
            }

            var ps = PlayerState.GetPlayerState(npc.Colony.Owner);

            if (ps.SettlersEnabled)
            {
                if (Configuration.GetorDefault("ColonistsRecruitment", true))
                {
                    if (ps.SettlersEnabled && npc.Colony.FollowerCount > MAX_BUYABLE)
                    {
                        var cost = Configuration.GetorDefault("CompoundingFoodRecruitmentCost", 5) * ps.ColonistsBought;
                        var num  = 0f;

                        if (cost < 1)
                        {
                            cost = 1;
                        }

                        if (npc.Colony.UsedStockpile.TotalFood < cost ||
                            !npc.Colony.UsedStockpile.TryRemoveFood(ref num, cost))
                        {
                            Chat.Send(npc.Colony.Owner,
                                      $"<color=red>Could not recruit a new colonist; not enough food in stockpile. {cost + ServerManager.ServerVariables.LaborerCost} food required.</color>",
                                      ChatSenderType.Server);

                            npc.Colony.UsedStockpile.Add(BuiltinBlocks.Bread,
                                                         (int)Math.Floor(ServerManager.ServerVariables.LaborerCost /
                                                                         3));

                            npc.health = 0;
                            npc.Update();
                            return;
                        }

                        ps.ColonistsBought++;
                        ps.NextColonistBuyTime = TimeCycle.TotalTime + 24;
                    }

                    SettlerInventory.GetSettlerInventory(npc);
                    UpdateFoodUse(npc.Colony.Owner);
                }
                else
                {
                    PandaChat.Send(npc.Colony.Owner,
                                   "The server administrator has disabled recruitment of colonists while settlers are enabled.");
                }
            }
        }
Example #17
0
        public static int IntLength(int i)
        {
            if (i < 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            if (i == 0)
            {
                return(1);
            }

            return((int)MathL.Floor(MathL.Log10(i)) + 1);
        }
Example #18
0
    //damage on enemy
    public void damage_enemy()
    {
        double profit = game_manager.army_dmg[nomber];

        game_manager.enemy_hp -= profit;
        if (profit > game_manager.enemy_mhp)
        {
            profit = game_manager.enemy_mhp;
        }

        profit = 1d / game_manager.enemy_mhp * profit;


        game_manager.player_coin += Math.Floor(game_manager.enemy_coin * profit);
    }
Example #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static float Wrap(float value, float min, float max)
        {
            if (NearEqual(min, max))
            {
                return(min);
            }

            double mind   = min;
            double maxd   = max;
            double valued = value;

            double range_size = maxd - mind;

            return((float)(mind + (valued - mind) - (range_size * SysMath.Floor((valued - mind) / range_size))));
        }
        // --------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Returns a random string of the given length that only contains numbers.
        /// </summary>
        public static string GetNumberString(int size)
        {
            StringBuilder builder = new StringBuilder();

            lock (RndLock)
            {
                char ch;
                for (int i = 0; i < size; i++)
                {
                    ch = Convert.ToChar(Convert.ToInt32(SysMath.Floor(10 * RNG.NextDouble() + 48)));
                    builder.Append(ch);
                }
            }
            return(builder.ToString());
        }
Example #21
0
        /// <summary>
        /// Reduces a given angle to a value between 0 and 2π radians, matching the sign of the angle.
        /// </summary>
        /// <param name="radians">The angle in radians.</param>
        /// <param name="tolerance">The tolerance.</param>
        /// <returns>System.Double.</returns>
        public static double WrapAngleWithinTwoPi(double radians, double tolerance = Numbers.ZeroTolerance)
        {
            if (radians.IsZeroSign(tolerance))
            {
                radians = 0;
            }
            if (radians == double.PositiveInfinity || radians == double.NegativeInfinity)
            {
                return(double.PositiveInfinity);
            }
            int    inferredRounding = NMath.Max(Numbers.DecimalPlaces(radians), 6);
            double roundedPi        = NMath.Round(Numbers.TwoPi, inferredRounding);
            int    revolutions      = (int)NMath.Round(NMath.Floor(radians / roundedPi), inferredRounding);

            return(radians - revolutions * roundedPi);
        }
Example #22
0
 public void AddSeconds(double sec)
 {
     week.Seconds += sec;
     if (sec < 0)
     {
         int weekNum = (int)Math.Ceiling(sec / Time.SecondsPerWeek);
         week.Weeks   -= weekNum;
         Week.Seconds += weekNum * Time.SecondsPerWeek;
         Week          = Week;
     }
     else
     {
         int weekNum = (int)Math.Floor(sec / Time.SecondsPerWeek);
         week.Weeks   += weekNum;
         Week.Seconds -= weekNum * Time.SecondsPerWeek;
         Week          = Week;
     }
 }
Example #23
0
 public static Point3d Evaluate3D(IList <Point3d> points, bool cerrada, double t)
 {
     if (cerrada)
     {
         t = t % points.Count;
         int    i     = (int)Math.Floor(t);
         int    inext = (i + 1) % points.Count;
         double alfa  = t - i;
         return(points[i].Lerp(points[inext], alfa));
     }
     else
     {
         int    i     = (int)Math.Floor(t);
         int    inext = i + 1;
         double alfa  = t - i;
         return(points[i].Lerp(points[inext], alfa));
     }
 }
Example #24
0
        public static int GetDecimalPlaces(double value)
        {
            // increasing max decimal places above 10 produces weirdness
            int    maxDecimalPlaces = 10;
            double threshold        = MathL.Pow(0.1d, maxDecimalPlaces);

            if (value == 0.0)
            {
                return(0);
            }
            int decimalPlaces = 0;

            while (value - MathL.Floor(value) > threshold && decimalPlaces < maxDecimalPlaces)
            {
                value *= 10.0;
                decimalPlaces++;
            }
            return(decimalPlaces);
        }
            public void Step1D(decimal min, decimal max, decimal step)
            {
                var param = new OptimizationStepParameter("ema-fast", min, max, step);
                var set   = new HashSet <OptimizationParameter>()
                {
                    param
                };

                _strategy.Initialize(new Target("Profit", new Maximization(), null), new List <Constraint>(), set, new StepBaseOptimizationStrategySettings());
                var counter = 0;

                using (var enumerator = new EnqueueableEnumerator <ParameterSet>())
                {
                    _strategy.NewParameterSet += (s, parameterSet) =>
                    {
                        enumerator.Enqueue(parameterSet);
                    };

                    _strategy.PushNewResults(OptimizationResult.Initial);

                    using (var paramEnumerator = new OptimizationStepParameterEnumerator(param))
                    {
                        while (paramEnumerator.MoveNext())
                        {
                            var value = paramEnumerator.Current;
                            counter++;
                            Assert.IsTrue(enumerator.MoveNext());

                            var suggestion = enumerator.Current;

                            Assert.IsNotNull(suggestion);
                            Assert.IsTrue(suggestion.Value.All(s => set.Any(arg => arg.Name == s.Key)));
                            Assert.AreEqual(1, suggestion.Value.Count);
                            Assert.AreEqual(value, suggestion.Value["ema-fast"]);
                        }
                    }

                    Assert.AreEqual(0, enumerator.Count);
                }

                Assert.Greater(counter, 0);
                Assert.AreEqual(Math.Floor((param.MaxValue - param.MinValue) / param.Step.Value) + 1, counter);
            }
            public void Estimate2D(decimal[,] data)
            {
                var args = new HashSet <OptimizationParameter>()
                {
                    new OptimizationStepParameter("ema-fast", data[0, 0], data[0, 1], data[0, 2]),
                    new OptimizationStepParameter("ema-slow", data[1, 0], data[1, 1], data[1, 2])
                };

                _strategy.Initialize(new Target("Profit", new Maximization(), null), new List <Constraint>(), args, new StepBaseOptimizationStrategySettings());

                var total = 1m;

                foreach (var arg in args.Cast <OptimizationStepParameter>())
                {
                    total *= Math.Floor((arg.MaxValue - arg.MinValue) / arg.Step.Value) + 1;
                }

                Assert.AreEqual(total, _strategy.GetTotalBacktestEstimate());
            }
Example #27
0
        /// <summary>
        /// Rounds to significant figures.
        /// </summary>
        /// <seealso cref="RoundToSignificantFigures">https://en.wikipedia.org/wiki/Significant_figures</seealso>
        /// <param name="value">The value.</param>
        /// <param name="significantFigures">The number of significant figures.</param>
        /// <param name="roundingTieBreaker">Method by which rounding is performed if the triggering rounding number is 5.</param>
        /// <returns>System.Double.</returns>
        public static double RoundToSignificantFigures(
            double value,
            int significantFigures,
            RoundingTieBreaker roundingTieBreaker = RoundingTieBreaker.HalfAwayFromZero)
        {
            if (value == 0 || significantFigures == 0)
            {
                return(0);
            }

            // Get value scaled to having sig figs result as an integer e.g. 4th sig fig 12345 = 1234.5 or 0.00012345 = 1234.5, 7th sig fig 12.345 = 1234500
            double scale      = NMath.Pow(10, NMath.Floor(NMath.Log10(NMath.Abs(value))) + 1 - significantFigures);
            double valueScale = value / scale;

            // Round in case floating point affects number outside of precision (e.g. for 0.545 vs. 0.5449999999 for rounding to 0.6)
            double valueScaleRounded = NMath.Round(valueScale, 2);

            // scale back up
            return(scale * NMath.Round(valueScaleRounded, midpointRounding(roundingTieBreaker)));
        }
Example #28
0
    /// <summary>
    /// Creates the windows of the facade
    /// </summary>
    /// <param name="vertices">The array containing the mesh's vertices, ref type</param>
    /// <returns></returns>
    private List <Face> CreateWindows(ref Vector3[] vertices)
    {
        //Remaining space should be the same on both ends
        int horizontalWindows    = (int)Math.Floor(width / (windowWidth + windowWidthSpacing * 2));
        var relativeLeftStartPos = (width - horizontalWindows * (windowWidth + windowWidthSpacing * 2)) / 2;

        var createdFaces = new List <Face>();

        //Get the height parts of all the lower-left coordinates, goes from the height of the door section to the top
        for (float heightLowerStart = doorSectionHeight; heightLowerStart + windowHeight + windowHeightSpacing < height; heightLowerStart += windowHeight + windowHeightSpacing * 2)
        {
            //Get the width parts of all the lower-left coordinates, goes from left edge + spacing to the other edge
            for (float widthLeftStart = genCoords.x + windowWidthSpacing + relativeLeftStartPos; widthLeftStart + windowWidth < width; widthLeftStart += windowWidth + windowWidthSpacing * 2)
            {
                createdFaces.Add(CreateWindowAt(ref vertices, new Vector3(widthLeftStart, heightLowerStart, genCoords.z)));
            }
        }

        return(createdFaces);
    }
Example #29
0
        public void AddMinesToTheBoard()
        {
            var min       = (int)Math.Ceiling(Width * Height * 0.2);
            var max       = (int)Math.Floor(Width * Height * 0.6);
            var mineCount = random.Next(min, max);

            RemainingMineCount = mineCount;

            while (mineCount > 0)
            {
                var row    = random.Next(0, Width - 1);
                var column = random.Next(0, Height - 1);

                if (Board[row, column].State == State.Mine)
                {
                    continue;
                }

                Board[row, column].State = State.Mine;
                mineCount--;

                for (var i = 0; i < 8; i++)
                {
                    int xDir = Helper.Directions[i, 0];
                    int yDir = Helper.Directions[i, 1];

                    if (Helper.CellIsOutOfTheBoardRange(xDir, yDir, row, column, Width, Height))
                    {
                        continue;
                    }

                    if (Board[row + yDir, column + xDir].State == State.MinesAround ||
                        Board[row + yDir, column + xDir].State == State.Empty)
                    {
                        Board[row + yDir, column + xDir].State = State.MinesAround;
                        Board[row + yDir, column + xDir].MinesAround++;
                    }
                }
            }
        }
Example #30
0
        internal Rectangle GetImageRectangle(float dpi)
        {
            var rect   = Rectangle.ToRectangleF();
            var mul    = dpi / 72f;
            var values = new[] { rect.X *mul, rect.Y *mul, rect.Width *mul, rect.Height *mul };

            // BUG 0015690
            for (int i = 0; i < values.Length; i++)
            {
                var v = SMath.Round(values[i]);
                if (SMath.Abs(v - values[i]) < 0.01f)
                {
                    values[i] = (float)v;
                }
            }

            int x      = (int)SMath.Floor(values[0]);
            int y      = (int)SMath.Floor(values[1]);
            int width  = (int)SMath.Ceiling(values[2]);
            int height = (int)SMath.Ceiling(values[3]);

            return(new Rectangle(x, y, width, height));
        }