Example #1
1
        private static void HandleCollision(Snake snake, ConsoleRenderer renderer)
        {
            List<GameFieldCoords> snakeElements = new List<GameFieldCoords>();

            foreach (GameFieldCoords element in snake.GetPosition())
            {
                snakeElements.Add(element);
            }

            foreach (GameFieldCoords element in snakeElements)
            {
                if (element.Row >= renderer.GameFieldSize.Row || element.Row < 0
                    || element.Col >= renderer.GameFieldSize.Col || element.Col < 0)
                {
                    snake.IsDestroyed = true;
                }
            }

            for (int element = 0; element < snakeElements.Count - 1; element++)
            {
                if (snakeElements.Last().Row == snakeElements[element].Row
                    && snakeElements.Last().Col == snakeElements[element].Col)
                {
                    snake.IsDestroyed = true;
                }
            }
        }
Example #2
0
        private static List<Command> Parse(string[] args)
        {
            var commands = new List<Command>();

            if (args.Length == 0) commands.Add(new Help());

            foreach (var commandStr in args)
            {
                switch (commandStr)
                {
                    case "/?":
                    case "/help":
                    case "-help":
                        commands.Clear();
                        commands.Add(new Help());
                        return commands;
                    case "-k":
                        commands.Add(new KeyValue());
                        break;
                    case "-ping":
                        commands.Add(new Ping());
                        break;
                    case "-print":
                        commands.Add(new Print());
                        break;
                    default:
                        if (commands.Count > 0 && !(commands.Last() is Ping))
                            commands.Last().AddValue(commandStr);
                        else
                            Console.WriteLine("Command <{0}> is not supported, use CommandParser.exe /? to see set of allowed commands", commandStr);
                        break;
                }
            }
            return commands;
        }
Example #3
0
        public IEnumerable<KeyValuePair<string, IStockRealTime>> GetData(IEnumerable<string> stockCodes)
        {
            if (stockCodes == null)
            {
                return new List<KeyValuePair<string, IStockRealTime>>();
            }

            List<List<string>> codePackages = new List<List<string>>();
            foreach(var code in stockCodes)
            {
                if(codePackages.Count < 1 || codePackages.Last().Count > 100)
                {
                    codePackages.Add(new List<string>());
                }

                codePackages.Last().Add(code);
            }

            List<KeyValuePair<string, IStockRealTime>> result = new List<KeyValuePair<string, IStockRealTime>>();
            foreach (var package in codePackages)
            {
                var packageResult = GetDataByPackage(package);
                result.AddRange(packageResult);
            }

            return result;
        }
Example #4
0
        private static List<IPerson> GeneratePopulation(int id, ICivilization civilization, int popCount)
        {
            List<IPerson> population = new List<IPerson>();
            for (int n = 0; n < popCount; n++)
            {
                //Thread.Sleep(_Random.Next(200, 700));
                PersonHelper personHelper = new PersonHelper();
                personHelper.Civilization = civilization;
                personHelper.Race = civilization.Race;
                personHelper.Mythology = civilization.Race.Mythos;

                // maybe we should check the population levels before starting the next loop? First thing in the for loop?
                IPopulationCenters popCenter = civilization.PopulationCenters.First(pc => pc.Population.Count < pc.MaxPopulation);
                personHelper.OriginatesFrom = popCenter; // WHAT HAPPENS WHEN WE RUN OUT OF CITIES!?
                personHelper.Father = new Person();
                personHelper.Mother = new Person();
                personHelper.Partner = new Person();

                PersonGen personGen = new PersonGen();

                IPerson person = personGen.GenerateSingle(personHelper);
                population.Add(person);
                popCenter.Population.Add(person);

                if (n < 9) person.SocialStatus = CoreEnums.Status.Highborne;
                WriteToConsole("ID: " + id + "Name: " + population.Last().Name + "; Race: " + population.Last().Race.Name);
            }
            return population;
        }
Example #5
0
        public static PointCollection FindConvexPolygon(List<Point> points)
        {
            List<Point> top = new List<Point>();
            List<Point> bottom = new List<Point>();

            IEnumerable<Point> finalTop;
            IEnumerable<Point> finalBottom;

            points.Sort((x, y) => { return (int) (x.X - y.X); });

            double deltaX = points.Last().X - points.First().X;
            double deltaY = points.Last().Y - points.First().Y;
            double denominator = (Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));

            for (int i = 1; i < points.Count - 1; i++)
                if (MinimumDistanceBetweenPointAndLine2D(points.First(), points.Last(), points[i], deltaX, deltaY,
                                                         denominator))
                    bottom.Add(points[i]);
                else
                    top.Add(points[i]);

            top.Insert(0, points.First());
            top.Add(points.Last());
            bottom.Insert(0, points.First());
            bottom.Add(points.Last());

            finalTop = ConvexHullCore(top, true);
            finalBottom = ConvexHullCore(bottom, false);

            return new PointCollection(finalTop.Union(finalBottom.Reverse()));
        }
Example #6
0
        void foo()
        {
            var g = new Stack<int>();
            var c = Enumerable.Range(1, 100).ToList();
            for (int i = 101; i > 2; i--)
            {
                g.Push(i);
            }

            var paisr = new List<clc>();
            int h = 0;
            while (g.Count > 1)
            {
                paisr.Add(new clc() { x = c[h], p = new Pair() { x1 = g.Pop(), x2 = g.Pop() } });
                h++;
                if (g.Count == 1)
                {
                    paisr.Add(new clc() { x = c[h], p = new Pair() { x1 = g.Pop() } });
                    break;
                }
            }

            h = paisr.Count;
            while (paisr.Count > 2)
            {
                var p = paisr.Last();
                var top = paisr.FirstOrDefault(x => x.p.Has(p.x));
                if (top != null)
                {
                    top.p.Addto(p.x, p.p);
                    paisr.Remove(paisr.Last());
                }
            }
            return;
        }
        /// <summary>
        /// Creates an enumeration of fits for X and Y coordinates such that each fit improves the previous one. The last fit is the best one.
        /// </summary>
        /// <param name="xs">The X coordinates array</param>
        /// <param name="ys">The corresponding Y coordinates array</param>
        /// <param name="threshold">Error threshold that controls division into intervals</param>
        /// <returns>The enumeration of fits. Each fit is made of the coefficients and the interval breaking indices</returns>
        private static IEnumerable<Fit> EnumerateFits(double[] xs, double[] ys, double threshold)
        {
            Contract.Requires(xs.Length > 0);
            Contract.Requires(xs.Length == ys.Length);
            Contract.Requires(threshold > 0);

            int n = xs.Length;
            var breakIndices = new List<int> { 3 };

            while (breakIndices.Last() < n) // while we haven't reached our optimal division yet
            {
                var breakIndicesArray = breakIndices.ToArray();
                var xIntervals = LSIntervalsFitter.FitIntervals(xs, breakIndicesArray);
                var yIntervals = LSIntervalsFitter.FitIntervals(ys, breakIndicesArray);
                yield return new Fit { xIntervals = xIntervals, yIntervals = yIntervals, breakIndices = breakIndicesArray };

                var xLastIntervalMSE = LastIntervalMSE(xIntervals, xs, breakIndices);
                var yLastIntervalMSE = LastIntervalMSE(yIntervals, ys, breakIndices);

                if (xLastIntervalMSE < threshold && yLastIntervalMSE < threshold) // our current interval is still good enough
                    breakIndices[breakIndices.Count - 1] = breakIndices.Last() + 1;
                else // we need a new interval to approximate well enough
                {
                    var nextIntervalBreak = breakIndices.Last() + 3;
                    if (nextIntervalBreak >= n)
                        breakIndices[breakIndices.Count - 1] = breakIndices.Last() + 1;
                    else
                        breakIndices.Add(nextIntervalBreak);
                }
            }
        }
        /// <summary>
        /// Convert List of Trades to List of Completed Trades
        /// </summary>
        /// <param name="TradesOnly"></param>
        /// <returns></returns>
        public static List<CompletedTrade> CreateList(List<Trade> TradesOnly)
        {
            var CompList = new List<CompletedTrade>();
            var even = TradesOnly.Count % 2;
            int back = even == 2 ? 0 : 1;

            for (int x = 0; x < TradesOnly.Count - back; x += 2)
            {
                CompletedTrade t = new CompletedTrade();
                t.OpenTrade = TradesOnly[x];
                t.CloseTrade = TradesOnly[x + 1];
                CompList.Add(t);
            }

            if (TradesOnly.Last() != CompList.Last().CloseTrade)
            {
                CompletedTrade last = new CompletedTrade();

                last.OpenTrade = TradesOnly.Last();
                last.CloseTrade.TimeStamp = last.OpenTrade.TimeStamp;
                last.CloseTrade.BuyorSell = Trade.BuySell.None;
                last.CloseTrade.Reason = Trade.Trigger.None;
                last.CloseTrade.CurrentDirection = last.OpenTrade.CurrentDirection;
                last.CloseTrade.TradedPrice = last.OpenTrade.TradedPrice;
                CompList.Add(last);
            }



            return CompList;
        }
        private List<Book> GetAllBooks()
        {
            var books = new List<Book>();
            var connectionString = ConfigurationManager.ConnectionStrings["HanHomeworkConnectStr"].ConnectionString;

            using (var connection = new SqlConnection(connectionString))
            {
                const string commandText = "SELECT * FROM book";
                var command = new SqlCommand(commandText, connection);

                connection.Open();
                using (var dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        books.Add(new Book());
                        books.Last().Id = (int)dataReader["Id"];
                        books.Last().BookName = (string)dataReader["bookName"];
                        books.Last().PageCount = (string)dataReader["pageCount"];
                    }
                }
            }

            return books;
        }
Example #10
0
 public List<Tuple<string, string>> OrderSecurityTokens(AccessCodeSet accessCodeSet, List<Tuple<string, string>> sortedList, string newStartColor)
 {
     var startColor = accessCodeSet.StartColor;
     if (!string.IsNullOrEmpty(newStartColor))
         startColor = newStartColor;
     if (accessCodeSet.TokenList.Count(x => x.Item1.Equals(startColor)) == 1)
     {
         sortedList.Add(accessCodeSet.TokenList.Single(x => x.Item1.Equals(startColor)));
         accessCodeSet.TokenList = accessCodeSet.TokenList.ToList().Except(new List<Tuple<string, string>> { sortedList.Last() }).ToList();
     }
     else
     {
         var listOfTokensWithSameStartColor = accessCodeSet.TokenList.Where(x => x.Item1.Equals(startColor));
         if (!listOfTokensWithSameStartColor.Any())
             return sortedList;
         foreach (var token in listOfTokensWithSameStartColor)
         {
             if (accessCodeSet.TokenList.Count(x => x.Item1.Equals(token.Item2)) == 1)
             {
                 sortedList.Add(token);
                 accessCodeSet.TokenList = accessCodeSet.TokenList.ToList().Except(new List<Tuple<string, string>> { token }).ToList();
                 sortedList.Add(accessCodeSet.TokenList.Single(x => x.Item1.Equals(token.Item2)));
                 accessCodeSet.TokenList = accessCodeSet.TokenList.ToList().Except(new List<Tuple<string, string>> { sortedList.Last() }).ToList();
             }
         }
     }
     if (accessCodeSet.TokenList.Any())
         OrderSecurityTokens(accessCodeSet, sortedList, sortedList.Last().Item2);
     return sortedList;
 }
