示例#1
0
 private void AIMLTopicsNeuAnzeigen()
 {
   if (this._wirdGeradeNeuGezeichnet)
     return;
   this._wirdGeradeNeuGezeichnet = true;
   AIMLDatei aimlDatei = this.AimlDatei;
   if (aimlDatei == null)
   {
     this.Enabled = false;
     this.listThemen.Items.Clear();
   }
   else
   {
     IOrderedEnumerable<AIMLTopic> source = aimlDatei.getTopics().OrderBy<AIMLTopic, string>((Func<AIMLTopic, string>) (t => t.Name));
     while (this.listThemen.Items.Count < source.Count<AIMLTopic>())
       this.listThemen.Items.Add(new ListViewItem());
     int index = 0;
     foreach (AIMLTopic aimlTopic in (IEnumerable<AIMLTopic>) source)
     {
       ListViewItem listViewItem = this.listThemen.Items[index];
       listViewItem.Tag = (object) aimlTopic;
       this.ListenEintragBeschriften(listViewItem);
       ++index;
     }
     for (int count = this.listThemen.Items.Count; count > source.Count<AIMLTopic>(); count = this.listThemen.Items.Count)
       this.listThemen.Items.Remove(this.listThemen.Items[count - 1]);
     this.Enabled = true;
   }
   this.ToolStripButtonsAnzeigen();
   this._wirdGeradeNeuGezeichnet = false;
 }
        //=================================
        /// <summary>
        ///
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="returnTotalRecord"></param>
        /// <returns></returns>
        public static ListResult <T> GetDataPage(IOrderedEnumerable <T> query, int?pageNumber, int?pageSize, bool returnTotalRecord = true)
        {
            if (query == null)
            {
                return(null);
            }
            var result = new ListResult <T>();

            if (pageNumber != null && pageSize != null &&
                pageNumber > 0 && pageSize > 0)
            {
                if (returnTotalRecord)
                {
                    result.TotalRecord = query.Count();
                }
                result.ListOfObjects = query.Skip((int)pageSize * ((int)pageNumber - 1)).Take((int)pageSize).ToList();
            }
            else
            {
                if (returnTotalRecord)
                {
                    result.TotalRecord = query.Count();
                }
                result.ListOfObjects = query.ToList();
            }
            return(result);
        }
示例#3
0
文件: Engine.cs 项目: Aknilam/1357
        public static List <GroupedItems <T> > CalcPossibilities(List <T> ils)
        {
            List <GroupedItems <T> > possibilities = new List <GroupedItems <T> >();

            foreach (var groupedByRow in ils.GroupBy(il => il.Row))
            {
                int row = groupedByRow.Key;
                IOrderedEnumerable <T> ilsInRow = groupedByRow.OrderBy(il => il.Col);
                if (ilsInRow.Count() > 1)
                {
                    List <T> linesToNextAdd = new List <T> {
                        ilsInRow.First()
                    };
                    for (int i = 1; i < ilsInRow.Count(); i++)
                    {
                        if (ilsInRow.ElementAt(i).Col - ilsInRow.ElementAt(i - 1).Col != 1)
                        {
                            AddPossibility(possibilities, linesToNextAdd);
                            linesToNextAdd = new List <T>();
                        }

                        linesToNextAdd.Add(ilsInRow.ElementAt(i));
                    }
                    AddPossibility(possibilities, linesToNextAdd);
                }
                else if (ilsInRow.Any())
                {
                    AddPossibility(possibilities, new List <T> {
                        ilsInRow.First()
                    });
                }
            }
            return(possibilities);
        }
示例#4
0
        void CastR(int minhit = 1)
        {
            UltMode ultmode = GetUltMode();

            IOrderedEnumerable <AIHeroClient> ordered = null;


            if (ultmode == UltMode.Health)
            {
                ordered = KnockedUp.OrderBy(x => x.Health).ThenByDescending(x => TargetSelector.GetPriority(x)).ThenByDescending(x => x.CountEnemiesInRange(350));
            }

            if (ultmode == UltMode.Priority)
            {
                ordered = KnockedUp.OrderByDescending(x => TargetSelector.GetPriority(x)).ThenBy(x => x.Health).ThenByDescending(x => x.CountEnemiesInRange(350));
            }

            if (ultmode == UltMode.EnemiesHit)
            {
                ordered = KnockedUp.OrderByDescending(x => x.CountEnemiesInRange(350)).ThenByDescending(x => TargetSelector.GetPriority(x)).ThenBy(x => x.Health);
            }

            if (GetBool("Combo.UltOnlyKillable", YasuoMenu.ComboM))
            {
                var killable = ordered.FirstOrDefault(x => !x.isBlackListed() && x.Health <= Yasuo.GetSpellDamage(x, SpellSlot.R) && x.HealthPercent >= GetSliderInt("Combo.MinHealthUlt", YasuoMenu.ComboM) && (GetBool("Combo.UltTower", YasuoMenu.ComboM) || GetKeyBind("Misc.TowerDive", YasuoMenu.MiscM) || ShouldDive(x)));
                if (killable != null && (!killable.IsInRange(Spells[Q].Range) || !isHealthy))
                {
                    Spells[R].CastOnUnit(killable);
                    return;
                }
                return;
            }

            if ((GetBool("Combo.OnlyifMin", YasuoMenu.ComboM) && ordered.Count() < minhit) || (ordered.Count() == 1 && ordered.FirstOrDefault().HealthPercent < GetSliderInt("Combo.MinHealthUlt", YasuoMenu.ComboM)))
            {
                return;
            }

            if (GetBool("Combo.RPriority", YasuoMenu.ComboM))
            {
                var best = ordered.Find(x => !x.isBlackListed() && TargetSelector.GetPriority(x).Equals(2.5f) && (GetBool("Combo.UltTower", YasuoMenu.ComboM) || GetKeyBind("Misc.TowerDive", YasuoMenu.MiscM) || !x.Position.LSTo2D().PointUnderEnemyTurret()));
                if (best != null && Yasuo.HealthPercent / best.HealthPercent <= 1)
                {
                    Spells[R].CastOnUnit(best);
                    return;
                }
            }

            if (ordered.Count() >= minhit)
            {
                var best2 = ordered.FirstOrDefault(x => !x.isBlackListed() && (GetBool("Combo.UltTower", YasuoMenu.ComboM) || ShouldDive(x)));
                if (best2 != null)
                {
                    Spells[R].CastOnUnit(best2);
                }
                return;
            }
        }
        public override void Execute(string arguments)
        {
            PhotonPlayer player = PLNetworkManager.Instance.LocalPlayer.GetPhotonPlayer();
            int          page   = 1;

            if (!string.IsNullOrWhiteSpace(arguments))
            {
                if (!int.TryParse(arguments, out page))
                {
                    if (arguments[0] == '/')
                    {
                        arguments = arguments.Substring(1);
                    }
                    Tuple <ChatCommand, PulsarMod> t = ChatCommandRouter.Instance.GetCommand(arguments);
                    if (t != null)
                    {
                        ChatCommand cmd  = t.Item1;
                        string      name = t.Item2 != null ? t.Item2.Name : "Pulsar Mod Loader";

                        Messaging.Echo(player, $"[&%~[C0 /{cmd.CommandAliases()[0]} ]&%~] - {cmd.Description()} <color=#ff6600ff>[{name}]</color>");
                        Messaging.Echo(player, $"Aliases: /{string.Join($", /", cmd.CommandAliases())}");
                        Messaging.Echo(player, $"Usage: {cmd.UsageExamples()[0]}");
                        for (int i = 1; i < cmd.UsageExamples().Length; i++)
                        {
                            Messaging.Echo(player, $"       {cmd.UsageExamples()[i]}");
                        }
                    }
                    else
                    {
                        Messaging.Echo(player, $"Command /{arguments} not found");
                    }
                    return;
                }
            }

            int commandsPerPage = (PLXMLOptionsIO.Instance.CurrentOptions.GetStringValueAsInt("ChatNumLines") * 5 + 10) - 2;
            IOrderedEnumerable <Tuple <ChatCommand, PulsarMod> > commands = ChatCommandRouter.Instance.GetCommands();
            int pages = Mathf.CeilToInt(commands.Count() / (float)commandsPerPage);

            page--; //Pages start from 1
            if (page < 0)
            {
                page = 0;
            }

            Messaging.Echo(player, pages == 1 && page == 0 ? "[&%~[C0 Command List: ]&%~] :" : $"[&%~[C0 Command List: ]&%~] Page {page + 1} : {pages}");
            for (int i = 0; i < commandsPerPage; i++)
            {
                int index = i + page * commandsPerPage;
                if (i + page * commandsPerPage >= commands.Count())
                {
                    break;
                }
                ChatCommand command = commands.ElementAt(index).Item1;
                Messaging.Echo(player, $"/{command.CommandAliases()[0]} - {command.Description()}");
            }
            Messaging.Echo(player, "Use [&%~[C2 /help <command> ]&%~] for details about a specific command");
        }
