public async Task Lsar(int page = 1)
            {
                if (--page < 0)
                {
                    List <IRole> rms;
                    using (var uow = _db.UnitOfWork)
                    {
                        var roleModels = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id).ToList();

                        rms = (from rm in roleModels
                               let role = Context.Guild.Roles.FirstOrDefault(r => r.Id == rm.RoleId)
                                          where role != null
                                          select role).ToList();

                        uow.SelfAssignedRoles.RemoveRange(roleModels.Where(rm => rms.All(r => r.Id != rm.RoleId)).ToArray());
                        await uow.CompleteAsync();
                    }
                    await Context.Channel.SendMessageAsync("", embed : new EmbedBuilder().WithTitle(GetText("self_assign_list", rms.Count)).WithDescription(rms.Aggregate("", (s, r) => s + Format.Bold(r.Name) + ", ", s => s.Substring(0, s.Length - 2))).WithOkColor().Build());

                    return;
                }

                var toRemove = new ConcurrentHashSet <SelfAssignedRole>();
                var roles    = new List <string>();
                var roleCnt  = 0;

                using (var uow = _db.UnitOfWork)
                {
                    var roleModels = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id).ToList();

                    foreach (var roleModel in roleModels)
                    {
                        var role = Context.Guild.Roles.FirstOrDefault(r => r.Id == roleModel.RoleId);
                        if (role == null)
                        {
                            toRemove.Add(roleModel);
                            uow.SelfAssignedRoles.Remove(roleModel);
                        }
                        else
                        {
                            roles.Add(Format.Bold(role.Name));
                            roleCnt++;
                        }
                    }
                    roles.AddRange(toRemove.Select(role => GetText("role_clean", role.RoleId)));
                    await uow.CompleteAsync();
                }

                await Context.Channel.SendPaginatedConfirmAsync((DiscordSocketClient)Context.Client, page, curPage => new EmbedBuilder()
                                                                .WithTitle(GetText("self_assign_list", roleCnt))
                                                                .WithDescription(string.Join("\n", roles.Skip(curPage * 10).Take(10)))
                                                                .WithOkColor(), roles.Count / 10);
            }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="scriptPubKey"></param>
        /// <param name="receivedTransactions">int: block height</param>
        /// <param name="spentTransactions">int: block height</param>
        /// <returns></returns>
        public bool TryFindConfirmedTransactions(Script scriptPubKey, out ConcurrentHashSet <SmartTransaction> receivedTransactions, out ConcurrentHashSet <SmartTransaction> spentTransactions)
        {
            var found = false;

            receivedTransactions = new ConcurrentHashSet <SmartTransaction>();
            spentTransactions    = new ConcurrentHashSet <SmartTransaction>();

            foreach (var tx in TrackedTransactions.Where(x => x.Confirmed))
            {
                // if already has that tx continue
                if (receivedTransactions.Any(x => x.GetHash() == tx.GetHash()))
                {
                    continue;
                }

                foreach (var output in tx.Transaction.Outputs)
                {
                    if (output.ScriptPubKey.Equals(scriptPubKey))
                    {
                        receivedTransactions.Add(tx);
                        found = true;
                    }
                }
            }

            if (found)
            {
                foreach (var tx in TrackedTransactions.Where(x => x.Confirmed))
                {
                    // if already has that tx continue
                    if (spentTransactions.Any(x => x.GetHash() == tx.GetHash()))
                    {
                        continue;
                    }

                    foreach (var input in tx.Transaction.Inputs)
                    {
                        if (receivedTransactions.Select(x => x.GetHash()).Contains(input.PrevOut.Hash))
                        {
                            spentTransactions.Add(tx);
                            found = true;
                        }
                    }
                }
            }

            return(found);
        }
            public async Task Lsar(int page = 1)
            {
                var roleModels = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id).ToList();

                if (--page < 0)
                {
                    var rms = (from rm in roleModels
                               let role = Context.Guild.Roles.FirstOrDefault(r => r.Id == rm.RoleId)
                                          where role != null
                                          select role).ToList();

                    uow.SelfAssignedRoles.RemoveRange(roleModels.Where(rm => rms.All(r => r.Id != rm.RoleId)).ToArray());
                    await uow.SaveChangesAsync(false);

                    await Context.Channel.SendMessageAsync("", embed : new EmbedBuilder().WithTitle(GetText("self_assign_list", rms.Count)).WithDescription(rms.Aggregate("", (s, r) => s + Format.Bold(r.Name) + ", ", s => s.Substring(0, s.Length - 2))).WithOkColor().Build());

                    return;
                }

                var toRemove = new ConcurrentHashSet <SelfAssignedRole>();
                var roles    = new List <string>();
                var roleCnt  = 0;

                foreach (var roleModel in roleModels)
                {
                    var role = Context.Guild.Roles.FirstOrDefault(r => r.Id == roleModel.RoleId);
                    if (role == null)
                    {
                        toRemove.Add(roleModel);
                        uow.SelfAssignedRoles.Remove(roleModel);
                    }
                    else
                    {
                        roles.Add(Format.Bold(role.Name));
                        roleCnt++;
                    }
                }
                roles.AddRange(toRemove.Select(role => GetText("role_clean", role.RoleId)));
                await uow.SaveChangesAsync(false);

                const int elementsPerPage = 10;

                await Context.Channel.SendPaginatedConfirmAsync(Context.Client as DiscordSocketClient, page, currentPage => new EmbedBuilder()
                                                                .WithTitle(GetText("self_assign_list", roleCnt))
                                                                .WithDescription(string.Join("\n", roles.Skip(currentPage *elementsPerPage).Take(elementsPerPage)))
                                                                .WithOkColor(), (int)Math.Ceiling(roles.Count * 1d / elementsPerPage), reactUsers : new[] { Context.User as IGuildUser });
            }