Example #11
0
        public void Should_Track_Bounds()
        {
            var target = new BoundsTracker();
            var control = default(Rectangle);
            var tree = new Decorator
            {
                Padding = new Thickness(10),
                Content = new Decorator
                {
                    Padding = new Thickness(5),
                    Content = (control = new Rectangle
                    {
                        Width = 15,
                        Height = 15,
                    }),
                }
            };

            tree.Measure(Size.Infinity);
            tree.Arrange(new Rect(0, 0, 100, 100));

            var track = target.Track(control, tree);
            var results = new List<TransformedBounds>();
            track.Subscribe(results.Add);

            Assert.Equal(new Rect(15, 15, 15, 15), results.Last().Bounds);

            tree.Padding = new Thickness(15);
            tree.Measure(Size.Infinity);
            tree.Arrange(new Rect(0, 0, 100, 100), true);

            Assert.Equal(new Rect(20, 20, 15, 15), results.Last().Bounds);
        }
Example #12
0
 public void nettoyerTrajectoire()
 {
     int dirX = 0, dirY = 0, oldDirX = 0, oldDirY = 0; // Directions sur les axes X et Y
     List<PositionElement> Sortie = new List<PositionElement>();
     foreach (PositionElement p in _Positions)
     {
         if (Sortie.Count == 0 )
             Sortie.Add(p);
         else
         {
             dirX = Math.Sign(p.X - Sortie.Last().X);
             dirY = Math.Sign(p.Y - Sortie.Last().Y);
             if (dirX != oldDirX || dirY != oldDirY)
             {
                 oldDirX = dirX;
                 oldDirY = dirY;
                 Sortie.Add(p);
             }
             else
             {
                 PositionElement p2 = Sortie[Sortie.Count-1];
                 p2.X = p.X;
                 p2.Y = p.Y;
                 Sortie[Sortie.Count - 1] = p2;
             }
         }
     }
     _Positions = Sortie;
 }
 /// <summary>
 /// Maak een mooie samenvatting van de opgegeven nummers
 /// </summary>
 /// Probeer de nummers samen te vatten door een bereik te tonen.
 /// Waar niet mogelijk toon daar gewoon komma gescheiden nummers.
 /// Als het in beeld is dan wordt de eerste in ieder geval los getoond.
 /// <remarks>
 /// </remarks>
 private static string LiedVerzen(ILiturgieDisplay regelDisplay, bool toonEersteLos, IEnumerable<ILiturgieContent> vanDelen = null)
 {
     if (regelDisplay.VersenGebruikDefault.Gebruik || vanDelen == null || (!toonEersteLos && regelDisplay.VolledigeContent))
         return !string.IsNullOrEmpty(regelDisplay.VersenGebruikDefault.Tekst) ? regelDisplay.VersenGebruikDefault.Tekst : null;
     var over = vanDelen.Where(v => v.Nummer.HasValue).Select(v => v.Nummer.Value).ToList();
     if (!over.Any())
         return null;
     var builder = new StringBuilder();
     if (toonEersteLos)
     {
         builder.Append(over.First()).Append(", ");
         over.RemoveAt(0);
     }
     while (over.Any())
     {
         var nieuweReeks = new List<int> { over.First() };
         over.RemoveAt(0);
         while (over.Any() && over[0] == nieuweReeks.Last() + 1)
         {
             nieuweReeks.Add(over[0]);
             over.RemoveAt(0);
         }
         if (nieuweReeks.Count == 1)
             builder.Append(nieuweReeks[0]);
         else if (nieuweReeks.Count == 2)
             builder.Append(string.Join(", ", nieuweReeks));
         else
             builder.AppendFormat("{0} - {1}", nieuweReeks.First(), nieuweReeks.Last());
         builder.Append(", ");
     }
     return builder.ToString().TrimEnd(',', ' ');
 }
        public List<GroupedFilesViewModel> Evaluate(int numberOfGroups, string[] directories)
        {
            var groups = new List<GroupedFilesViewModel>();
            var foldersPerGroup = FoldersPerGroupEvaluator.Evaluate(directories.Count(), numberOfGroups);

            var i = 0;
            for (var g = 0; g < numberOfGroups; g++)
            {
                var group = new GroupedFilesViewModel { Files = new List<string>() };
                group.StartDir = directories[i];

                for (var f = 0; f < foldersPerGroup; f++)
                {
                    if (i < directories.Count())
                    {
                        group.Files.AddRange(DirectoryDescendentFilesEvaluator.Evaluate(directories[i]).ToList());
                        i++;
                    }
                }

                group.EndDir = directories[i - 1];
                groups.Add(group);
            }

            if (directories.Count() > i)
            {
                for (var r = i; r < directories.Count(); r++)
                {
                    groups.Last().Files.Add(directories[r]);
                    groups.Last().EndDir = directories[r];
                }
            }

            return groups;
        }