示例#6
0
        public LastName GetFamilyAtRanking(int i)
        {
            if (_ranking.Count() > i)
            {
                return(_ranking.ElementAt(i).Key);
            }

            return(0);
        }
示例#7
0
 public void HeadToEscapePoint()
 {
     SortEscapePoints();
     //int rand = Random.Range(0, escapePoints.Capacity);
     if (escapePointsByDistance.Count() > 1)
     {
         currTarget = escapePointsByDistance.ElementAt(0);
         PathRequestManager.RequestPath(transform.position, currTarget.position, OnPathFound2);
     }
 }
示例#8
0
        public void NextItem()
        {
            SetCurrentItemFocus(false);

            ++_index;
            if (_index >= _rows.Count())
            {
                _index = 0;
            }

            SetCurrentItemFocus(true);
        }
示例#9
0
        private static double GetQuartile(IOrderedEnumerable <double> list, double quartile)
        {
            double result;

            // Get roughly the index
            double index = quartile * (list.Count() + 1);

            // Get the remainder of that index value if exists
            double remainder = index % 1;

            // Get the integer value of that index
            index = Math.Floor(index) - 1;

            if (remainder.Equals(0))
            {
                // we have an integer value, no interpolation needed
                result = list.ElementAt((int)index);
            }
            else
            {
                // we need to interpolate
                double value = list.ElementAt((int)index);
                double interpolationValue = value
                                            .Interpolate(list.ElementAt((int)(index + 1)), remainder);

                result = value + interpolationValue;
            }

            return(result);
        }
示例#10
0
        void getBasEquipments(Document doc)
        {
            FilteredElementCollector systems
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(MEPSystem));
            IOrderedEnumerable <MEPSystem> systemsSorted = from MEPSystem s in systems orderby Int32.Parse(s.Name) ascending select s;

            int i = 0;

            if (systemsSorted.Count() == 0)
            {
                throw new Exception("Не обнаружены системы в Revit-модели.");
            }
            foreach (MEPSystem system in systemsSorted)
            {
                string sysId = system.BaseEquipment.Id.ToString();

                if (!this.ARKBLocks.Any(element => element.id == sysId))
                {
                    ARKModule m = new ARKModule(sysId, i, system.BaseEquipment);
                    m.mark = GetMark(system.BaseEquipment);
                    ARKBLocks.Add(m);
                }
                findAndAddSystem(system);
            }
        }
示例#11
0
        /// <summary>
        /// Prints test results in AppVeyor
        /// </summary>
        /// <param name="measuresToPrint">Average load times for particular scenarios and browsers</param>
        public static void PrintResultsInAppVeyor(IOrderedEnumerable <string> measuresToPrint)
        {
            // Use ProcessStartInfo class
            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.CreateNoWindow  = false;
            startInfo.UseShellExecute = false;
            startInfo.FileName        = "appveyor";
            startInfo.WindowStyle     = ProcessWindowStyle.Hidden;
            for (int i = 0; i < measuresToPrint.Count(); i++)
            {
                startInfo.Arguments = "AddTest " + measuresToPrint.ElementAt(i);

                // Start the process with the info we specified.
                // Call WaitForExit and then the using statement will close.
                try
                {
                    using (Process exeProcess = Process.Start(startInfo))
                    {
                        if (exeProcess != null)
                        {
                            exeProcess.WaitForExit();
                        }
                    }
                }
                catch (Win32Exception)
                {
                    Logger.Info("AppVeyor app not found");
                    break;
                }
            }
        }
示例#12
0
        /// <summary>
        /// 从集合中随机抽出定量元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static IList <T> RandomSelect <T>(this IOrderedEnumerable <T> source, int count)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (count <= 0)
            {
                throw new ArgumentException("The value of parameter “count” must greater than 0!");
            }
            int totalCount = source.Count();

            if (totalCount > count)
            {
                Random      r       = new Random();
                IList <int> skips   = new List <int>(count);
                IList <T>   results = new List <T>(count);
                for (int i = 0; i < count; i++)
                {
                    int skip = r.Next(totalCount);
                    while (skips.Contains(skip))
                    {
                        skip = r.Next(totalCount);
                    }
                    results.Add(source.Skip(skip).FirstOrDefault());
                }
                return(results);
            }
            else
            {
                return(source.Take(count).ToList());
            }
        }