Пример #4
0
        private BoundingBox GetExtents()
        {
            // todo: Calculate extents only once. Use a _modified field to determine when this is needed.

            var geometries = _cache
                             .Select(f => f.Geometry)
                             .Where(g => g != null && !g.IsEmpty() && g.BoundingBox != null)
                             .ToList();

            if (geometries.Count == 0)
            {
                return(null);
            }

            var minX = geometries.Min(g => g.BoundingBox.MinX);
            var minY = geometries.Min(g => g.BoundingBox.MinY);
            var maxX = geometries.Max(g => g.BoundingBox.MaxX);
            var maxY = geometries.Max(g => g.BoundingBox.MaxY);

            return(new BoundingBox(minX, minY, maxX, maxY));
        }
 public Task <IEnumerable <ServerRecord> > FetchServerListAsync() => Task.FromResult(ServerRecords.Select(server => ServerRecord.CreateServer(server.Host, server.Port, server.ProtocolTypes)));
        public Task Run()
        {
            var backupDir = Core.Instance.Config.BackupDirectory;

            Core.Instance.Log.InfoFormat("Starting LookUpProtocol: '{0}'", backupDir);
            return(Task.Factory.StartNew(() =>
            {
                // get array with all the fileId's associated with the backed up chunks
                var fileIds = Util.GetLocalFileChunks()
                              .Select(chunk => chunk.FileId)
                              .Distinct().ToList();

                if (fileIds.Count == 0)
                {
                    Core.Instance.Log.Info("LookUpProtocol: got no files, no lookup required");
                    return;
                }

                // remove duplicates, transform the collection into a ConcurrentHashSet
                var backedUpFilesId = new ConcurrentHashSet <FileId>(fileIds);

                var waitPeriod = 1000;
                for (int retry = 0; retry < MaxRetries; ++retry)
                {
                    // perform a lookup for each fileId
                    var subscriptions = backedUpFilesId.Select(id =>
                    {
                        Core.Instance.MCChannel.Send(new LookupMessage(id));
                        return Core.Instance.MCChannel.Received
                        .Where(message => message.MessageType == MessageType.Got)
                        .Cast <GotMessage>()
                        .Where(message => message.FileId == id)
                        // ReSharper disable once AccessToDisposedClosure
                        .Subscribe(msg => backedUpFilesId.Remove(msg.FileId));
                    }).ToList();

                    // wait
                    Task.Delay(waitPeriod).Wait();

                    foreach (var subscription in subscriptions)
                    {
                        subscription.Dispose();
                    }

                    // if we got a Got for all the files we don't need to wait longer
                    if (backedUpFilesId.Count == 0)
                    {
                        break;
                    }

                    waitPeriod *= 2;
                }

                // delete all the unused chunks
                foreach (var unusedFileId in backedUpFilesId)
                {
                    var fileList = Directory.GetFiles(backupDir, unusedFileId + "_*");
                    foreach (var backedUpChunk in fileList)
                    {
                        File.Delete(backedUpChunk);
                    }

                    Core.Instance.ChunkPeers.RemoveAllChunkPeer(unusedFileId);
                }

                backedUpFilesId.Clear();
                backedUpFilesId.Dispose();
            }));
        }
Пример #7
0
		private bool FarmHours(ConcurrentHashSet<Game> games) {
			if ((games == null) || (games.Count == 0)) {
				Logging.LogNullError(nameof(games), Bot.BotName);
				return false;
			}

			float maxHour = games.Max(game => game.HoursPlayed);
			if (maxHour < 0) {
				Logging.LogNullError(nameof(maxHour), Bot.BotName);
				return false;
			}

			if (maxHour >= 2) {
				Logging.LogGenericError("Received request for past-2h games!", Bot.BotName);
				return true;
			}

			Bot.ArchiHandler.PlayGames(games.Select(game => game.AppID), Bot.BotConfig.CustomGamePlayedWhileFarming);

			bool success = true;
			while (maxHour < 2) {
				Logging.LogGenericInfo("Still farming: " + string.Join(", ", games.Select(game => game.AppID)), Bot.BotName);

				DateTime startFarmingPeriod = DateTime.Now;
				if (FarmResetEvent.Wait(60 * 1000 * Program.GlobalConfig.FarmingDelay)) {
					FarmResetEvent.Reset();
					success = KeepFarming;
				}

				// Don't forget to update our GamesToFarm hours
				float timePlayed = (float) DateTime.Now.Subtract(startFarmingPeriod).TotalHours;
				foreach (Game game in games) {
					game.HoursPlayed += timePlayed;
				}

				if (!success) {
					break;
				}

				maxHour += timePlayed;
			}

			Logging.LogGenericInfo("Stopped farming: " + string.Join(", ", games.Select(game => game.AppID)), Bot.BotName);
			return success;
		}