Example #15
0
        /// <summary>
        /// Calculates Exponential Moving Average (EMA) indicator
        /// </summary>
        /// <param name="input">Input signal</param>
        /// <param name="period">Number of periods</param>
        /// <param name="uisngavg">Start with Average or start with first element</param>
        /// <returns>Object containing operation results</returns>
        public static EMAResult EMA(IEnumerable<double> input, int period, bool usingavg=true)
        {
            var returnValues = new List<double>();

            double multiplier = (2.0 / (period + 1));

            int start = usingavg ? period : 1;

            if ( input.Count() >= start)
            {
                double initialEMA = usingavg ? input.Take(period).Average() : input.First();

                returnValues.Add(initialEMA);

                var copyInputValues = input.ToList();

                for (int i = start; i < copyInputValues.Count; i++)
                {
                    var resultValue = (copyInputValues[i] - returnValues.Last()) * multiplier + returnValues.Last();

                    returnValues.Add(resultValue);
                }
            }

            var result = new EMAResult()
            {
                Values = returnValues,
                StartIndexOffset = start - 1
            };

            return result;
        }
 public int ModifLikeProduit(List<string> aData)
 {
     DataSet DsJson = new DataSet();
     MyCo NewCo = new MyCo();
     NewCo.UpdateLikeProduit(aData.IndexOf(aData.Last()).ToString(),aData.Last(),ref DsJson);
     return aData.IndexOf(aData.Last());
 }
        private static void ValidateReordering(List<INode> chain1, List<INode> chain2, int closestParentIndex, IDiagInfo diagInfo)
        {
            var invalidNode1 = GetInvalidNode(chain1, closestParentIndex);
            var invalidNode2 = GetInvalidNode(chain2, closestParentIndex);
            if (invalidNode1 == null && invalidNode2 == null)
            {
                return;
            }

            var fixNode1 = invalidNode1 ?? chain1.Last();
            var fixNode2 = invalidNode2 ?? chain2.Last();

            var exceptionMessage = $"There is an uncertainty between {chain1.Last()} (a) and {chain2.Last()} (b)" + Environment.NewLine +
                $"{GetInvalidateString("a", chain1.Last(), invalidNode1)}{GetInvalidateString("b", chain2.Last(), invalidNode2)}" +
                $"To deal with this uncertainty, you can either make {fixNode1} depend on {chain2.Last()} or {fixNode2} depend on {chain1.Last()}";
            var tuples = new List<Tuple<IToken, IDiagInfo>>
                         {
                             GetNodeTuple(fixNode1),
                             GetNodeTuple(chain1.Last()),
                             GetNodeTuple(fixNode2),
                             GetNodeTuple(chain2.Last())
                         };

            throw new DetailedRegistrationException(exceptionMessage, tuples, diagInfo);
        }
        private void IdentifyRoutes(List<List<Node>> allRoutes, List<Node> currentList, Graph map)
        {
            foreach (var node in map.Nodes)
            {
                if (currentList.Count > 0)
                    if (!map.EdgeExists(currentList.Last(), node.Value))
                        continue;

                if ((currentList.Select(x => x.Key).Contains(node.Key)))
                    continue;

                if (currentList.Count < map.Nodes.Count - 1)
                {
                    if (!(currentList.Select(x => x.Key).Contains(node.Key)))
                    {
                        var newList = CloneList(currentList);
                        newList.Add(node.Value);
                        IdentifyRoutes(allRoutes, newList, map);
                    }
                }
                else
                {
                    var newList = CloneList(currentList);
                    newList.Add(node.Value);

                    if (!map.EdgeExists(currentList.Last(), currentList.First()))
                        continue;

                    newList.Add(currentList.First());
                    allRoutes.Add(newList);
                }
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            // Task: to convert the Dictionary collection "elements"
            //to List with keeping hierarchy of elements
            Dictionary<string, string> elements = new Dictionary<string, string>()
            {
                {"Tissue", "Organ"},
                {"Cell", "Cells"},
                {"System", "Body"},
                {"Cells", "Tissue"},
                {"Organ", "System"},
            };

            List<string> hierarchy = new List<string>();

            string first = elements.Keys.First(el => !elements.ContainsValue(el));
            hierarchy.Add(first);

            while (elements.ContainsKey(hierarchy.Last()))
                hierarchy.Add(elements[hierarchy.Last()]);

            foreach (var item in hierarchy)
                Console.WriteLine(item);

            Console.ReadKey();
        }
        /// <summary>
        /// Reads the specified sub key.
        /// </summary>
        /// <param name="subKeys">The sub key.</param>
        /// <returns></returns>
        protected Object Read(string subKeys)
        {
            Object result = default(Object);

            try
            {
                string[] subKeyNames = subKeys.Split('/');
                List<RegistryKey> registryKeys = new List<RegistryKey>();
                for (int i = 0; i < subKeyNames.Length - 1; i++)
                {
                    RegistryKey currentRegistryKey = default(RegistryKey);
                    if (i == 0)
                    {
                        currentRegistryKey = Registry.CurrentUser.OpenSubKey(subKeyNames[i]);
                    }
                    else
                    {
                        currentRegistryKey = registryKeys[i - 1].OpenSubKey(subKeyNames[i]);
                    }
                    registryKeys.Add(currentRegistryKey);
                    if (registryKeys.Last() != null && subKeyNames.Last() != null)
                    {
                        result = registryKeys.Last().GetValue(subKeyNames.Last());
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            return result;
        }
    public int[] FindBest()
    {
      var remaining = new HashSet<Point>(_cities);
      var first = remaining.First();
      var route = new List<Point> { first };
      remaining.Remove(first);

      var numericRoute = new List<int>{_cities.IndexOf(first)};
      var distance = 0.0d;
      while (remaining.Any())
      {
        var shortest = double.MaxValue;
        Point next = null;
        foreach (var p in remaining)
        {
          var d = Distance(route.Last(), p);
          if (d < shortest)
          {
            shortest = d;
            next = p;
          }
        }
        route.Add(next);
        numericRoute.Add(_cities.IndexOf(next));
        remaining.Remove(next);
        distance += shortest;
    
      }


      distance += Distance(route.First(), route.Last());
      Console.WriteLine("Distance calculated in closestneighbour: " + distance);
      return numericRoute.ToArray();
    }
Example #22
0
        public async Task InitializeContextAsync()
        {
            //simulates a network delay
            await Task.Delay(TimeSpan.FromSeconds(2.5d));

            Tables = new List<Table>
            {
                new Table() {Description = "Back-Corner Two Top"},
                new Table() {Description = "Front Booth"}
            };

            StandardMenuItems = new List<MenuItem>
            {
                new MenuItem { Title = "French Bread & Fondue Dip", Price = 5.75m },
                new MenuItem { Title = "Curried Chicken and Rice", Price = 9.00m },
                new MenuItem { Title = "Feta-Stuffed Chicken", Price = 8.25m },
                new MenuItem { Title = "Grilled Pork Loin", Price = 11.50m },
                new MenuItem { Title = "Carnitas Tacos", Price = 7.50m },
                new MenuItem { Title = "Fillet Mignon & Asparagus", Price = 15.75m },
                new MenuItem { Title = "T-Bone Steak", Price = 12.25m },
                new MenuItem { Title = "Pineapple and Pear Salad", Price = 6.25m },
                new MenuItem { Title = "Sautéed Broccoli", Price = 3.75m },
                new MenuItem { Title = "Mashed Peas", Price = 3.25m }
            };

            Orders = new ObservableCollection<Order>
            {
                new Order { Complete = false, Expedite = true, SpecialRequests = "Allergic to Shellfish", Table = Tables.Last(), Items = new List<MenuItem> { StandardMenuItems.First() } },
                new Order { Complete = false, Expedite = false, SpecialRequests = string.Empty, Table = Tables.Last(), Items = new List<MenuItem> { StandardMenuItems.Last(), StandardMenuItems.First() } },
            };
        }
        // Editors
        void Extend(List<double[]> list, double topLayer)
        {
            double newAltitude = list.Last()[0];
            double dX = list.Last()[0] - list[list.Count - 2][0];
            double[] K = getK(list);

            for (int i = 0; newAltitude < topLayer; i++)
            {
                newAltitude += dX;
                double newPressure = getY(newAltitude, list.Last(), K);
                double[] newKey = { newAltitude, newPressure };

                if (newKey[1] < 0)
                {
                    if (list.Last()[1] == 0)
                        break;
                    else
                        newKey[1] = 0;
                }

                list.Add(newKey);
            }

            // Debug
            PrintCurve(list, "Extend");
        }
Example #24
0
        private void StartThreads()
        {
            //How many threads do I need?
            int itemCount = ((int)(nudMax.Value - nudMin.Value)) + 1;
            int threadCount = itemCount / (int)nudInterval.Value + 1;
            threadList = new List<Thread>(threadCount);

            //Split up my ranges
            int increment = (int)nudInterval.Value;
            int maximum = (int)nudMax.Value;
            
            int current = (int)nudMin.Value;
            int next = current + increment;

            while (current <= maximum)
            {
                if (next > maximum) next = maximum;
                //Create some threads
                threadList.Add(new Thread(new ParameterizedThreadStart(FindPrimes)));
                threadList.Last().Start(new Limits(current, next));
                threadList.Last().IsBackground = true;
                current = next + 1;
                next = current + increment;
            }
            //Problem!!  If my threads are foreground, we wait here until they are all done.
            //If they are background, they all exit once we get here.
            //We can solve some of these problems with a threadpool.
        }
Example #25
0
        public static int ReverseMod(int num, int mod)
        {
            if (Math.Abs(num)>mod)
                throw new Exception("Number should be less then mode");
            if (num < 0)
                num = mod + num;

            List<int> dividers = new List<int>();
            int rest = 0;

            int smaller = num;
            int bigger = mod;

            while (rest != 1)
            {
                rest = bigger%smaller;
                dividers.Add(bigger/smaller);

                bigger = smaller;
                smaller = rest;
            }
            List<int> p = new List<int>();
            p.Add(0);
            p.Add(1);
            foreach (var divider in dividers)
            {
                p.Add(-divider*p.Last() + p[p.Count()-2]);
            }
            return p.Last() > 0 ? p.Last() :  mod + p.Last();
        }
        public static List<INFATITrip> CalculateTripsByCarId(Int16 carId)
        {
            DBController dbc = new DBController();

            //Fetch all temporalinformation for a cardId
            List<TemporalInformation> datapoints = dbc.GetTimestampsByCarId(carId);
            dbc.Close();
            //Instantiate the containers for trips and timestamps fetched by a single date at a time
            List<INFATITrip> allTrips = new List<INFATITrip>();
            INFATITrip trip = new INFATITrip(carId);
            allTrips.Add(trip);

            //First case
            allTrips.Last().Timestamps.Add(new TemporalInformation(datapoints.ElementAt(0).EntryId, datapoints.ElementAt(0).Timestamp));

            //Starting to iterate over all timestamps
            for (int i = 1; i < datapoints.Count(); i++) {
                //Compare the last seen timestamp to the current, if more than 300 seconds has past, create a new trip and store the current timestamp in it
                if (Math.Abs(ToUnixTime(allTrips.Last().Timestamps.Last().Timestamp) - ToUnixTime(datapoints.ElementAt(i).Timestamp)) <= 180) {
                    allTrips.Last().Timestamps.Add(new TemporalInformation(datapoints.ElementAt(i).EntryId, datapoints.ElementAt(i).Timestamp));
                } else {
                    allTrips.Add(new INFATITrip(carId));
                    allTrips.Last().Timestamps.Add(new TemporalInformation(datapoints.ElementAt(i).EntryId, datapoints.ElementAt(i).Timestamp));
                }
            }

            return allTrips;
        }
Example #27
0
        private void HandleCollision(IHungryCreature creature, IRenderer renderer)
        {
            List<GameFieldCoords> creatureElements = new List<GameFieldCoords>();

            foreach (GameFieldCoords element in creature.GetPosition())
            {
                creatureElements.Add(element);
            }

            foreach (GameFieldCoords element in creatureElements)
            {
                if (element.Row >= renderer.GameFieldSize.Row || element.Row < 0
                    || element.Col >= renderer.GameFieldSize.Col || element.Col < 0)
                {
                    creature.IsDestroyed = true;
                }
            }

            for (int element = 0; element < creatureElements.Count - 1; element++)
            {
                if (creatureElements.Last().Row == creatureElements[element].Row
                    && creatureElements.Last().Col == creatureElements[element].Col)
                {
                    creature.IsDestroyed = true;
                }
            }
        }
Example #28
0
 public IList<Hand> ProcessFile(FileInfo fileInfo)
 {
     DateTime fileStartDate = DateTime.UtcNow;
     string fileStatus = "succes";
     var lastImportDate = _dataRepository.GetImportsRepository().GetLastImportFileDate(fileInfo.Name);
     IList<Hand> hands = new List<Hand>();
     try
     {
         hands = _parser.Parse(fileInfo.FullName, lastImportDate);
         _dataRepository.GetHandsRepository().SaveHandsSqlCommand(hands);
         OnNewFileProcessed(new NewFileProcessedEventArgs(fileInfo.Name, hands.Count, hands.Last()));
     }
     catch (Exception e)
     {
         fileStatus = "fail : " + e.Message + " " + e.StackTrace;
     }
     finally
     {
         DateTime endFileDate = DateTime.UtcNow;
         if (hands.Count > 0)
         {
             var lastHand = hands.Last();
             _dataRepository.GetImportsRepository().LogFileImport(fileInfo, fileStartDate, endFileDate, fileStatus, lastHand);
         }
     }
     return hands;
 }
Example #29
0
 /// группирование гэпов; применятся для работы с минутными свечками
 public static List<GapList> CreateGapList(List<GapInfo> gaps, int maxGapListLengthDays = 3, int maxGapCount = 50)
 {
     var result = new List<GapList>();
     foreach (var gap in gaps)
     {
         var requestStart = gap.start;
         while (requestStart < gap.end)
         {
             if(result.Count == 0)
                 result.Add(new GapList(maxGapListLengthDays, maxGapCount));
             var gapList = result.Last();
             if (gapList.GetFreeLengthDays() < 0.01) // 0.01 принято за минимально допустимое GetFreeLengthDays
             {
                 result.Add(new GapList(maxGapListLengthDays, maxGapCount));
                 gapList = result.Last();
             }
             var requestEnd = requestStart.AddDays(gapList.GetFreeLengthDays()).AddMinutes(-1);
             if (requestEnd > gap.end)
                 requestEnd = gap.end;
             gapList.AddGap(new GapInfo {start = requestStart, end = requestEnd});
             requestStart = requestEnd.AddMinutes(1);
         }
     }
     return result;
 }
        /// <summary>
        /// 将共享点前移,构成2个图元组成的新的小小的索引。
        /// </summary>
        /// <param name="recognizedPrimitiveIndex0"></param>
        /// <param name="recognizedPrimitiveIndex1"></param>
        /// <param name="drawMode"></param>
        /// <param name="lastIndex0"></param>
        /// <param name="lastIndex1"></param>
        /// <returns></returns>
        private List<uint> ArrangeIndexes(
            RecognizedPrimitiveInfo recognizedPrimitiveIndex0,
            RecognizedPrimitiveInfo recognizedPrimitiveIndex1,
            DrawMode drawMode,
            out uint lastIndex0, out uint lastIndex1)
        {
            var sameIndexList = new List<uint>();
            var array0 = new List<uint>(recognizedPrimitiveIndex0.VertexIds);
            var array1 = new List<uint>(recognizedPrimitiveIndex1.VertexIds);
            array0.Sort(); array1.Sort();
            int p0 = 0, p1 = 0;
            while (p0 < array0.Count && p1 < array1.Count)
            {
                if (array0[p0] < array1[p1])
                { p0++; }
                else if (array0[p0] > array1[p1])
                { p1++; }
                else
                {
                    sameIndexList.Add(array0[p0]);
                    array0.RemoveAt(p0);
                    array1.RemoveAt(p1);
                }
            }

            if (array0.Count == 0 && array1.Count == 0)
            { throw new Exception("Two primitives are totally the same!"); }

            if (array0.Count > 0)
            { lastIndex0 = array0.Last(); }
            else
            {
                if (sameIndexList.Count == 0)
                { throw new Exception("array0 is totally empty!"); }

                lastIndex0 = sameIndexList.Last();
            }

            if (array1.Count > 0)
            { lastIndex1 = array1.Last(); }
            else
            {
                if (sameIndexList.Count == 0)
                { throw new Exception("array1 is totally empty!"); }

                lastIndex1 = sameIndexList.Last();
            }

            if (lastIndex0 == lastIndex1) { throw new Exception(); }

            var result = new List<uint>();
            result.AddRange(sameIndexList);
            result.AddRange(array0);
            result.Add(uint.MaxValue);// primitive restart index
            result.AddRange(sameIndexList);
            result.AddRange(array1);

            return result;
        }
Example #31
0
        private void FindValidPath(Node node, List <Node> path)
        {
            var previousNode = path.Count == 0 ? null : path?.Last();

            //if bottom node reached calculate path length and compare to current max path
            if (node == null && previousNode != null && previousNode.Level == _maxBranchLength)
            {
                var pathValue = path.Sum(node => node.Value);

                if (_maxPath == null || pathValue > _maxPath.Value)
                {
                    _maxPath = new Path {
                        Steps = path, Value = pathValue
                    };

                    return;
                }
            }

            //recursively iterate throug branches
            if (node != null && (previousNode == null || previousNode?.Even != node.Even))
            {
                path.Add(node);

                FindValidPath(node.LeftChild, new List <Node>(path));
                FindValidPath(node.RightChild, new List <Node>(path));
            }
        }
Example #32
0
        public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi, List <StackValue> s)
        {
            Object retVal = base.Execute(c, dsi, s);

            if (retVal == null)
            {
                return(null);
            }

            StackValue propValue  = (StackValue)retVal;
            var        thisObject = s?.Last() ?? dsi.runtime.rmem.Stack.Last();

            bool isValidPointer = thisObject.IsPointer && thisObject.Pointer != Constants.kInvalidIndex;

            if (isValidPointer && propValue.IsReferenceType)
            {
                int classIndex = thisObject.metaData.type;
                if (classIndex != ProtoCore.DSASM.Constants.kInvalidIndex)
                {
                    var runtimeCore = dsi.runtime.RuntimeCore;
                    int idx         = runtimeCore.DSExecutable.classTable.ClassNodes[classIndex].Symbols.IndexOf(PropertyName);

                    var        obj      = runtimeCore.Heap.ToHeapObject <DSObject>(thisObject);
                    StackValue oldValue = obj.GetValueFromIndex(idx, runtimeCore);
                    if (!StackUtils.Equals(oldValue, propValue))
                    {
                        obj.SetValueAtIndex(idx, propValue, runtimeCore);
                    }
                }
            }

            return(retVal);
        }
Example #33
0
 public static StreamData <T> Create(StreamInfo <T> streamInfo, List <T> initData = null)
 {
     return(new StreamData <T>
     {
         CompletionTask = new TaskCompletionSource <int>(),
         CancelationToken = streamInfo.CancelationToken,
         Stream = streamInfo.Stream,
         Keys = streamInfo.Keys,
         Peer = streamInfo.Peer,
         LastSentData = initData?.Last(),
         KeepLastData = initData != null
     });
 }
Example #34
0
        /// <exception cref = "InvalidOperationException">
        /// when the number of menu options is greater than 9 or less than 1,
        /// or when the last item is not of type Exit.ExitOption
        /// </exception>
        public void ExecutingMenuOperation()
        {
            if (Options?.Count < 1 || Options?.Count > 9)
            {
                throw new InvalidOperationException("Nieodpowiednia ilość opcji!");
            }

            if (Options?.Last()?.GetType() != typeof(Exit.ExitOption))
            {
                throw new InvalidOperationException("Ostatnia opcja nie jest opcją wyjścia");
            }

            EventLoop();
        }
Example #35
0
        public async Task DownloadAllFiles(string startFile = null)
        {
            TwilioService twilioService = new TwilioService();

            bool isStarted = false;

            string lastFile = "";
            using (var context = new CovidContext())
            {
                List<DataCollectionStatistic> startFileStat = await context.DataCollectionStatistics.ToListAsync();
                lastFile = startFileStat?.Last()?.FileName;
            }

            if (string.IsNullOrWhiteSpace(startFile) && string.IsNullOrWhiteSpace(lastFile))
            {
                isStarted = true;
            }

            List<DataFile> files = new List<DataFile>();

            files = await GetListOfFiles("CSSEGISandData",
                                                "COVID-19",
                                                "csse_covid_19_data/csse_covid_19_daily_reports");
            foreach (DataFile file in files)
            {
                if (file.FileName == startFile)
                {
                    isStarted = true;
                }

                if (isStarted == true)
                {
                    DateTime startTime = DateTime.Now;
                    await ParseAndDeleteFile(file);
                    await SaveEntriesToDataModel(file.FileName);
                    DateTime fileComplete = DateTime.Now;
                    var elapsed = fileComplete - startTime;
                    twilioService.SendSMS($"COVIDAP -> File {file.FileName}. Records:{Entries.Count} Completed in {elapsed.Minutes}:{elapsed.Seconds}");
                    Entries.Clear();
                }

                if (file.FileName == lastFile)
                {
                    isStarted = true;
                }
            }
            twilioService.SendSMS("COVIDAP -> SUCCESS - UP TO DATE");
        }
Example #36
0
        private static IEnumerable <IList <int> > GetCombinations(int[] array, int m)
        {
            var  result  = new List <int>();
            bool isEmpty = result.Count() == 0;

            if (m > array.Length / 2 && m <= array.Length)
            {
                foreach (int[] j in CombinationsRosettaWoRecursion(m, array.Length))
                {
                    for (int i = 0; i < m && (result.Any() ? result?.Last() > (array[j[i]] - 4) : array[j[i]] < 4); i++)
                    {
                        result.Add(array[j[i]]);
                    }
                    yield return((IList <int>)result.Distinct().OrderBy(o => o).ToList());
                }
            }
        }
Example #37
0
 public Pair(List <string> data)
 {
     if (data == null || data.Count == 0 || data.All(d => string.IsNullOrEmpty(d)))
     {
         return;
     }
     data.RemoveAll(d => string.IsNullOrEmpty(d));
     Number = int.TryParse(data?.FirstOrDefault() ?? "", out int number)
            ? number
            : 999;
     CreateWorkTime(data);
     CreateDinnerOrSettlingTime(data);
     data.Remove(data.LastOrDefault());
     FlightsCount = int.TryParse(data?.Last()?.Split(' ')[0], out var number1)
                  ? number1
                  : -999;
     Flights = new List <Flight>();
 }
Example #38
0
        public async Task <bool> StraightSieveEratosthenesDemo(int limit, ObservableCollection <NaturalNumberViewModel> numbers, CancellationTokenSource taskCts)
        {
            return(await Task <bool> .Run(async() =>
            {
                DemoPrimeNumbers = new List <int>();
                int sequence = 1;
                BitArray primeCandidates = new BitArray(limit + 1);
                int p, j;
                for (p = 2; p *p <= limit; p++)
                {
                    if (taskCts.IsCancellationRequested)
                    {
                        return false;
                    }
                    if (!primeCandidates[p])
                    {
                        if (DemoPrimeNumbers.Count == 0 || p > DemoPrimeNumbers?.Last())
                        {
                            DemoPrimeNumbers.Add(p);
                        }

                        for (int i = p * 2; i <= limit; i += p)
                        {
                            if (taskCts.IsCancellationRequested)
                            {
                                return false;
                            }
                            primeCandidates[i] = true;
                            var compositeNumber = numbers.FirstOrDefault(x => x.Number == i);
                            if (compositeNumber != null)
                            {
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                                                                                                            () =>
                                {
                                    compositeNumber.CompositeFoundSequence = sequence++;
                                });
                                await Task.Delay(100);
                            }
                        }
                    }
                }
                return true;
            }));
        }
        internal DestinationProjXml(string destProjAbsolutePath)
        {
            try
            {
                DestProjAbsolutePath = PathMaker.MakeAbsolutePathFromPossibleRelativePathOrDieTrying(null, destProjAbsolutePath);
                DestProjDirectory    = Path.GetDirectoryName(DestProjAbsolutePath) ?? "";

                DestProjXdoc = XDocument.Load(DestProjAbsolutePath);
                RootXelement = DestProjXdoc.Element(Settings.MSBuild + "Project");
                ItemGroups   = RootXelement?.Elements(Settings.MSBuild + "ItemGroup").ToList();
            }
            catch (Exception e)
            {
                App.Crash(e, $"Crash: DestProjXml CTOR loading destination XML from {DestProjAbsolutePath}");
            }

            if (RootXelement == null)
            {
                App.Crash($"Crash: No MSBuild Namespace in {DestProjAbsolutePath}");
            }

            StartPlaceHolder = FindStartOrEndCommentOrCrashIfDuplicatesFound(Settings.StartPlaceholderComment);
            EndPlaceHolder   = FindStartOrEndCommentOrCrashIfDuplicatesFound(Settings.EndPlaceholderComment);

            if (StartPlaceHolder == null && RootXelement != null)
            {
                try
                {
                    XElement lastItemGroup = ItemGroups?.Last();
                    lastItemGroup?.AddAfterSelf(new XComment(Settings.EndPlaceholderComment));
                    lastItemGroup?.AddAfterSelf(new XComment(Settings.StartPlaceholderComment));
                    StartPlaceHolder = FindStartOrEndCommentOrCrashIfDuplicatesFound(Settings.StartPlaceholderComment);
                    EndPlaceHolder   = FindStartOrEndCommentOrCrashIfDuplicatesFound(Settings.EndPlaceholderComment);
                    Log.WriteLine("No placeholders in destination Project. Added them", ConsoleColor.Yellow);
                }
                catch (Exception e)
                {
                    App.Crash(e, $"Crash: DestProjXmladding placeholders to destination XML in {DestProjAbsolutePath}");
                }
            }

            OldLinkedXml = ReadLinkedXml();
            Keepers      = new List <XElement>();
        }
        /// <summary>
        /// The .net configuration provider doesn't play nice with the old configs. This attempts to clean it up just enough to get the information we need from it
        /// https://github.com/aspnet/Extensions/pull/862
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static void SanitizeConfig(string path)
        {
            string Cleaned = "<!--cleaned-->";

            List <string> oldLines = File.ReadAllLines(path).ToList();
            List <string> newLines = new List <string>();

            if (oldLines.Last() == Cleaned)
            {
                return;
            }

            int SkipDepth = 0;

            List <(string StartTag, string EndTag)> SkipSections = new List <(string StartTag, string EndTag)>()
            {
                //("<runtime>","</runtime>"),
                ("<controls>", "</controls>"),
                ("<httpModules>", "</httpModules>"),
                ("<system.web>", "</system.web>"),
                ("<system.net>", "</system.net>"),
                ("<system.webServer>", "</system.webServer>"),
                ("<system.codedom>", "</system.codedom>")
            };

            List <string> StripTags = new List <string>()
            {
                "<location",
                "</location>",
                "<system.webServer />"
            };

            Dictionary <string, List <string> > InsertSections = new Dictionary <string, List <string> >()
            {
                ["<configSections>"] = new List <string>()
                {
                    "<section name=\"appSettings\" type=\"System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" restartOnExternalChanges=\"false\" requirePermission=\"false\"/>",
                    "<section name=\"connectionStrings\" type=\"System.Configuration.ConnectionStringsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" requirePermission=\"false\"/>"
                }
            };

            List <string> TagsToName = new List <string>()
            {
                "add",
                "remove",
                "location"
            };

            foreach (string s in oldLines)
            {
                if (SkipSections.Any(ss => s.Contains(ss.StartTag)))
                {
                    SkipDepth++;
                }

                if (SkipDepth == 0 && !StripTags.Any(st => s.Contains(st)))
                {
                    {
                        newLines.Add(s);
                    }
                }

                if (InsertSections.Any(kvp => s.Contains(kvp.Key)))
                {
                    foreach (string toInsert in InsertSections[InsertSections.First(kvp => s.Contains(kvp.Key)).Key])
                    {
                        newLines.Add(toInsert);
                    }
                }

                if (SkipSections.Any(ss => s.Contains(ss.EndTag)))
                {
                    SkipDepth--;
                }
            }

            newLines.Add(Cleaned);

            File.WriteAllLines(path, newLines.Where(n => !string.IsNullOrWhiteSpace(n)));
        }
Example #41
0
 public static void endTime(ref TimeSpan counter)
 {
     counter += (DateTime.Now - beginTimes.Last());
     beginTimes.RemoveAt(beginTimes.Count - 1);
 }
Example #42
0
    public bool CanCastThisSkill(List <AttributeType> types)
    {
        if (SkillRequirements.Count == 0)
        {
            return(false);
        }

        int count = SkillRequirements.Count;

        List <AttributeType> temp    = new List <AttributeType>();
        List <int>           indexes = new List <int>();

        if (SkillRequirements.Count(a => a == SkillRequirements.First()) > 1 && types.Count(a => a == SkillRequirements.First()) > 1)
        {
            indexes = GetAllIndexOfType(SkillRequirements.First(), types);

            while (indexes.Count > SkillRequirements.Count)
            {
                indexes.Remove(indexes.Last());
            }
        }
        else
        {
            foreach (var type in SkillRequirements)
            {
                int index = 0;

                if (indexes.Count == 0)
                {
                    index = types.FindIndex(indexes.Count, a => a == type);
                }
                else
                {
                    index = types.FindIndex(indexes.Last(), a => a == type);
                }

                //No Requirement in current match, so return false
                if (index < 0)
                {
                    return(false);
                }

                indexes.Add(index);
            }
        }

        if (indexes.Count == 0)
        {
            return(false);
        }

        int num = indexes.First();

        for (int i = 1; i < indexes.Count; i++)
        {
            if (num < indexes[i])
            {
                num = indexes[i];
            }
            else
            {
                return(false);
            }
        }

        return(true);
    }
        public void ImportFactoriesFromSource(BuilderLibraryTreeItem sourceCategory)
        {
            var deferredFactories      = new List <IUxmlFactory>();
            var processingData         = new FactoryProcessingHelper();
            var emptyNamespaceControls = new List <ITreeViewItem>();

            foreach (var factories in VisualElementFactoryRegistry.factories)
            {
                if (factories.Value.Count == 0)
                {
                    continue;
                }

                var factory = factories.Value[0];
                if (!ProcessFactory(factory, processingData))
                {
                    // Could not process the factory now, because it depends on a yet unprocessed factory.
                    // Defer its processing.
                    deferredFactories.Add(factory);
                }
            }

            List <IUxmlFactory> deferredFactoriesCopy;

            do
            {
                deferredFactoriesCopy = new List <IUxmlFactory>(deferredFactories);
                foreach (var factory in deferredFactoriesCopy)
                {
                    deferredFactories.Remove(factory);
                    if (!ProcessFactory(factory, processingData))
                    {
                        // Could not process the factory now, because it depends on a yet unprocessed factory.
                        // Defer its processing again.
                        deferredFactories.Add(factory);
                    }
                }
            }while (deferredFactoriesCopy.Count > deferredFactories.Count);

            if (deferredFactories.Count > 0)
            {
                Debug.Log("Some factories could not be processed because their base type is missing.");
            }

            var categoryStack = new List <BuilderLibraryTreeItem>();

            foreach (var known in processingData.knownTypes.Values)
            {
                var split = known.uxmlNamespace.Split('.');
                if (split.Length == 0)
                {
                    continue;
                }

                // Avoid adding our own internal factories (like Package Manager templates).
                if (!Unsupported.IsDeveloperMode() && split.Length > 0 && s_NameSpacesToAvoid.Contains(split[0]))
                {
                    continue;
                }

                // Avoid adding UI Builder's own types, even in internal mode.
                if (split.Length >= 3 && split[0] == "Unity" && split[1] == "UI" && split[2] == "Builder")
                {
                    continue;
                }

                var asset     = new VisualElementAsset(known.uxmlQualifiedName);
                var slots     = new Dictionary <string, VisualElement>();
                var overrides = new List <TemplateAsset.AttributeOverride>();
                var vta       = ScriptableObject.CreateInstance <VisualTreeAsset>();
                var context   = new CreationContext(slots, overrides, vta, null);

                Type elementType = null;
                var  factoryType = known.GetType();
                while (factoryType != null && elementType == null)
                {
                    if (factoryType.IsGenericType && factoryType.GetGenericTypeDefinition() == typeof(UxmlFactory <,>))
                    {
                        elementType = factoryType.GenericTypeArguments[0];
                    }
                    else
                    {
                        factoryType = factoryType.BaseType;
                    }
                }

                var newItem = new BuilderLibraryTreeItem(
                    known.uxmlName, "CustomCSharpElement", elementType, () => known.Create(asset, context));
                newItem.HasPreview = true;

                if (string.IsNullOrEmpty(split[0]))
                {
                    emptyNamespaceControls.Add(newItem);
                }
                else
                {
                    AddCategoriesToStack(sourceCategory, categoryStack, split);
                    if (categoryStack.Count == 0)
                    {
                        sourceCategory.AddChild(newItem);
                    }
                    else
                    {
                        categoryStack.Last().AddChild(newItem);
                    }
                }
            }

            sourceCategory.AddChildren(emptyNamespaceControls);
        }
Example #44
0
 static void LastElement()                                        // элемент с конца коллекции
 {
     Console.WriteLine("Элемент с конца коллекции");
     Console.WriteLine(vehicleCollection.Last <Vehicle>());
     vehicleCollection[vehicleCollection.Count - 1].Print1();
 }
Example #45
0
        private static List <Defect> SeedDefectData(ProductDevelopmentContext context, List <Severity> severities, Project project, List <User> users)
        {
            var defects = new List <Defect>
            {
                new Defect
                {
                    Project          = project,
                    Summary          = "Test defect summary 1",
                    StepsToReproduce = "Test steps to reproduce 1",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddDays(-3),
                    ModifyDate       = DateTime.Now.AddDays(-2),
                    Severity         = severities[0]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 2",
                    StepsToReproduce = "Test steps to reproduce 2",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.First(),
                    CreateDate       = DateTime.Now.AddDays(-2),
                    ModifyDate       = DateTime.Now.AddDays(-1),
                    Severity         = severities[1]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 3",
                    StepsToReproduce = "Test steps to reproduce 3",
                    CreatorUser      = users.Last(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddMonths(-2),
                    ModifyDate       = DateTime.Now.AddMonths(-1),
                    Severity         = severities[2]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "Test defect summary 4",
                    StepsToReproduce = "Test steps to reproduce 4",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddMonths(-3),
                    ModifyDate       = DateTime.Now.AddMonths(-2),
                    Severity         = severities[0]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 5",
                    StepsToReproduce = "Test steps to reproduce 5",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.First(),
                    CreateDate       = DateTime.Now.AddHours(-3),
                    ModifyDate       = DateTime.Now.AddHours(-2),
                    Severity         = severities[1]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 6",
                    StepsToReproduce = "Test steps to reproduce 6",
                    CreatorUser      = users.Last(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddHours(-2),
                    ModifyDate       = DateTime.Now.AddHours(-1),
                    Severity         = severities[2]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "Test defect summary 7",
                    StepsToReproduce = "Test steps to reproduce 7",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddMinutes(-3),
                    ModifyDate       = DateTime.Now.AddMinutes(-2),
                    Severity         = severities[0]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 8",
                    StepsToReproduce = "Test steps to reproduce 8",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.First(),
                    CreateDate       = DateTime.Now.AddMinutes(-2),
                    ModifyDate       = DateTime.Now.AddMinutes(-1),
                    Severity         = severities[1]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 9",
                    StepsToReproduce = "Test steps to reproduce 9",
                    CreatorUser      = users.Last(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddHours(-5),
                    ModifyDate       = DateTime.Now.AddHours(-4),
                    Severity         = severities[2]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "Test defect summary 10",
                    StepsToReproduce = "Test steps to reproduce 10",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddHours(-4),
                    ModifyDate       = DateTime.Now.AddHours(-3),
                    Severity         = severities[0]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 11",
                    StepsToReproduce = "Test steps to reproduce 11",
                    CreatorUser      = users.First(),
                    AssignedToUser   = users.First(),
                    CreateDate       = DateTime.Now.AddHours(-2),
                    ModifyDate       = DateTime.Now.AddHours(-1),
                    Severity         = severities[1]
                },
                new Defect
                {
                    Project          = project,
                    Summary          = "This is a test defect summary 12",
                    StepsToReproduce = "Test steps to reproduce 12",
                    CreatorUser      = users.Last(),
                    AssignedToUser   = users.Last(),
                    CreateDate       = DateTime.Now.AddMonths(-5),
                    ModifyDate       = DateTime.Now.AddMonths(-4),
                    Severity         = severities[2]
                }
            };

            defects.ForEach(x => context.Defects.Add(x));
            return(defects);
        }
Example #46
0
        public APIHierarchyNode AddRoot(APIRecord Record)
        {
            // Try to find the "primary" path to a root object; ignoring interfaces and non-UObject base classes
            List <APIRecord> PrimaryHierarchy = new List <APIRecord>();

            for (APIRecord ParentRecord = Record; ParentRecord != null;)
            {
                // Add the current record
                PrimaryHierarchy.Add(ParentRecord);

                // Try to find a UObject base class
                List <APIRecord> Candidates = new List <APIRecord>();
                foreach (KeyValuePair <XmlNode, APIRecord> BaseRecord in ParentRecord.BaseRecords)
                {
                    if (BaseRecord.Key.InnerText.StartsWith("U") || BaseRecord.Key.InnerText.StartsWith("A"))
                    {
                        Candidates.Add(BaseRecord.Value);
                    }
                }

                // If we didn't get one, add everything else
                if (Candidates.Count == 0)
                {
                    foreach (KeyValuePair <XmlNode, APIRecord> BaseRecord in ParentRecord.BaseRecords)
                    {
                        Candidates.Add(BaseRecord.Value);
                    }
                }

                // Move to the next record
                ParentRecord = (Candidates.Count == 1) ? Candidates[0] : null;
            }

            // Create the hidden root node of the hierarchy
            APIHierarchyNode NextNode = this;

            // Show the list from root; show a flat list of base classes for the last record
            if (PrimaryHierarchy.Last().BaseRecords.Count > 0)
            {
                foreach (KeyValuePair <XmlNode, APIRecord> BaseRecord in PrimaryHierarchy.Last().BaseRecords)
                {
                    if (BaseRecord.Value == null)
                    {
                        NextNode.Children.Add(new APIHierarchyNode(BaseRecord.Key.InnerText, false));
                    }
                    else
                    {
                        NextNode.Children.Add(new APIHierarchyNode(BaseRecord.Value.FullName, BaseRecord.Value.LinkPath, false));
                    }
                }
                NextNode = NextNode.Children.Last();
            }

            // Append the rest of the primary hierarchy
            for (int Idx = PrimaryHierarchy.Count - 1; Idx > 0; Idx--)
            {
                APIRecord ParentRecord = PrimaryHierarchy[Idx];
                NextNode.Children.Add(new APIHierarchyNode(ParentRecord.FullName, ParentRecord.LinkPath, false));
                NextNode = NextNode.Children.Last();
            }

            // Add the current record
            NextNode.Children.Add(new APIHierarchyNode(Record.FullName, false));
            return(NextNode.Children.Last());
        }
Example #47
0
        public override IEnumerable <(ICandle, ITradingAdviceCode)> AllForecasts(IEnumerable <ICandle> candles)
        {
            if (candles.Count() < MinNumberOfCandles)
            {
                throw new Exception("Number of candles less then expected");
            }

            RedWeddingPreset preset = null;

            if (!string.IsNullOrWhiteSpace(Preset))
            {
                preset = JsonConvert.DeserializeObject <RedWeddingPreset>(Preset);
            }

            List <(ICandle, ITradingAdviceCode)> result = new List <(ICandle, ITradingAdviceCode)>();

            decimal fastEnd   = 0.666m;
            int     smaPeriod = preset?.Sma ?? 6;

            List <decimal?> open  = candles.Open().Sma(smaPeriod);
            List <decimal?> close = candles.Close().Sma(smaPeriod);
            List <decimal?> high  = candles.High().Sma(smaPeriod);
            List <decimal?> low   = candles.Low().Sma(smaPeriod);

            List <decimal> closes = candles.Close();

            // Calculate the vClose
            List <decimal?> vClose = new List <decimal?>();

            for (int i = 0; i < open.Count; i++)
            {
                if (open[i].HasValue && close[i].HasValue && low[i].HasValue && high[i].HasValue)
                {
                    vClose.Add((open[i].Value + close[i].Value + low[i].Value + high[i].Value) / 4);
                }
                else
                {
                    vClose.Add(null);
                }
            }

            // Calculate the vOpen
            decimal         smooth        = fastEnd * fastEnd;
            List <decimal?> vOpen         = new List <decimal?>();
            List <decimal?> shiftedvClose = new List <decimal?> {
                null
            };

            foreach (decimal?item in vClose)
            {
                if (item != vClose.Last())
                {
                    shiftedvClose.Add(item);
                }
            }

            for (int i = 0; i < vClose.Count; i++)
            {
                if (shiftedvClose[i] != null)
                {
                    if (vClose[i] == null)
                    {
                        vOpen.Add(shiftedvClose[i]);
                    }
                    else if (vOpen[i - 1] == null)
                    {
                        vOpen.Add(shiftedvClose[i]);
                    }
                    else
                    {
                        vOpen.Add(vOpen[i - 1] + smooth * (shiftedvClose[i] - vOpen[i - 1]));
                    }
                }
            }

            List <decimal?> snow_high = new List <decimal?>();

            for (int i = 0; i < vClose.Count; i++)
            {
                if (high[i].HasValue && vClose[i].HasValue && vOpen[i].HasValue)
                {
                    snow_high.Add(Math.Max(high[i].Value, Math.Max(vClose[i].Value, vOpen[i].Value)));
                }
                else
                {
                    snow_high.Add(null);
                }
            }

            List <decimal?> snow_low = new List <decimal?>();

            for (int i = 0; i < vClose.Count; i++)
            {
                if (low[i].HasValue && vClose[i].HasValue && vOpen[i].HasValue)
                {
                    snow_low.Add(Math.Min(low[i].Value, Math.Min(vClose[i].Value, vOpen[i].Value)));
                }
                else
                {
                    snow_low.Add(null);
                }
            }

            List <decimal?> long_sma  = vClose.Sma(10);
            List <decimal?> short_sma = vClose.Sma(3);
            StochItem       stoch     = candles.Stoch();
            List <decimal?> fish      = candles.Fisher();

            List <bool> sma_crossover  = short_sma.Crossover(long_sma);
            List <bool> sma_crossunder = short_sma.Crossunder(long_sma);
            List <bool> snow_cross     = vClose.Crossunder(vOpen);

            List <bool> stoch_cross  = stoch.K.Crossunder(80);
            List <bool> stoch_cross2 = stoch.K.Crossunder(stoch.D);

            for (int i = 0; i < candles.Count(); i++)
            {
                if (i <= 1)
                {
                    result.Add((candles.ElementAt(i), TradingAdviceCode.HOLD));
                }
                else if (fish[i] >= fish[i - 1] && closes[i] < snow_high[i] && sma_crossover[i])
                {
                    result.Add((candles.ElementAt(i), TradingAdviceCode.BUY));
                }
                else if (fish[i] < fish[i - 1] && fish[i - 1] >= fish[i - 2] || sma_crossunder[i] || snow_cross[i] || stoch_cross[i] || stoch_cross2[i] && stoch.K[i - 1] > 80)
                {
                    result.Add((candles.ElementAt(i), TradingAdviceCode.SELL));
                }
                else
                {
                    result.Add((candles.ElementAt(i), TradingAdviceCode.HOLD));
                }
            }

            return(result);
        }
Example #48
0
        public static string[] SplitLexically(this string text, int desiredChunkLength)
        {
            var result = new List <string>();

            foreach (string item in text.Split(newLineSeparators, StringSplitOptions.None))
            {
                string paragraph               = item;
                var    extraIndent             = 0;
                var    merge                   = false;
                int    firstDesiredChunkLength = desiredChunkLength;
                int    allDesiredChunkLength   = desiredChunkLength;

                string[] fittedLines = null;

                const string prefix = "${<=";

                if (paragraph.StartsWith(prefix)) // e.g. "${<=12}" or "${<=-12}" (to merge with previous line)
                {
                    var indent_info = paragraph.Split('}').First();

                    paragraph = paragraph.Substring(indent_info.Length + 1);
                    int.TryParse(indent_info.Substring(prefix.Length).Replace("}", ""), out extraIndent);

                    if (extraIndent != 0)
                    {
                        firstDesiredChunkLength   =
                            allDesiredChunkLength = desiredChunkLength - Math.Abs(extraIndent);

                        if (extraIndent < 0)
                        {
                            merge = true;
                            if (result.Any())
                            {
                                firstDesiredChunkLength = desiredChunkLength - result.Last().Length;
                                firstDesiredChunkLength = firstDesiredChunkLength.Limit(0, desiredChunkLength);
                            }

                            if (firstDesiredChunkLength == 0)  // not enough space to merge so break it to the next line
                            {
                                merge = false;
                                firstDesiredChunkLength = allDesiredChunkLength;
                            }

                            extraIndent = -extraIndent;
                        }

                        fittedLines = SplitLexicallyWithoutTakingNewLineIntoAccount(paragraph, firstDesiredChunkLength, allDesiredChunkLength);

                        for (int i = 0; i < fittedLines.Length; i++)
                        {
                            if (i > 0 || !merge)
                            {
                                fittedLines[i] = ' '.Repeat(extraIndent) + fittedLines[i];
                            }
                        }
                    }
                }

                if (fittedLines == null)
                {
                    fittedLines = SplitLexicallyWithoutTakingNewLineIntoAccount(paragraph, firstDesiredChunkLength, allDesiredChunkLength);
                }

                if (merge && result.Any())
                {
                    result[result.Count - 1] = result[result.Count - 1] + fittedLines.FirstOrDefault();
                    fittedLines = fittedLines.Skip(1).ToArray();
                }

                result.AddRange(fittedLines);
            }
            return(result.ToArray());
        }
        private void btnCumpara_Click(object sender, EventArgs e)
        {
            inForma = false;
            List <Persoana> persoane = adminPersoane.GetPersoane();

            try
            {
                List <Masina> masini = adminMasini.GetMasiniIndex(Convert.ToInt32(masina.IdMasina - 1));
                if (masini.Last() != null)
                {
                    if (masini.Last().NumeProprietar == OptiuneInfoForm.InfoPersoana.NumeComplet)
                    {
                        MessageBox.Show("Nu puteti cumpara o masina care va apartine!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (OptiuneInfoForm.InfoPersoana.Buget < masini.Last().Pret)
                        {
                            MessageBox.Show("Nu aveti suficiente fonduri pentru a cumpara aceasta masina!", "Fonduri insuficiente", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        else
                        {
                            OptiuneInfoForm.InfoPersoana.Buget -= masini.Last().Pret;
                            adminPersoane.UpdatePersoana(OptiuneInfoForm.InfoPersoana);
                            LoginForm.infoForm.lblBuget.Text = "Buget: " + OptiuneInfoForm.InfoPersoana.Buget + "$";
                            inForma = true;

                            foreach (Persoana p in persoane)
                            {
                                if (p.NumeComplet == masini.Last().NumeProprietar)
                                {
                                    p.Buget += masini.Last().Pret;
                                    adminPersoane.UpdatePersoana(p);
                                }
                            }
                            masini.Last().NumeProprietar = OptiuneInfoForm.InfoPersoana.NumeComplet;
                            masini.Last().istoricProprietari.Add(masini.Last().NumeProprietar);
                            adminMasini.UpdateMasina(masini.Last());
                            lblProprietar.Text = "Proprietar: " + masini.Last().NumeProprietar;
                            MessageBox.Show("Masina achizitionata cu succes!", "Info Cumparare", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
            catch
            {
                MessageBox.Show("S-a produs o eroare!", "Eroare selectie", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #50
0
 public int GetLastPing() => _pingHistory?.Last() ?? 0;
Example #51
0
    private void ListPage(int pageNumber)
    {
        var previousIndex = this.currentIndex;
        var pageIndex     = pageNumber - 1;

        this.currentIndex = pageIndex;

        foreach (var prefab in this.levelPrefabs)
        {
            prefab.transform.SetParent(null, false);
        }

        var activeButtons = new List <GameObject>();

        for (var i = 0; i < this.LevelsPerPage && i < this.activePagedLevelData[pageIndex].Count; ++i)
        {
            var prefab = i < this.levelPrefabs.Count ? this.levelPrefabs[i] : null;
            if (prefab == null)
            {
                prefab = Instantiate(this.listLevelPrefab, Vector3.zero, Quaternion.identity);
                this.levelPrefabs.Add(prefab);
            }
            activeButtons.Add(prefab);
            prefab.transform.SetParent(this.levelHolder.transform, false);
            prefab.name = $"levelButton{i + 1}";

            var text         = prefab.GetComponentInChildren <Text>();
            var runtimeIndex = pageIndex * this.LevelsPerPage + i;
            text.text = $"#{runtimeIndex + 1}";

            var levelData   = this.activePagedLevelData[pageIndex][i];
            var button      = prefab.GetComponent <CustomButton>();
            var isPurchased = this.IsPurchased(levelData);

            var isPlayable = false;
            if (IsAllAvailable)
            {
                isPlayable = true;// && isPurchased; // test all purchased levels
            }
            else
            {
                isPlayable = this.IsPlayableLevel(levelData) && isPurchased;
            }

            button.Toggle(isPlayable);
            button.interactable = true;//isPlayable || !isPurchased;

            var levelButton = prefab.GetComponent <LevelButton>();
            levelButton.SetIcon(
                this.activeCategory,
                isPlayable,
                isPurchased,
                levelData.IsCompleted,
                levelData.IsCompleted ? this.completedLevelColor : this.activeLevelColor);

            button.onClick.RemoveAllListeners();
            button.onClick.AddListener(() =>
            {
                if (isPlayable)
                {
                    var data             = this.File.LoadJson <WarehouseManager.Data>(levelData.relativePath);
                    data.runtimeIndex    = runtimeIndex;
                    data.runtimeCategory = this.activeCategory;
                    this.PlaySfx();
                    this.OnLevelSelectedEvent.Invoke(data, levelData);
                }
                else if (!isPurchased && iapAlert != null)
                {
                    this.PlaySfx();
                    iapAlert.PromptIap(IAPLevelPak.GetIAPRequirement(levelData.FileName));
                }
                else if (!GameContext.IsNavigationEnabled)
                {
                    this.EventSystem.SetSelectedGameObject(null);
                }
            });

            var row  = i / this.levelsPerRow;
            var col  = i - row * this.levelsPerRow;
            var rect = prefab.GetComponent <RectTransform>();
            rect.localPosition = rect.localPosition
                                 .WithX(this.startListingPosition.x + col * this.levelWidth)
                                 .WithY(this.startListingPosition.y - row * this.levelHeight);
        }

        if (GameContext.IsNavigationEnabled)
        {
            if (!this.isInitialized)
            {
                this.SelectDefault();
            }
            else if (this.EventSystem.currentSelectedGameObject?.activeInHierarchy != true)
            {
                if (activeButtons.HasItems())
                {
                    var selectTarget = previousIndex > this.currentIndex ? activeButtons.First() : activeButtons.Last();
                    this.EventSystem.SetSelectedGameObject(selectTarget);
                }
                else
                {
                    this.SelectDefault();
                }
            }
        }

        this.isInitialized = true;
    }
Example #52
0
        public ActionResult BlogMonths()
        {
            if (!_blogSettings.Enabled)
            {
                return(Content(""));
            }

            var cacheKey    = string.Format(ModelCacheEventConsumer.BLOG_MONTHS_MODEL_KEY, _workContext.WorkingLanguage.Id, _storeContext.CurrentStore.Id);
            var cachedModel = _cacheManager.Get(cacheKey, () =>
            {
                var model = new List <BlogPostYearModel>();

                var blogPosts = _blogService.GetAllBlogPosts(_storeContext.CurrentStore.Id,
                                                             _workContext.WorkingLanguage.Id, null, null, 0, int.MaxValue);
                if (blogPosts.Count > 0)
                {
                    var months = new SortedDictionary <DateTime, int>();

                    var first = blogPosts[blogPosts.Count - 1].CreatedOnUtc;
                    while (DateTime.SpecifyKind(first, DateTimeKind.Utc) <= DateTime.UtcNow.AddMonths(1))
                    {
                        var list = blogPosts.GetPostsByDate(new DateTime(first.Year, first.Month, 1), new DateTime(first.Year, first.Month, 1).AddMonths(1).AddSeconds(-1));
                        if (list.Count > 0)
                        {
                            var date = new DateTime(first.Year, first.Month, 1);
                            months.Add(date, list.Count);
                        }

                        first = first.AddMonths(1);
                    }


                    int current = 0;
                    foreach (var kvp in months)
                    {
                        var date          = kvp.Key;
                        var blogPostCount = kvp.Value;
                        if (current == 0)
                        {
                            current = date.Year;
                        }

                        if (date.Year > current || model.Count == 0)
                        {
                            var yearModel = new BlogPostYearModel()
                            {
                                Year = date.Year
                            };
                            model.Add(yearModel);
                        }

                        model.Last().Months.Add(new BlogPostMonthModel()
                        {
                            Month         = date.Month,
                            BlogPostCount = blogPostCount
                        });

                        current = date.Year;
                    }
                }
                return(model);
            });

            return(PartialView(cachedModel));
        }
 /// <summary>
 /// Deserializes <paramref name="CsvText"/>
 /// in Array of <typeparamref name="T"/>
 /// </summary>
 /// <param name="CsvText">Csv File Text</param>
 /// <param name="UseFirstRowAsHeaders">
 /// When true, the First row of the CSV File will be used as column headers.
 /// When false, the Column Index defined in <see cref="CsvColumnAttribute"/> will be used.
 /// </param>
 /// <returns>Array of <typeparamref name="T"/> with values from CSV File</returns>
 private IEnumerable<T> DeSerializeText(string CsvText, bool UseFirstRowAsHeaders)
 {
     if (!UseFirstRowAsHeaders
         && ColumnSchema.Count(e => e.ColumnNumber == -1) > 0)
         throw new InvalidOperationException("Column Number not set");
     if (CsvText == string.Empty)
         return new T[0];
     List<List<string>> Csv = new List<List<string>>(); //Csv File (as string)
     StringReader fileReader = new StringReader(CsvText,
         CsvStyle.Aggregate, CsvStyle.LineDelimiter);
     while (!fileReader.EOF)
     {
         Csv.Add(new List<string>());
         StringReader lineReader = new StringReader(fileReader.Read(),
             CsvStyle.Aggregate, CsvStyle.Delimiter);
         //Add Cell (replace double Aggregate with single)
         while (!lineReader.EOF)
             Csv.Last().Add(lineReader.Read()?.Replace(
                 CsvStyle.Aggregate + CsvStyle.Aggregate,
                 CsvStyle.Aggregate));
     }
     if (UseFirstRowAsHeaders)
     {
         //Get the Schema for this file
         ColumnSchema = new List<CsvColumn>();
         foreach (PropertyInfo property in Properties)
             ColumnSchema.Add(new CsvColumn(property, Csv[0], Strict));
     }
     //Serialize into T
     List<T> list = new List<T>();
     //Start at first row if not using first row as headers
     for (int i = UseFirstRowAsHeaders ? 1 : 0; i < Csv.Count; i++)
     {
         list.Add(new T());
         //Process all columns that we are not ignoring
         foreach (CsvColumn column in ColumnSchema.Where(e => e.ColumnNumber != -1))
         {
             if (column.ColumnNumber < Csv[i].Count)
             {
                 try
                 {
                     column.Property.SetValue(list.Last(),
                         GetValue(column.Property, Csv[i][column.ColumnNumber]));
                 }
                 catch (System.FormatException)
                 {
                     //Throw parsing error exception
                     throw new InvalidOperationException(
                         $"Error Converting Value to desired format on " +
                         $"Line Number {i}, Column '{column.ColumnName}'/" +
                         $"Column No '{column.ColumnNumber}'. " +
                         $"See inner exception for further details",
                         new InvalidOperationException(
                             $"Target Type was {column.Property.PropertyType}. " +
                             $"Value was '{Csv[i][column.ColumnNumber]}'"));
                 }
             }
         }
     }
     return list.ToArray();
 }
Example #54
0
        private static void MakeGreedySlideshow()
        {
            int totalScore = 0;

            Console.WriteLine($"Sorting by tags...");

            Slides = Slides.OrderByDescending(s => s.HashedTags.Length).ToArray();

            var inputList = Slides.ToList();
            var result    = new List <Slide>();

            Console.WriteLine($"Comparing tags...");

            result.Add(inputList[0]);
            inputList.RemoveAt(0);

            while (inputList.Any())
            {
                var batch     = inputList.Take(Math.Min(3000, inputList.Count)).ToList();
                int batchSize = batch.Count;

                while (batch.Count > batchSize / 2)
                {
                    Slide currentSlide = result.Last();

                    Slide nextSlide = batch[0];
                    int   maxScore  = ScoreSlides(currentSlide, nextSlide);

                    for (int i = 1; i < batch.Count; i++)
                    {
                        int score = ScoreSlides(currentSlide, batch[i]);
                        if (maxScore < score)
                        {
                            nextSlide = batch[i];
                            maxScore  = score;
                            if (maxScore >= (int)(currentSlide.HashedTags.Length / 2))
                            {
                                break;
                            }
                        }
                        else if (maxScore >= (int)(batch[i].HashedTags.Length / 2))
                        {
                            break;
                        }
                    }

                    totalScore += maxScore;

                    result.Add(nextSlide);
                    batch.Remove(nextSlide);
                    inputList.Remove(nextSlide);

                    //Console.WriteLine($"Score: {totalScore} | {inputList.Count()} slides to sort...");
                }

                Console.WriteLine($"Score: {totalScore} | {inputList.Count()} slides to sort...");
            }

            Console.WriteLine($"Score: {totalScore} | {inputList.Count()} slides to sort...");

            Slides = result.ToArray();
        }
Example #55
0
        protected override void OnUpdateTextureAndBillboardVertices(IDeviceResources deviceResources)
        {
            Width  = 0;
            Height = 0;
            // http://www.cyotek.com/blog/angelcode-bitmap-font-parsing-using-csharp
            var tempList = new List <BillboardVertex>(100);

            foreach (var textInfo in TextInfo)
            {
                int  tempPrevCount = tempList.Count;
                int  x             = 0;
                int  y             = 0;
                var  w             = BitmapFont.TextureSize.Width;
                var  h             = BitmapFont.TextureSize.Height;
                char previousCharacter;

                previousCharacter = ' ';
                var normalizedText = textInfo.Text;
                var rect           = new RectangleF(textInfo.Origin.X, textInfo.Origin.Y, 0, 0);
                foreach (char character in normalizedText)
                {
                    switch (character)
                    {
                    case '\n':
                        x  = 0;
                        y -= BitmapFont.LineHeight;
                        break;

                    default:
                        Character data    = BitmapFont[character];
                        int       kerning = BitmapFont.GetKerning(previousCharacter, character);
                        tempList.Add(DrawCharacter(data, new Vector3(x + data.Offset.X, y - data.Offset.Y, 0), w, h, kerning, textInfo));

                        x += data.XAdvance + kerning;
                        break;
                    }
                    previousCharacter = character;
                    if (tempList.Count > 0)
                    {
                        rect.Width  = Math.Max(rect.Width, x * textInfo.Scale * textureScale);
                        rect.Height = Math.Max(rect.Height, Math.Abs(tempList.Last().OffBR.Y));
                    }
                }
                var transform = textInfo.Angle != 0 ? Matrix3x2.Rotation(textInfo.Angle) : Matrix3x2.Identity;
                var halfW     = rect.Width / 2;
                var halfH     = rect.Height / 2;
                //Add backbround vertex first. This also used for hit test
                BillboardVertices.Add(new BillboardVertex()
                {
                    Position   = textInfo.Origin.ToVector4(),
                    Background = textInfo.Background,
                    TexTL      = Vector2.Zero,
                    TexBR      = Vector2.Zero,
                    OffTL      = Matrix3x2.TransformPoint(transform, new Vector2(-halfW, halfH)),
                    OffBR      = Matrix3x2.TransformPoint(transform, new Vector2(halfW, -halfH)),
                    OffTR      = Matrix3x2.TransformPoint(transform, new Vector2(-halfW, -halfH)),
                    OffBL      = Matrix3x2.TransformPoint(transform, new Vector2(halfW, halfH)),
                });

                textInfo.UpdateTextInfo(rect.Width, rect.Height);

                for (int k = tempPrevCount; k < tempList.Count; ++k)
                {
                    var v = tempList[k];
                    v.OffTL     = Matrix3x2.TransformPoint(transform, v.OffTL + new Vector2(-halfW, halfH));
                    v.OffBR     = Matrix3x2.TransformPoint(transform, v.OffBR + new Vector2(-halfW, halfH));
                    v.OffTR     = Matrix3x2.TransformPoint(transform, v.OffTR + new Vector2(-halfW, halfH));
                    v.OffBL     = Matrix3x2.TransformPoint(transform, v.OffBL + new Vector2(-halfW, halfH));
                    tempList[k] = v;
                }
                Width  += rect.Width;
                Height += rect.Height;
            }

            foreach (var v in tempList)
            {
                BillboardVertices.Add(v);
            }
        }
Example #56
0
        public virtual List <List <string> > GetFormTable(bool selected)
        {
            var         exportTable = new List <List <string> >();
            IList <int> exportedRows, exportedColumns;

            if (selected && treeDataGridView.SelectedCells.Count > 0 && !treeDataGridView.AreAllCellsSelected(false))
            {
                var selectedRows    = new Set <int>();
                var selectedColumns = new Map <int, int>(); // ordered by DisplayIndex

                foreach (DataGridViewCell cell in treeDataGridView.SelectedCells)
                {
                    selectedRows.Add(cell.RowIndex);
                    selectedColumns[cell.OwningColumn.DisplayIndex] = cell.ColumnIndex;
                }

                exportedRows    = selectedRows.ToList();
                exportedColumns = selectedColumns.Values;
            }
            else
            {
                exportedRows    = treeDataGridView.Rows.Cast <DataGridViewRow>().Select(o => o.Index).ToList();
                exportedColumns = treeDataGridView.GetVisibleColumnsInDisplayOrder().Select(o => o.Index).ToList();
            }

            // add column headers
            exportTable.Add(new List <string>());
            foreach (var columnIndex in exportedColumns)
            {
                exportTable.Last().Add(treeDataGridView.Columns[columnIndex].HeaderText);
            }

            foreach (int rowIndex in exportedRows)
            {
                /* TODO: how to handle non-root rows?
                 * var row = rows[rowIndex];
                 *
                 * // skip non-root rows or filtered rows
                 * if (rowIndexHierarchy.Count > 1 || getRowFilterState(row) == RowFilterState.Out)
                 *  continue;*/

                var rowIndexHierarchy = treeDataGridView.GetRowHierarchyForRowIndex(rowIndex);

                var rowText = new List <string>();
                foreach (var columnIndex in exportedColumns)
                {
                    object value = treeDataGridView[columnIndex, rowIndex].Value ?? String.Empty;
                    rowText.Add(value.ToString());

                    if (columnIndex == 0 && rowIndexHierarchy.Count > 1)
                    {
                        int indent = (rowIndexHierarchy.Count - 1) * 2;
                        rowText[rowText.Count - 1] = new string(' ', indent) + rowText[rowText.Count - 1];
                    }
                }

                exportTable.Add(rowText);
            }

            return(exportTable);
        }
Example #57
0
        public override void BeforeRender(float dt)
        {
            if (meshRefOpaque == null && meshRefOit == null)
            {
                return;
            }
            if (capi.IsGamePaused)
            {
                return;
            }

            if (HeadControl && player == null && entity is EntityPlayer)
            {
                player = capi.World.PlayerByUid((entity as EntityPlayer).PlayerUID);
            }

            isSpectator = player != null && player.WorldData.CurrentGameMode == EnumGameMode.Spectator;
            if (isSpectator)
            {
                return;
            }


            curAnimator.FastMode = !DoRenderHeldItem && !capi.Settings.Bool["highQualityAnimations"];

            if (DisplayChatMessages && messageTextures.Count > 0)
            {
                MessageTexture tex = messageTextures.Last();
                if (capi.World.ElapsedMilliseconds > tex.receivedTime + 3500 + 100 * (tex.message.Length - 10))
                {
                    messageTextures.RemoveAt(messageTextures.Count - 1);
                    tex.tex.Dispose();

                    if (messageTextures.Count > 0)
                    {
                        tex = messageTextures[messageTextures.Count - 1];
                        long msvisible = tex.receivedTime + 3500 + 100 * (tex.message.Length - 10) - capi.World.ElapsedMilliseconds;
                        tex.receivedTime += Math.Max(0, 1000 - msvisible);
                    }
                }
            }



            if (HeadControl)
            {
                /*if (player == api.World.Player && api.Render.CameraType == EnumCameraMode.FirstPerson)
                 * {
                 *  AttachmentPointAndPose apap = null;
                 *  curAnimator.AttachmentPointByCode.TryGetValue("Eyes", out apap);
                 *  float[] tmpMat = Mat4f.Create();
                 *
                 *  for (int i = 0; i < 16; i++) tmpMat[i] = ModelMat[i];
                 *  AttachmentPoint ap = apap.AttachPoint;
                 *
                 *  float[] mat = apap.Pose.AnimModelMatrix;
                 *  Mat4f.Mul(tmpMat, tmpMat, mat);
                 *
                 *  Mat4f.Translate(tmpMat, tmpMat, (float)ap.PosX / 16f, (float)ap.PosY / 16f, (float)ap.PosZ / 16f);
                 *  Mat4f.RotateX(tmpMat, tmpMat, (float)(ap.RotationX) * GameMath.DEG2RAD);
                 *  Mat4f.RotateY(tmpMat, tmpMat, (float)(ap.RotationY) * GameMath.DEG2RAD);
                 *  Mat4f.RotateZ(tmpMat, tmpMat, (float)(ap.RotationZ) * GameMath.DEG2RAD);
                 *  float[] vec = new float[] { 0,0,0, 0 };
                 *  float[] outvec = Mat4f.MulWithVec4(tmpMat, vec);
                 *
                 *  api.Render.CameraOffset.Translation.Set(outvec[0], outvec[1] + 1, outvec[2]);
                 * }*/


                float diff = GameMath.AngleRadDistance(bodyYaw, entity.Pos.Yaw);

                if (Math.Abs(diff) > GameMath.PIHALF * 1.2f)
                {
                    opposite = true;
                }
                if (opposite)
                {
                    if (Math.Abs(diff) < GameMath.PIHALF * 0.9f)
                    {
                        opposite = false;
                    }
                    else
                    {
                        diff = 0;
                    }
                }

                headYaw += (diff - headYaw) * dt * 6;
                headYaw  = GameMath.Clamp(headYaw, -0.75f, 0.75f);

                curAnimator.HeadYaw   = headYaw;
                curAnimator.HeadPitch = GameMath.Clamp((entity.Pos.Pitch - GameMath.PI) * 0.75f, -1.2f, 1.2f);


                if (capi.World.Player.CameraMode == EnumCameraMode.Overhead || capi.World.Player.Entity.MountedOn != null)
                {
                    bodyYaw = entity.Pos.Yaw;
                }
                else
                {
                    float yawDist = GameMath.AngleRadDistance(bodyYaw, entity.Pos.Yaw);
                    if (Math.Abs(yawDist) > 1f - (capi.World.Player.Entity.Controls.TriesToMove ? 0.99f : 0) || rotateTpYawNow)
                    {
                        bodyYaw       += GameMath.Clamp(yawDist, -dt * 3, dt * 3);
                        rotateTpYawNow = Math.Abs(yawDist) > 0.01f;
                    }
                }
            }
            else
            {
                curAnimator.HeadYaw   = entity.Pos.Yaw;
                curAnimator.HeadPitch = entity.Pos.Pitch;
            }

            curAnimator.OnFrame(dt);
        }
        public Histogram BuildWithFixedBinSize(IEnumerable<double> values, double binSize)
        {
            const double eps = 1e-9;
            const double margin = 0.1;
            const double adaptiveFactor = 0.02;

            if (binSize < eps)
                throw new ArgumentException($"binSize ({binSize.ToStr()}) should be a positive number", nameof(binSize));
            if (binSize < Resolution)
                binSize = Resolution;
            binSize = NiceCeiling(binSize);
            
            var list = values.ToList();
            if (list.IsEmpty())
                throw new ArgumentException("Values should be non-empty", nameof(values));

            list.Sort();
            if (list.Last() - list.First() < binSize)
            {
                double center = (list.First() + list.Last()) / 2;
                double lower = center - binSize / 2;
                double upper = center + binSize / 2;
                return new Histogram(binSize, new[] { new HistogramBin(lower, upper, list.ToArray()) });
            }

            var points = new List<double> { NiceFloor(list.Min() - binSize / 2), NiceCeiling(list.Max() + binSize / 2) };
            int processedPointCount = 0;
            while (true)
            {
                if (points.Count > 10 * list.Count)
                {
                    var errorMessage = new StringBuilder();
                    errorMessage.AppendLine("Failed to run AdaptiveHistogramBuilder.BuildWithFixedBinSize");
                    errorMessage.AppendLine("BinSize: " + binSize.ToStr("N12"));
                    errorMessage.AppendLine("Values: ");
                    foreach (double value in list)
                        errorMessage.AppendLine("  " + value.ToStr("N12"));
                    throw new InvalidOperationException(errorMessage.ToString());
                }

                int pointIndex = -1;
                for (int i = processedPointCount; i < points.Count - 1; i++)
                {
                    double adaptiveBinSize = (points[i] + points[i + 1]) / 2.0 * adaptiveFactor;
                    double maxSize = Math.Max(binSize * (1.0 + 2 * margin), adaptiveBinSize);
                    if (points[i + 1] - points[i] > maxSize)
                    {
                        pointIndex = i;
                        break;
                    }
                }

                if (pointIndex == -1)
                    break;

                double lower = points[pointIndex];
                double upper = points[pointIndex + 1];

                int bestIndex1 = -1;
                int bestIndex2 = -1;
                int bestCount = -1;
                double bestDist = double.MaxValue;

                bool Inside(double x) => x > lower - eps && x < upper - eps;

                for (int i = 0; i < list.Count; i++)
                    if (Inside(list[i]))
                    {
                        int j = i;
                        while (j < list.Count && Inside(list[j]) && list[j] - list[i] < binSize)
                            j++;
                        int count = j - i;
                        double dist = list[j - 1] - list[i];
                        if (count > bestCount || count == bestCount && dist < bestDist)
                        {
                            bestCount = count;
                            bestIndex1 = i;
                            bestIndex2 = j - 1;
                            bestDist = dist;
                        }
                    }

                if (bestIndex1 != -1)
                {
                    double center = (list[bestIndex1] + list[bestIndex2]) / 2.0;
                    double adaptiveBinSize = Math.Max(binSize, center * adaptiveFactor);
                    double left = NiceFloor(center - adaptiveBinSize / 2);
                    double right = NiceFloor(Math.Min(center + adaptiveBinSize / 2, upper));

                    if (left > lower + binSize * margin)
                        points.Insert(pointIndex + 1, left);
                    else if (right < upper - binSize * margin && right > lower + binSize * margin)
                    {
                        points.Insert(pointIndex + 1, right);
                        processedPointCount++;
                    }
                    else
                        processedPointCount++;
                }
                else
                {
                    points.Insert(pointIndex + 1, NiceFloor(lower + binSize));
                    processedPointCount++;
                }
            }

            var bins = new List<HistogramBin>(points.Count - 1);
            int counter = 0;
            for (int i = 0; i < points.Count - 1; i++)
            {
                var bin = new List<double>();
                double lower = points[i];
                double upper = points[i + 1];

                while (counter < list.Count && (list[counter] < upper || i == points.Count - 1))
                    bin.Add(list[counter++]);

                bins.Add(new HistogramBin(lower, upper, bin.ToArray()));
            }

            // Trim
            while (bins.Any() && bins.First().IsEmpty)
                bins.RemoveAt(0);
            while (bins.Any() && bins.Last().IsEmpty)
                bins.RemoveAt(bins.Count - 1);

            // Join small bins to neighbors
            counter = 0;
            double lastValue = 0;
            while (counter < bins.Count)
            {
                if (bins[counter].HasAny)
                    lastValue = Math.Max(lastValue, bins[counter].Values.Last());
                double adaptiveThreshold = Math.Max(binSize / 2, lastValue * adaptiveFactor);
                if (bins[counter].Gap < adaptiveThreshold)
                {
                    double leftGap = counter > 0 ? bins[counter - 1].Gap : double.MaxValue;
                    double rightGap = counter < bins.Count - 1 ? bins[counter + 1].Gap : double.MaxValue;
                    if (leftGap < rightGap && counter > 0)
                    {
                        bins[counter - 1] = HistogramBin.Union(bins[counter - 1], bins[counter]);
                        bins.RemoveAt(counter);
                    }
                    else if (counter < bins.Count - 1)
                    {
                        bins[counter] = HistogramBin.Union(bins[counter], bins[counter + 1]);
                        bins.RemoveAt(counter + 1);
                    }
                    else
                        counter++;
                }
                else
                    counter++;
            }

            return new Histogram(binSize, bins.ToArray());
        }
Example #59
0
 /// <summary>
 /// returns the card object for the top card on the stack
 /// </summary>
 /// <returns>the top card on the pile</returns>
 public Card topCard()
 {
     cards = cards.OrderBy(z => z.ZIndex).ToList();
     return(cards?.Last());
 }
        async Task PerformSearch(CancellationToken token)
        {
            Searching = true;
            await Invoke(StateHasChanged);

            await Task.Delay(1);

            var options = GitterApi.GetNewOptions();

            options.Query = SearchText;
            options.Limit = 100;
            SearchResult  = new List <IChatMessage>();
            var messages = await GitterApi.SearchChatMessages(ChatRoom.Id, options);

            while ((messages?.Any() ?? false) && !token.IsCancellationRequested)
            {
                SearchResult?.AddRange(messages.OrderBy(m => m.Sent).Reverse());
                Console.WriteLine($"Got {messages.Count()} results. First is {SearchResult?.First().Id} Last is {SearchResult?.Last().Id} Token is {token.IsCancellationRequested}");
                await Invoke(StateHasChanged);

                await Task.Delay(1000);

                options.Skip += messages.Count();
                messages      = await GitterApi.SearchChatMessages(ChatRoom.Id, options);
            }

            Searching = false;
            await Invoke(StateHasChanged);

            await Task.Delay(1);
        }