示例#13
0
        public void CanFilterCommurators()
        {
            //Arrange
            Mock <IDBRepository> mock = new Mock <IDBRepository>();

            mock.Setup(h => h.switches).Returns(new _switch[] {
                new _switch {
                    Name = "S1", status = new status[] { new status {
                                                             action = "+1"
                                                         } }
                },
                new _switch {
                    Name = "S2", status = new status[] { new status {
                                                             action = "-1"
                                                         } }
                },
            });

            HomeController controller = new HomeController(mock.Object);

            //Act
            IOrderedEnumerable <status> result = (IOrderedEnumerable <status>)controller.Index("S1").Model;

            // Assert
            Assert.AreEqual(result.Count(), 1);
            Assert.IsTrue(result.First().action == "+1");
        }
示例#14
0
        /// <summary>
        /// Return a list of latest dates in sequence with the desired value.
        /// </summary>
        /// <param name="ordered">Ordered data model</param>
        /// <param name="currDate">Lookup Date</param>
        /// <param name="valueToFind">Value to find</param>
        /// <returns></returns>
        public static IEnumerable <DateTime> FindLatestValue(this IOrderedEnumerable <DataModel> ordered, DateTime lookupDate, double valueToFind)
        {
            if (ordered.Count(x => x.MarketPriceEX1 == valueToFind) == 1)
            {
                var index = ordered.ToList().FindIndex(x => x.MarketPriceEX1 == valueToFind);
                yield return(ordered.ElementAt(index).Date);

                yield break;
            }

            var indices = ordered
                          .Select((data, index) => new { data, index })
                          .Where(x => x.data.MarketPriceEX1 == valueToFind && x.data.Date.Date == lookupDate.Date)
                          .Select(x => x.index)
                          .ToList();

            var result = indices.GroupWhile((x, y) => y - x == 1)
                         .Select(x => new { Count = x.Count(), Elements = x })
                         .ToList();

            var biggestSuccession = result.Last(x => x.Elements.Count() == result.Max(y => y.Count)).Elements;

            foreach (var index in biggestSuccession)
            {
                yield return(ordered.ElementAt(index).Date);
            }
        }
示例#15
0
        private async Task ProcessList()
        {
            try
            {
                IMessageChannel channel = await ChannelProvider.GetDMChannelAsync(this.Context);

                List <TReminder> reminders = this._reminderDAO.GetAll(this.Context.User.Id);
                IOrderedEnumerable <TReminder> orderedList = reminders.OrderBy(x => x.ExpirationTime);

                FormattedEmbedBuilder message = new FormattedEmbedBuilder()
                                                .AppendTitle($"{XayahReaction.Hourglass} Active reminders");
                if (orderedList.Count() > 0)
                {
                    foreach (TReminder entry in orderedList)
                    {
                        message.AddField($"Expires: {entry.ExpirationTime} UTC", entry.Message, inline: false);
                    }
                }
                else
                {
                    message.AppendDescription("imagine a soulrending void", AppendOption.Italic);
                }
                await channel.SendEmbedAsync(message);

                await this.Context.Message.AddReactionIfNotDMAsync(this.Context, XayahReaction.Envelope);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        public List <int> LinqMethodQueryIntro()
        {
            //A LINQ query has 3 parts

            //1. The first part is obtaining the data, in this case, a simple integer array
            int[] numArray = new int[10] {
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9
            };

            //2. The second part is the query execution. The query in created but not executed at this stage because of "deferred execution".
            // "deferred execution", aslo known as "lazy loading", means the the query in not executed until the query result is actually used
            IOrderedEnumerable <int> query = numArray.Where(x => x % 3 == 0)
                                             .OrderByDescending(x => x);

            //3. Execution. The query is executed when the data from the query is requested, for example in a foreach loop
            foreach (var x in query)
            {
                Console.Write("{0} ", x);
            }

            //Other ways to force the execution of the query are
            int size = query.Count();

            //or

            List <int> list = query.ToList();

            return(list);
        }
示例#17
0
        private async Task CmdListModsAsync(SocketCommandContext context, CancellationToken cancellationToken = default)
        {
            using IDisposable logScope = _log.BeginCommandScope(context, this);
            IOrderedEnumerable <StellarisMod> mods = (await _stellarisModsStore.GetAllAsync(cancellationToken).ConfigureAwait(false)).OrderBy(m => m.Name);

            if (!mods.Any())
            {
                await context.ReplyAsync($"{_einherjiOptions.FailureSymbol} You did not have any mod on the list.", cancellationToken).ConfigureAwait(false);

                return;
            }

            List <string> listStrings = new List <string>(mods.Count());

            foreach (StellarisMod mod in mods)
            {
                listStrings.Add(ModToListString(mod, listStrings.Count + 1));
            }
            EmbedBuilder embed = new EmbedBuilder()
                                 .WithDescription(string.Join('\n', listStrings))
                                 .WithFooter($"Currently you guys are using {listStrings.Count} mods.", context.Client.CurrentUser.GetAvatarUrl())
                                 .WithTimestamp(DateTimeOffset.Now)
                                 .WithAuthor("Your Stellaris mods", context.Client.CurrentUser.GetAvatarUrl());

            await context.ReplyAsync(null, false, embed.Build(), cancellationToken).ConfigureAwait(false);
        }
示例#18
0
        /// <summary>
        /// Gets list of files in the playback folder and create a worker task to parse the file.
        /// </summary>
        private void QueueFilesForThreads()
        {
            DirectoryInfo dir = new DirectoryInfo(_playbackFolder);
            IOrderedEnumerable <FileInfo> files = dir.GetFiles(_extension).OrderBy(
                f => TryGetFileIDLength(f)
                );

            // This may need to be updated if there are invalid frames found, if checking # frames read as the stopping condition.
            lock (_totalFrameLock)
            {
                try
                {
                    _totalFrames = files.Count();
                }
                catch (Exception e)
                {
                    Debug.LogError("A filename could not be parsed as a frame ID (int): " + e.Message);
                }
            }
            Debug.Log(_extension + " files to process in thread: " + _totalFrames);
            int frameId = 0;

            foreach (FileInfo f in files)
            {
                ThreadPool.QueueUserWorkItem(ThreadPoolCallback, new ParseTaskInfo(f, frameId++));
            }
        }
示例#19
0
        public static void GenerateGodIconSprites(IOrderedEnumerable <FileInfo> files, string targetFilePathNoExtension)
        {
            var spriteBase = targetFilePathNoExtension;

            Console.WriteLine($"Generating sprite for {files.Count()} files of square size {squareItemSize}...");
            using var bitmap = SpriteGenerator.GenerateForBitmaps(files, squareItemSize);
            bitmap.Save(spriteBase + ".png", ImageFormat.Png);
            bitmap.Save(spriteBase + ".jpg", ImageFormat.Jpeg);

            Console.WriteLine("Writing sprite data files...");
            File.WriteAllText(spriteBase + ".spriteorder", string.Join("\n", files.Select(x => x.Name)) + "\n");
            File.WriteAllText(spriteBase + ".json", @"{""images"":[{" + string.Join("},{", files.Select((x, i) => $@"""name"":""{x.Name}"",""x"":{i * squareItemSize}")) + "}]}");

            Console.WriteLine("Converting sprites to additional image formats...");
            var pWebp = Process.Start("ffmpeg.exe", $@"-hide_banner -y -i ""{spriteBase}.png"" ""{spriteBase}.webp""");

            pWebp.WaitForExit();
            if (pWebp.ExitCode != 0)
            {
                Console.WriteLine($"ERROR: Sprite webp conversion with ffmpeg.exe failed with exit code {pWebp.ExitCode}");
            }

            var pAvif = Process.Start("avifenc.exe", $@"""{spriteBase}.png"" ""{spriteBase}.avif""");

            pAvif.WaitForExit();
            if (pAvif.ExitCode != 0)
            {
                Console.WriteLine($"ERROR: Sprite avif conversion with avifenc.exe failed with exit code {pAvif.ExitCode}");
            }
        }
示例#20
0
        public void SearchForValuesInMultipleThreads(int typeSize, byte[] valueToFind)
        {
            threadList   = new List <Thread>();
            memoryMemory = new List <IntPtr>();

            int threadCount = Environment.ProcessorCount;

            //int threadCount = sortedRegions.Count();
            Dictionary <IntPtr, int>[] splittedRegionBeginning = new Dictionary <IntPtr, int> [threadCount];

            for (int i = 0; i < splittedRegionBeginning.Count(); i++)
            {
                splittedRegionBeginning[i] = new Dictionary <IntPtr, int>();
            }

            for (int i = 0; i < sortedRegions.Count(); i++)
            {
                splittedRegionBeginning[i % threadCount].Add(sortedRegions.ElementAt(i).Key, sortedRegions.ElementAt(i).Value);
            }

            foreach (Dictionary <IntPtr, int> dict in splittedRegionBeginning)
            {
                Thread arsch = new Thread(() => TestMethod2(typeSize, valueToFind, dict));
                arsch.Start();
                threadList.Add(arsch);
            }

            foreach (Thread thread in threadList)
            {
                thread.Join();
            }
        }
示例#21
0
 void AdjustSort(ListTaskItem listItem, int oldOrderIndex, IOrderedEnumerable <ListTaskItem> sortedTasks)
 {
     if (oldOrderIndex != listItem.Sort)
     {
         if (oldOrderIndex < listItem.Sort)
         {
             for (var i = oldOrderIndex; i < listItem.Sort; i++)
             {
                 if (sortedTasks.ElementAt(i).Sort > 0)
                 {
                     sortedTasks.ElementAt(i).Sort--;
                 }
             }
         }
         else if (oldOrderIndex > listItem.Sort)
         {
             for (var i = listItem.Sort; i < oldOrderIndex; i++)
             {
                 if (sortedTasks.ElementAt(i).Sort < sortedTasks.Count())
                 {
                     sortedTasks.ElementAt(i).Sort++;
                 }
             }
         }
     }
 }
示例#22
0
        public static PaginatedList <T> CreatePage(IOrderedEnumerable <T> source, int pageIndex, int pageSize)
        {
            var count = source.Count();
            var items = source.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return(new PaginatedList <T>(items, count, pageIndex, pageSize));
        }
示例#23
0
        public static JqueryDataTablesResponse ProcessRequest <TEntity>(IEnumerable <TEntity> entities, JqueryDataTableRequest request) where TEntity : JqueryDataTableBaseEntity
        {
            IOrderedEnumerable <TEntity> orderedEntities = null;

            foreach (var order in request.Orders)
            {
                var closure = order;

                if (orderedEntities == null)
                {
                    orderedEntities = order.Ascending ? entities.OrderBy(x => x[closure.Column]) : entities.OrderByDescending(x => x[closure.Column]);
                }
                else
                {
                    orderedEntities = order.Ascending ? orderedEntities.ThenBy(x => x[closure.Column]) : orderedEntities.ThenByDescending(x => x[closure.Column]);
                }
            }

            if (orderedEntities == null)
            {
                orderedEntities = entities.OrderBy(x => x[0]);
            }

            var itemsPaged = orderedEntities.Skip(request.Start).Take(request.Count).ToList();
            var totalCount = orderedEntities.Count();


            return(new JqueryDataTablesResponse(
                       request.Draw,
                       itemsPaged,
                       totalCount,
                       totalCount));
        }
        public async Task <ActionResult <ThreadViewModel[]> > GetForum(int forumId)
        {
            List <ThreadViewModel> forumThreadEntries = new List <ThreadViewModel>();

            Forum currentForum = await _context.Fora.Include(i => i.ForumThreadEntries).ThenInclude(i => i.Author).FirstOrDefaultAsync(cf => cf.Id == forumId);

            // Create the view model
            foreach (ThreadEntry threadEntry in currentForum.ForumThreadEntries)
            {
                ThreadViewModel forumThreadEntryViewModel = new ThreadViewModel();

                forumThreadEntryViewModel.InjectFrom(threadEntry);

                forumThreadEntryViewModel.Author = new ApplicationUserViewModel();
                forumThreadEntryViewModel.Author.InjectFrom(threadEntry);

                forumThreadEntryViewModel.Replies = currentForum.ForumThreadEntries.Where(forumThreadEntry => forumThreadEntry.Root?.Id == threadEntry.Id && forumThreadEntry.Parent != null).Count();
                IOrderedEnumerable <ThreadEntry> interim = currentForum.ForumThreadEntries.Where(m => m.Root?.Id == threadEntry.Id).OrderBy(m => m.UpdatedAt.ToFileTime());
                if (interim.Count() > 0)
                {
                    forumThreadEntryViewModel.LastReply = interim.FirstOrDefault().UpdatedAt.ToString();
                }
                else
                {
                    forumThreadEntryViewModel.LastReply = DateTime.Now.ToString();
                }

                forumThreadEntries.Add(forumThreadEntryViewModel);
            }

            return(forumThreadEntries.ToArray());
        }
示例#25
0
        //phân trang đặc biệt
        public PaginationComic ListPage(Pagination pagination, IOrderedEnumerable <comic> comics)
        {
            int page = pagination.Page;
            int size = pagination.Size;

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

            int skip = (page - 1) * size;

            int sizePage = comics.Count();

            if (sizePage % size > 0)
            {
                sizePage = sizePage / size + 1;
            }
            else
            {
                sizePage = sizePage / size;
            }

            var sql = comics.Skip(skip).Take(size).ToList();

            PaginationComic paginationComic = new PaginationComic(sizePage, page, sql);

            return(paginationComic);
        }
示例#26
0
 protected override void Render(HtmlTextWriter writer)
 {
     if (this.Activity != null)
     {
         IOrderedEnumerable <PrizeRecordInfo> orderedEnumerable =
             from a in VshopBrowser.GetPrizeList(new PrizeQuery
         {
             ActivityId = this.Activity.ActivityId,
             SortOrder  = SortAction.Desc,
             SortBy     = "PrizeTime"
         })
             orderby a.PrizeTime descending
             select a;
         StringBuilder stringBuilder = new StringBuilder();
         if (orderedEnumerable != null && orderedEnumerable.Count <PrizeRecordInfo>() > 0)
         {
             foreach (PrizeRecordInfo current in orderedEnumerable)
             {
                 if (!string.IsNullOrEmpty(current.CellPhone) && !string.IsNullOrEmpty(current.RealName))
                 {
                     stringBuilder.AppendFormat("<p>{0}&nbsp;&nbsp;{1} &nbsp;&nbsp;{2}</p>", current.Prizelevel, this.ShowCellPhone(current.CellPhone), current.RealName);
                 }
             }
             writer.Write(stringBuilder.ToString());
             return;
         }
         stringBuilder.AppendFormat("<p>暂无获奖名单!</p>", new object[0]);
     }
 }
示例#27
0
 private void CheckForEmptyCollection(IOrderedEnumerable <Battlecard> result)
 {
     if (result.Count() == 0)
     {
         throw new InvalidOperationException();
     }
 }
        private double Percentile(IOrderedEnumerable<double> sortedData, double p)
        {
            int count = sortedData.Count();
            if (count == 0) return 0;
            if (count == 1) return sortedData.Last();
            if (p >= 100.0d) return sortedData.Last();

            double position = (count + 1) * p / 100d;
            double leftNumber, rightNumber;

            double n = p / 100d * (count - 1) + 1d;

            if (position >= 1)
            {
                leftNumber = sortedData.ElementAt((int)Math.Floor(n) - 1);
                rightNumber = sortedData.ElementAt((int)Math.Floor(n));
            }
            else
            {
                leftNumber = sortedData.First();
                rightNumber = sortedData.ElementAt(1);
            }

            if (Math.Abs(leftNumber - rightNumber) < Double.Epsilon)
                return leftNumber;
            else
            {
                double part = n - Math.Floor(n);
                return leftNumber + part*(rightNumber - leftNumber);
            }
        }
示例#29
0
 protected override void Render(HtmlTextWriter writer)
 {
     if (this.Activity != null)
     {
         PrizeQuery page = new PrizeQuery {
             ActivityId = this.Activity.ActivityId,
             SortOrder  = SortAction.Desc,
             SortBy     = "PrizeTime"
         };
         IOrderedEnumerable <PrizeRecordInfo> source = from a in VshopBrowser.GetPrizeList(page)
                                                       orderby a.PrizeTime descending
                                                       select a;
         StringBuilder builder = new StringBuilder();
         if ((source != null) && (source.Count <PrizeRecordInfo>() > 0))
         {
             foreach (PrizeRecordInfo info in source)
             {
                 if (!string.IsNullOrEmpty(info.CellPhone) && !string.IsNullOrEmpty(info.RealName))
                 {
                     builder.AppendFormat("<p>{0}&nbsp;&nbsp;{1} &nbsp;&nbsp;{2}</p>", info.Prizelevel, this.ShowCellPhone(info.CellPhone), info.RealName);
                 }
             }
             writer.Write(builder.ToString());
         }
         else
         {
             builder.AppendFormat("<p>暂无获奖名单!</p>", new object[0]);
         }
     }
 }
示例#30
0
        public bool IsCorrectNumber(UInt64 n, IOrderedEnumerable <UInt64> last25)
        {
            int low  = 0;
            int high = last25.Count() - 1;

            while (low != high)
            {
                var sum = last25.ElementAt(low) + last25.ElementAt(high);
                if (sum == n)
                {
                    return(true);
                }

                if (sum > n)
                {
                    --high;
                }
                if (sum < n)
                {
                    ++low;
                }
            }

            return(false);
        }
示例#31
0
        private void ControlEndMove(object sender, EventArgs e)
        {
            int nextTop = 0;
            IOrderedEnumerable <Control> SortedControls = Panel.Controls.OfType <Control>().OrderBy(control => control.Top);

            Panel.SuspendLayout();

            foreach (Control control in SortedControls)
            {
                control.Top = nextTop + control.Margin.Top;
                nextTop     = control.Bottom + control.Margin.Bottom;
            }

            Panel.ResumeLayout();

            if (_prevSortedControls == null || _prevSortedControls.Count() != SortedControls.Count())
            {
                OnListChanged();
                return;
            }

            List <Control> prevSortedControls = _prevSortedControls.ToList();
            List <Control> sortedControls     = SortedControls.ToList();

            for (int i = 0; i < sortedControls.Count; i++)
            {
                if (prevSortedControls[i] == sortedControls[i])
                {
                    OnListChanged();
                    return;
                }
            }
        }
示例#32
0
        private static double GetQuartile(IOrderedEnumerable<double> list, double quartile)
        {
            double result;

            // Get roughly the index
            double index = quartile * (list.Count() + 1);

            // Get the remainder of that index value if exists
            double remainder = index % 1;

            // Get the integer value of that index
            index = Math.Floor(index) - 1;

            if (remainder.Equals(0))
            {
                // we have an integer value, no interpolation needed
                result = list.ElementAt((int)index);
            }
            else
            {
                // we need to interpolate
                double value = list.ElementAt((int)index);
                double interpolationValue = value
                    .Interpolate(list.ElementAt((int)(index + 1)), remainder);

                result = value + interpolationValue;
            }

            return result;
        }
示例#33
0
        private async void Execute()
        {
            EnabledButton(false);
            textBox1.Text = "Reloading Pokemon list.";

            client = new Client(ClientSettings);

            try
            {
                switch (ClientSettings.AuthType)
                {
                    case AuthType.Ptc:
                        await client.DoPtcLogin(ClientSettings.PtcUsername, ClientSettings.PtcPassword);
                        break;
                    case AuthType.Google:
                        await client.DoGoogleLogin();
                        break;
                }

                await client.SetServer();
                profile = await client.GetProfile();
                inventory = await client.GetInventory();
                pokemons =
                    inventory.InventoryDelta.InventoryItems
                    .Select(i => i.InventoryItemData?.Pokemon)
                        .Where(p => p != null && p?.PokemonId > 0)
                        .OrderByDescending(key => key.Cp);
                var families = inventory.InventoryDelta.InventoryItems
                    .Select(i => i.InventoryItemData?.PokemonFamily)
                    .Where(p => p != null && (int)p?.FamilyId > 0)
                    .OrderByDescending(p => (int)p.FamilyId);

                var imageSize = 50;

                var imageList = new ImageList { ImageSize = new Size(imageSize, imageSize) };
                listView1.ShowItemToolTips = true;
                listView1.SmallImageList = imageList;

                var templates = await client.GetItemTemplates();
                var myPokemonSettings = templates.ItemTemplates.Select(i => i.PokemonSettings).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                var pokemonSettings = myPokemonSettings.ToList();

                var myPokemonFamilies = inventory.InventoryDelta.InventoryItems.Select(i => i.InventoryItemData?.PokemonFamily).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                var pokemonFamilies = myPokemonFamilies.ToArray();

                listView1.DoubleBuffered(true);
                listView1.View = View.Details;

                ColumnHeader columnheader;
                columnheader = new ColumnHeader();
                columnheader.Text = "Name";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "CP";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "IV A-D-S";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Candy";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Evolvable?";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Height";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Weight";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Attack";
                listView1.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "SpecialAttack";
                listView1.Columns.Add(columnheader);

                foreach (var pokemon in pokemons)
                {
                    Bitmap pokemonImage = null;
                    await Task.Run(() =>
                    {
                        pokemonImage = GetPokemonImage((int)pokemon.PokemonId);
                    });
                    imageList.Images.Add(pokemon.PokemonId.ToString(), pokemonImage);

                    listView1.LargeImageList = imageList;
                    var listViewItem = new ListViewItem();
                    listViewItem.Tag = pokemon;



                    var currentCandy = families
                        .Where(i => (int)i.FamilyId <= (int)pokemon.PokemonId)
                        .Select(f => f.Candy)
                        .First();
                    var currIv = Math.Round(Perfect(pokemon));
                    listViewItem.SubItems.Add(string.Format("{0}", pokemon.Cp));
                    listViewItem.SubItems.Add(string.Format("{0}% {1}-{2}-{3}", currIv, pokemon.IndividualAttack, pokemon.IndividualDefense, pokemon.IndividualStamina));
                    listViewItem.SubItems.Add(string.Format("{0}", currentCandy));
                    listViewItem.ImageKey = pokemon.PokemonId.ToString();

                    var pokemonId2 = pokemon.PokemonId;
                    var pokemonName = pokemon.Id;

                    listViewItem.Text = string.Format("{0}", pokemon.PokemonId);
                    listViewItem.ToolTipText = "Favorite: " + pokemon.Favorite + "\nNickname: " + pokemon.Nickname;

                    var settings = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                    var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                    if (settings.EvolutionIds.Count > 0 && familyCandy.Candy > settings.CandyToEvolve)
                    {
                        listViewItem.SubItems.Add("Y ("+ settings.CandyToEvolve+")");
                        listViewItem.Checked = true;
                    }
                    else
                    {
                        if (settings.EvolutionIds.Count > 0)
                            listViewItem.SubItems.Add("N (" + familyCandy.Candy + "/" + settings.CandyToEvolve + ")");
                        else
                            listViewItem.SubItems.Add("N (Max)");
                    }
                    listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.HeightM, 2)));
                    listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.WeightKg,2)));
                    listViewItem.SubItems.Add(string.Format("{0}", pokemon.Move1));
                    listViewItem.SubItems.Add(string.Format("{0}", pokemon.Move2));

                    listView1.Items.Add(listViewItem);
                }
                listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                Text = "Pokemon List | User: "******" | Pokemons: " + pokemons.Count() + "/" + profile.Profile.PokeStorage;
                EnabledButton(true);

                textBox1.Text = string.Empty;
            }
            catch (TaskCanceledException e)
            {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (UriFormatException e)
            {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (ArgumentOutOfRangeException e)
            {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (ArgumentNullException e)
            {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (NullReferenceException e)
            {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (Exception e)
            {
                textBox1.Text = e.Message;
                Execute();
            }
        }
示例#34
0
 private Task InvokeRecursive(int index, IOrderedEnumerable<IMOwinFilter> filters, IIMOwinOptions options, OperationContext context)
 {
     index += 1;
     return filters.Count() != index ? filters.Skip(index).First().Invoke(context, () => InvokeRecursive(index, filters, options, context)) : ExecuteOperation(options, context);
 }
 private void AddCorners(IOrderedEnumerable<Pixel> cornerCandidates)
 {
     if (cornerCandidates.Count() > 50)
     {
         //First and Last point are corners
         MassureAngleAndAddCorner(cornerCandidates.First());
         MassureAngleAndAddCorner(cornerCandidates.Last());
     }
     else
     {
         // middle point is corner
         int index = cornerCandidates.Count() / 2;
         MassureAngleAndAddCorner(cornerCandidates.ElementAt(index));
     }
 }
示例#36
0
        private async void Execute()
        {
            EnabledButton(false);
            textBox1.Text = "Reloading Pokemon list.";

            client = new Client(ClientSettings);

            try
            {
                switch (ClientSettings.AuthType)
                {
                    case AuthType.Ptc:
                        await client.DoPtcLogin(ClientSettings.PtcUsername, ClientSettings.PtcPassword);
                        break;
                    case AuthType.Google:
                        await client.DoGoogleLogin();
                        break;
                }

                await client.SetServer();
                profile = await client.GetProfile();
                inventory = await client.GetInventory();
                pokemons =
                    inventory.InventoryDelta.InventoryItems
                    .Select(i => i.InventoryItemData?.Pokemon)
                        .Where(p => p != null && p?.PokemonId > 0)
                        .OrderByDescending(key => key.Cp);
                var families = inventory.InventoryDelta.InventoryItems
                    .Select(i => i.InventoryItemData?.PokemonFamily)
                    .Where(p => p != null && (int)p?.FamilyId > 0)
                    .OrderByDescending(p => (int)p.FamilyId);

                var imageSize = 50;

                var imageList = new ImageList { ImageSize = new Size(imageSize, imageSize) };
                listView1.ShowItemToolTips = true;

                var templates = await client.GetItemTemplates();
                var myPokemonSettings =  templates.ItemTemplates.Select(i => i.PokemonSettings).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                var pokemonSettings = myPokemonSettings.ToList();

                var myPokemonFamilies = inventory.InventoryDelta.InventoryItems.Select(i => i.InventoryItemData?.PokemonFamily).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                var pokemonFamilies = myPokemonFamilies.ToArray();

                listView1.DoubleBuffered(true);
                foreach (var pokemon in pokemons)
                {
                    Bitmap pokemonImage = null;
                    await Task.Run(() =>
                    {
                        pokemonImage = GetPokemonImage((int)pokemon.PokemonId);
                    });
                    imageList.Images.Add(pokemon.PokemonId.ToString(), pokemonImage);

                    listView1.LargeImageList = imageList;
                    var listViewItem = new ListViewItem();
                    listViewItem.Tag = pokemon;


                    var currentCandy = families
                        .Where(i => (int)i.FamilyId <= (int)pokemon.PokemonId)
                        .Select(f => f.Candy)
                        .First();
                    var currIv = Math.Round(Perfect(pokemon));
                    //listViewItem.SubItems.Add();
                    listViewItem.ImageKey = pokemon.PokemonId.ToString();

                    var pokemonId2 = pokemon.PokemonId;
                    var pokemonName = pokemon.Id;

                    listViewItem.Text = string.Format("{0}\n{1} CP", pokemon.PokemonId, pokemon.Cp);
                    listViewItem.ToolTipText = currentCandy + " Candy\n" + currIv + "% IV";

                    var settings = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                    var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                    if (settings.EvolutionIds.Count > 0 && familyCandy.Candy > settings.CandyToEvolve)
                        listViewItem.Checked = true;

                    listView1.Items.Add(listViewItem);
                }
                Text = "Pokemon List | User: "******" | Pokemons: " + pokemons.Count() + "/" + profile.Profile.PokeStorage;
                EnabledButton(true);

                textBox1.Text = string.Empty;
            }
            catch (TaskCanceledException e) {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (UriFormatException e) {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (ArgumentOutOfRangeException e) {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (ArgumentNullException e) {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (NullReferenceException e) {
                textBox1.Text = e.Message;
                Execute();
            }
            catch (Exception e) {
                textBox1.Text = e.Message;
                Execute();
            }
        }
        public ObserverShroudSelectorLogic(Widget widget, World world)
        {
            var groups = new Dictionary<string, IEnumerable<CameraOption>>();

            teams = world.Players.Where(p => !p.NonCombatant)
                .Select(p => new CameraOption(this, p))
                .GroupBy(p => (world.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team)
                .OrderBy(g => g.Key);

            var noTeams = teams.Count() == 1;
            foreach (var t in teams)
            {
                var label = noTeams ? "Players" : t.Key == 0 ? "No Team" : "Team {0}".F(t.Key);
                groups.Add(label, t);
            }

            combined = new CameraOption(this, world, "All Players", world.Players.First(p => p.InternalName == "Everyone"));
            disableShroud = new CameraOption(this, world, "Disable Shroud", null);
            groups.Add("Other", new List<CameraOption>() { combined, disableShroud });

            var shroudSelector = widget.Get<DropDownButtonWidget>("SHROUD_SELECTOR");
            shroudSelector.OnMouseDown = _ =>
            {
                Func<CameraOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                {
                    var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                    var showFlag = option.Race != null;

                    var label = item.Get<LabelWidget>("LABEL");
                    label.IsVisible = () => showFlag;
                    label.GetText = () => option.Label;
                    label.GetColor = () => option.Color;

                    var flag = item.Get<ImageWidget>("FLAG");
                    flag.IsVisible = () => showFlag;
                    flag.GetImageCollection = () => "flags";
                    flag.GetImageName = () => option.Race;

                    var labelAlt = item.Get<LabelWidget>("NOFLAG_LABEL");
                    labelAlt.IsVisible = () => !showFlag;
                    labelAlt.GetText = () => option.Label;
                    labelAlt.GetColor = () => option.Color;

                    return item;
                };

                shroudSelector.ShowDropDown("SPECTATOR_DROPDOWN_TEMPLATE", 400, groups, setupItem);
            };

            var shroudLabel = shroudSelector.Get<LabelWidget>("LABEL");
            shroudLabel.IsVisible = () => selected.Race != null;
            shroudLabel.GetText = () => selected.Label;
            shroudLabel.GetColor = () => selected.Color;

            var shroudFlag = shroudSelector.Get<ImageWidget>("FLAG");
            shroudFlag.IsVisible = () => selected.Race != null;
            shroudFlag.GetImageCollection = () => "flags";
            shroudFlag.GetImageName = () => selected.Race;

            var shroudLabelAlt = shroudSelector.Get<LabelWidget>("NOFLAG_LABEL");
            shroudLabelAlt.IsVisible = () => selected.Race == null;
            shroudLabelAlt.GetText = () => selected.Label;
            shroudLabelAlt.GetColor = () => selected.Color;

            var keyhandler = shroudSelector.Get<LogicKeyListenerWidget>("SHROUD_KEYHANDLER");
            keyhandler.OnKeyPress = HandleKeyPress;

            selected = disableShroud;
        }
示例#38
0
        private List<string> GetListOfTrades(string player, IOrderedEnumerable<KeyValuePair<string, double>> tradeList, bool topDown)
        {
            List<string> results = new List<string>();

            if (topDown)
            {
                for (int i = 0; i < tradeList.Count(); i++)
                {
                    if (tradeList.ElementAt(i).Key == player)
                    {
                        break;
                    }

                    results.Add(tradeList.ElementAt(i).Key);
                }
            }
            else
            {
                for (int i = tradeList.Count() - 1; i >= 0; i--)
                {
                    if (tradeList.ElementAt(i).Key == player)
                    {
                        break;
                    }

                    results.Add(tradeList.ElementAt(i).Key);
                }
            }
            return results;
        }
示例#39
0
 /// <summary>
 /// Exports the queue with the current set of builds and the default or last used filename.
 /// </summary>
 /// <param name="queueBuilds"></param>
 /// <param name="results"></param>
 public static void Export(this QueueBuilds queueBuilds, IOrderedEnumerable<IQueuedBuild> results)
 {
     queueBuilds.WriteHeaders();
     queueBuilds.WriteBody(results);
     queueBuilds.WriteFooter(results.Count());
 }
示例#40
0
        private async void Execute()
        {
            EnabledButton(false, "Reloading Pokemon list.");

            client = new Client(ClientSettings);

            try
            {
                switch (ClientSettings.AuthType)
                {
                    case AuthType.Ptc:
                        await client.DoPtcLogin(ClientSettings.PtcUsername, ClientSettings.PtcPassword);
                        break;
                    case AuthType.Google:
                        await client.DoGoogleLogin();
                        break;
                }

                await client.SetServer();
                profile = await client.GetProfile();
                inventory = await client.GetInventory();
                pokemons =
                    inventory.InventoryDelta.InventoryItems
                    .Select(i => i.InventoryItemData?.Pokemon)
                        .Where(p => p != null && p?.PokemonId > 0)
                        .OrderByDescending(key => key.Cp);
                var families = inventory.InventoryDelta.InventoryItems
                    .Select(i => i.InventoryItemData?.PokemonFamily)
                    .Where(p => p != null && (int)p?.FamilyId > 0)
                    .OrderByDescending(p => (int)p.FamilyId);

                var imageSize = 50;

                var imageList = new ImageList { ImageSize = new Size(imageSize, imageSize) };
                PokemonListView.ShowItemToolTips = true;
                PokemonListView.SmallImageList = imageList;

                var templates = await client.GetItemTemplates();
                var myPokemonSettings = templates.ItemTemplates.Select(i => i.PokemonSettings).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                var pokemonSettings = myPokemonSettings.ToList();

                var myPokemonFamilies = inventory.InventoryDelta.InventoryItems.Select(i => i.InventoryItemData?.PokemonFamily).Where(p => p != null && p?.FamilyId != PokemonFamilyId.FamilyUnset);
                var pokemonFamilies = myPokemonFamilies.ToArray();

                PokemonListView.DoubleBuffered(true);
                PokemonListView.View = View.Details;

                ColumnHeader columnheader;
                columnheader = new ColumnHeader();
                columnheader.Text = "Name";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "CP";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "IV A-D-S";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "LVL";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Evolvable?";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Height";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Weight";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "HP";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "Attack";
                PokemonListView.Columns.Add(columnheader);
                columnheader = new ColumnHeader();
                columnheader.Text = "SpecialAttack";
                PokemonListView.Columns.Add(columnheader);

                foreach (var pokemon in pokemons)
                {
                    Bitmap pokemonImage = null;
                    await Task.Run(() =>
                    {
                        pokemonImage = GetPokemonImage((int)pokemon.PokemonId);
                    });
                    imageList.Images.Add(pokemon.PokemonId.ToString(), pokemonImage);

                    PokemonListView.LargeImageList = imageList;
                    var listViewItem = new ListViewItem();
                    listViewItem.Tag = pokemon;



                    var currentCandy = families
                        .Where(i => (int)i.FamilyId <= (int)pokemon.PokemonId)
                        .Select(f => f.Candy)
                        .First();
                    listViewItem.SubItems.Add(string.Format("{0}", pokemon.Cp));
                    listViewItem.SubItems.Add(string.Format("{0}% {1}-{2}-{3}", Math.Round(pokemon.CalculateIV()), pokemon.IndividualAttack, pokemon.IndividualDefense, pokemon.IndividualStamina));
                    listViewItem.SubItems.Add(string.Format("{0}", PokemonInfo.GetLevel(pokemon)));
                    listViewItem.ImageKey = pokemon.PokemonId.ToString();
                    
                    listViewItem.Text = string.Format((pokemon.Favorite == 1)? "{0} ★" : "{0}", pokemon.PokemonId);

                    listViewItem.ToolTipText = new DateTime((long)pokemon.CreationTimeMs * 10000).AddYears(1970).ToString("dd/MM/yyyy HH:mm:ss");
                    if (pokemon.Nickname!="")
                        listViewItem.ToolTipText += "\nNickname: " + pokemon.Nickname;

                    var settings = pokemonSettings.Single(x => x.PokemonId == pokemon.PokemonId);
                    var familyCandy = pokemonFamilies.Single(x => settings.FamilyId == x.FamilyId);

                    if (settings.EvolutionIds.Count > 0 && familyCandy.Candy >= settings.CandyToEvolve)
                    {
                        listViewItem.SubItems.Add("Y (" + familyCandy.Candy + "/" + settings.CandyToEvolve + ")");
                        listViewItem.Checked = true;
                    }
                    else
                    {
                        if (settings.EvolutionIds.Count > 0)
                            listViewItem.SubItems.Add("N (" + familyCandy.Candy + "/" + settings.CandyToEvolve + ")");
                        else
                            listViewItem.SubItems.Add("N (" + familyCandy.Candy + "/Max)");
                    }
                    listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.HeightM, 2)));
                    listViewItem.SubItems.Add(string.Format("{0}", Math.Round(pokemon.WeightKg, 2)));
                    listViewItem.SubItems.Add(string.Format("{0}/{1}", pokemon.Stamina, pokemon.StaminaMax));
                    listViewItem.SubItems.Add(string.Format("{0}", pokemon.Move1));
                    listViewItem.SubItems.Add(string.Format("{0}", pokemon.Move2));

                    PokemonListView.Items.Add(listViewItem);
                }
                PokemonListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                Text = "Pokemon List | User: "******" | Pokemons: " + pokemons.Count() + "/" + profile.Profile.PokeStorage;
                EnabledButton(true);

                statusTexbox.Text = string.Empty;
            }
            catch (Exception e)
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Red, "Error reloading Pokemon list: " + e.Message);
                await Task.Delay(500); // Lets the API make a little pause, so we dont get blocked
                Execute();
            }
        }