Inheritance: FrobbableObject
コード例 #1
0
ファイル: WarnBuilder.cs プロジェクト: JulianusIV/LathBot
        public async Task RequestPoints()
        {
            DiscordMessageBuilder discordMessage = new DiscordMessageBuilder
            {
                Content = $"For this rule you can reduce the users chances by {Rule.MinPoints} - {Rule.MaxPoints}"
            };

            for (int i = 0; i < 3; i++)
            {
                List <DiscordButtonComponent> buttons = new List <DiscordButtonComponent>();
                for (int index = i * 5; index < (i * 5) + 5; index++)
                {
                    buttons.Add(new DiscordButtonComponent
                                (
                                    ButtonStyle.Primary,
                                    (index + 1).ToString(),
                                    (index + 1).ToString(),
                                    (index + 1) < Rule.MinPoints || (index + 1) > Rule.MaxPoints)
                                );
                }
                discordMessage.AddComponents(buttons);
            }
            DiscordMessage pointsMessage = await WarnChannel.SendMessageAsync(discordMessage);

            var interactpointsMessage = await Interactivity.WaitForButtonAsync(pointsMessage, Mod, TimeSpan.FromMinutes(2));

            PointsDeducted = int.Parse(interactpointsMessage.Result.Id);
            await pointsMessage.DeleteAsync();
        }
コード例 #2
0
ファイル: JUDGE_STATUS.cs プロジェクト: oneshadab/UVA-Arena
        private void submissionStatus_HyperlinkClicked(object sender, BrightIdeasSoftware.HyperlinkClickedEventArgs e)
        {
            JudgeStatus list = (JudgeStatus)e.Model;

            if (e.Column == pnumSUB || e.Column == ptitleSUB)
            {
                Interactivity.ShowProblem(list.pnum);
            }
            else if (e.Column == unameSUB)
            {
                if (LocalDatabase.ContainsUser(list.uname))
                {
                    Interactivity.ShowUserStat(list.uname);
                }
                else
                {
                    if (MessageBox.Show("Add \"" + list.uname + "\" to your favorite list?", "Add User",
                                        MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return;
                    }
                    RegistryAccess.AddUserid(list.uname, list.uid.ToString());
                    Interactivity.ShowUserStat(list.uname);
                }
            }
        }
コード例 #3
0
        private void ShowDeepSearchStatus()
        {
            if (this.IsDisposed)
            {
                return;
            }

            if (_InDeepSearch)
            {
                int total = LocalDatabase.problemList.Count;
                Interactivity.SetProgress(_DeepSearchProgress, total);
                string msg = "Searching for problems... [{0} of {1} problems completed.]";
                Interactivity.SetStatus(string.Format(msg, _DeepSearchProgress, total));

                _SetObjects(_deepSearchRes);
                problemListView.Sort(priorityProb, SortOrder.Descending);

                TaskQueue.AddTask(ShowDeepSearchStatus, 1000);
            }
            else
            {
                Interactivity.SetProgress(0);
                if (_CancelSearch)
                {
                    Interactivity.SetStatus("Deep search cancelled.");
                }
                else
                {
                    Interactivity.SetStatus("Deep search completed.");
                }
            }
        }
コード例 #4
0
ファイル: Internet.cs プロジェクト: maestrofx/UVA-Arena
        private static void __DownloadUseridCompleted(DownloadTask task)
        {
            string uid  = (string)task.Result;
            string name = (string)task.Token;

            task.Status = ProgressStatus.Failed;
            if (string.IsNullOrEmpty(uid))
            {
                task.Error = new Exception("Connection error. Retry please.");
            }
            else if (uid.Trim() == "0")
            {
                task.Error = new Exception(name + " doesn't exist.");
            }
            else if (task.Error == null)
            {
                task.Status = ProgressStatus.Completed;
            }

            if (task.Status == ProgressStatus.Completed)
            {
                RegistryAccess.SetUserid(name, uid);
                string msg = "Username downloaded : {0} = {1}";
                Interactivity.SetStatus(string.Format(msg, name, uid));
            }
        }
コード例 #5
0
        public async Task GetAnimeAsync(CommandContext ctx, [RemainingText] string name)
        {
            var animes = (await Kitsu.GetAnimeAsync(name)).Data.Take(10).ToList();
            var embed  = new DiscordEmbedBuilder()
                         .WithTitle("Select anime")
                         .WithFooter(ctx.Member.GetFullName(), ctx.Member.AvatarUrl);

            for (var i = 0; i < animes.Count; i++)
            {
                var a = animes[i];
                embed.AddField($"[{i + 1}] {a.Attributes.Titles.En}({a.Attributes.Titles.JaJp})",
                               $"{a.Attributes.AverageRating?.ToString() ?? "none"}");
            }
            var index = -1;

            ToDelete.Add(ctx.Message);
            ToDelete.Add(await ctx.RespondAsync(embed: embed));
            ToDelete.Add((await Interactivity.WaitForMessageAsync(
                              x => int.TryParse(x.Content, out index) &&
                              index > 0 &&
                              index <= 10 ||
                              index == -1,
                              TimeSpan.FromSeconds(30))).Message);
            if (index == -1)
            {
                return;
            }
            var anime = animes[index - 1];

            embed.WithTitle($"{anime.Attributes.Titles.En}({anime.Attributes.Titles.EnJp})");
            embed.ClearFields();
            embed.Description = anime.Attributes.Synopsis;
            await ctx.RespondAsync(embed : embed);
        }
コード例 #6
0
        public async Task Hentai([Remainder] string tags)
        {
            GalleryElement qq = await NHentaiService.getBook(tags);

            Console.WriteLine(qq.numPages);
            var paginator = new LazyPaginatorBuilder()
                            .WithUsers(Context.User)
                            .WithPageFactory(PageFactory)
                            .WithMaxPageIndex(int.Parse(qq.numPages.ToString()))
                            .WithFooter(PaginatorFooter.PageNumber | PaginatorFooter.Users)
                            .WithDefaultEmotes()
                            .Build();

            Console.WriteLine(qq.cover.imageUrl);
            //await Context.Channel.SendMessageAsync(stuff.value[0].thumbnailUrl.ToString());
            await Interactivity.SendPaginatorAsync(paginator, Context.Channel, TimeSpan.FromMinutes(2));

            Task <PageBuilder> PageFactory(int page)
            {
                return(Task.FromResult(new PageBuilder()
                                       //.WithText((page + 1).ToString())
                                       .WithTitle(qq.prettyTitle + $" Page {page + 1}")
                                       .WithImageUrl(qq.pages[page].imageUrl.ToString())
                                       .WithColor(System.Drawing.Color.FromArgb(page * 400))));
            }
        }
コード例 #7
0
ファイル: WarnBuilder.cs プロジェクト: JulianusIV/LathBot
        public async Task <ulong> RequestRuleEphemeral(ContextMenuContext ctx)
        {
            List <DiscordSelectComponentOption> options = new List <DiscordSelectComponentOption>();

            foreach (var item in RuleService.rules)
            {
                if (item.RuleNum == 0)
                {
                    options.Add(new DiscordSelectComponentOption(
                                    $"OTHER",
                                    item.RuleNum.ToString()));
                    continue;
                }
                var option = new DiscordSelectComponentOption(
                    $"Rule {item.RuleNum}: {item.ShortDesc}",
                    item.RuleNum.ToString(),
                    item.RuleText.Length > 99 ? item.RuleText[..95] + "..." : item.RuleText);
                options.Add(option);
            }
            DiscordSelectComponent selectMenu = new DiscordSelectComponent("warnSelect", "Select a Rule!", options);

            var message = await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder()
                                                  .AddComponents(selectMenu)
                                                  .WithContent("­")
                                                  .AsEphemeral(true));

            var reaction = await Interactivity.WaitForSelectAsync(message, Mod, "warnSelect", TimeSpan.FromMinutes(2));

            Rule = RuleService.rules.Single(x => x.RuleNum.ToString() == reaction.Result.Values.First());
            await reaction.Result.Interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate);

            return(message.Id);
        }
コード例 #8
0
        public async Task ImageSearch([Remainder] string query)
        {
            string qq = await PictureService.GetGoogleResult(query);

            dynamic stuff = JsonConvert.DeserializeObject(qq);

            Console.WriteLine(stuff.totalEstimatedMatches);
            var paginator = new LazyPaginatorBuilder()
                            .WithUsers(Context.User)
                            .WithPageFactory(PageFactory)
                            .WithMaxPageIndex(int.Parse(stuff.totalEstimatedMatches.ToString()) - 1)
                            .WithFooter(PaginatorFooter.PageNumber | PaginatorFooter.Users)
                            .WithDefaultEmotes()
                            .Build();

            Console.WriteLine(stuff.value[0].thumbnailUrl);
            //await Context.Channel.SendMessageAsync(stuff.value[0].thumbnailUrl.ToString());
            await Interactivity.SendPaginatorAsync(paginator, Context.Channel, TimeSpan.FromMinutes(2));

            Task <PageBuilder> PageFactory(int page)
            {
                return(Task.FromResult(new PageBuilder()
                                       //.WithText((page + 1).ToString())
                                       .WithTitle($"Image Result {page + 1}")
                                       .WithImageUrl(stuff.value[page].thumbnailUrl.ToString())
                                       .WithColor(System.Drawing.Color.FromArgb(page * 1500))));
            }
        }
コード例 #9
0
ファイル: USER_STAT.cs プロジェクト: oneshadab/UVA-Arena
        /// <summary>
        /// Runs a background thread to download and show world rank data.
        /// </summary>
        /// <param name="from">Integer type objects </param>
        private void ShowWorldRank(object from)
        {
            if (currentUser == null)
            {
                return;
            }

            if (webClient2.IsBusy)
            {
                webClient2.CancelAsync();
                TaskQueue.AddTask(new TaskQueue.Function2(ShowWorldRank), from, 500);
                return;
            }

            string url;

            if ((int)from <= 0)
            {
                //get current user's ranklist
                string format = "http://uhunt.felix-halim.net/api/ranklist/{0}/{1}/{2}";
                url = string.Format(format, currentUser.uid, 100, 100);
                Interactivity.SetStatus("Downloading " + currentUser.uname + "'s rank-list...");
            }
            else
            {
                //get ranklist from a specific rank
                string format = "http://uhunt.felix-halim.net/api/rank/{0}/{1}";
                url = string.Format(format, from, 200);
                Interactivity.SetStatus("Downloading rank-list from " + from.ToString() + "...");
            }

            webClient2.DownloadDataAsync(new Uri(url), from);
        }
コード例 #10
0
ファイル: USER_STAT.cs プロジェクト: oneshadab/UVA-Arena
        private void ShowDataByTab()
        {
            Interactivity.SetStatus();
            if (currentUser == null)
            {
                return;
            }

            //change view and looks
            userNameTitle.Text = string.Format(userNameTitle.Tag.ToString(),
                                               currentUser.name, currentUser.uname);

            if (tabControl1.SelectedTab == submissionTab)
            {
                SetSubmissionToListView();
            }
            else if (tabControl1.SelectedTab == progtrackerTab)
            {
                Interactivity.progTracker.ShowUserInfo(currentUser);
            }
            else if (tabControl1.SelectedTab == worldrankTab)
            {
                ShowWorldRank(-1);
            }
        }
コード例 #11
0
ファイル: Classic.cs プロジェクト: unclevicky/Sanguosha-Unity
        public override void OnChooseGeneralReply(Room room, Interactivity client)
        {
            Player        player      = room.GetPlayers(client.ClientId)[0];
            List <string> options     = JsonUntity.Json2List <string>((string)player.GetTag("generals"));
            List <string> reply       = client.ClientReply;
            bool          success     = true;
            string        generalName = string.Empty;

            if (reply == null || reply.Count == 0 || string.IsNullOrEmpty(reply[0]))
            {
                success = false;
            }
            else
            {
                generalName = reply[0];
            }

            if (!success || (!options.Contains(generalName) && room.GetClient(client.ClientId).UserRight < 3))
            {
                generalName = options[0];
            }

            player.General1       = generalName;
            player.ActualGeneral1 = generalName;
            player.Kingdom        = Engine.GetGeneral(generalName, room.Setting.GameMode).Kingdom;
            player.General1Showed = true;
            room.NotifyProperty(room.GetClient(player), player, "General1");
            room.NotifyProperty(room.GetClient(player), player, "Kingdom");
        }
コード例 #12
0
        private static void __DownloadProblemDatabaseCompleted(DownloadTask task)
        {
            _DownloadingProblemDatabase = false;

            string msg = "Failed to update problem list.";

            if (task.Status == ProgressStatus.Completed)
            {
                LocalDatabase.LoadDatabase();
                msg = "Problem list is successfully updated.";
                Logger.Add("Downloaded problem database file", "__DownloadProblemDatabaseCompleted");
            }
            else if (task.Error != null)
            {
                if (task.Token == null)
                {
                    LocalDatabase.LoadDatabase();
                    Logger.Add(task.Error.Message, "__DownloadProblemDatabaseCompleted");
                }
                else
                {
                    DownloadFileAsync((string)task.Token, task.FileName, null, Priority.High,
                                      __DownloadProblemDatabaseProgress, __DownloadProblemDatabaseCompleted, 0);
                }
            }

            Interactivity.SetStatus(msg);
            Interactivity.SetProgress(0);
        }
コード例 #13
0
ファイル: CompareUsers.cs プロジェクト: maestrofx/UVA-Arena
 private void lastSubmissions1_HyperlinkClicked(object sender, BrightIdeasSoftware.HyperlinkClickedEventArgs e)
 {
     if (e.Column == pnumSUB || e.Column == ptitleSUB)
     {
         Interactivity.ShowProblem(((UserSubmission)e.Model).pnum);
     }
 }
コード例 #14
0
        public override void OnChooseGeneralReply(Room room, Interactivity client)
        {
            //该模式下玩家完成选将会立即先所有人公布
            Player        player      = room.GetPlayers(client.ClientId)[0];
            List <string> options     = JsonUntity.Json2List <string>((string)player.GetTag("generals"));
            List <string> reply       = client.ClientReply;
            bool          success     = true;
            string        generalName = string.Empty;

            if (reply == null || reply.Count == 0 || string.IsNullOrEmpty(reply[0]))
            {
                success = false;
            }
            else
            {
                generalName = reply[0];
            }

            if (!success || (!options.Contains(generalName) && room.GetClient(player).UserRight < 3) ||
                (player.Camp == Game3v3Camp.S_CAMP_COOL && Engine.GetGeneral(generalName, room.Setting.GameMode).Kingdom[0] != General.KingdomENUM.Wei) ||
                (player.Camp == Game3v3Camp.S_CAMP_WARM && Engine.GetGeneral(generalName, room.Setting.GameMode).Kingdom[0] != General.KingdomENUM.Qun))
            {
                generalName = options[0];
            }

            player.General1       = generalName;
            player.ActualGeneral1 = generalName;
            player.Kingdom        = General.GetKingdom(Engine.GetGeneral(generalName, room.Setting.GameMode).Kingdom[0]);
            player.General1Showed = true;
            room.BroadcastProperty(player, "General1");
            room.BroadcastProperty(player, "Kingdom");
        }
コード例 #15
0
ファイル: JUDGE_STATUS.cs プロジェクト: oneshadab/UVA-Arena
        void webClient1_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            try
            {
                string result = System.Text.Encoding.UTF8.GetString(e.Result);

                //update or add last submission id
                JudgeStatus[] statuslist = JsonConvert.DeserializeObject <JudgeStatus[]>(result);
                foreach (JudgeStatus status in statuslist)
                {
                    SetStatus(status);
                    if (status.id > LastSubID)
                    {
                        LastSubID = status.id;
                    }
                }

                Interactivity.SetProgress();
                Interactivity.SetStatus("Judge status update finished.");

                //set submission status
                submissionStatus.SetObjects(StatusList, false);
                submissionStatus.Sort(sidSUB, SortOrder.Descending);
                submissionStatus.EnsureVisible(0);
            }
            catch (Exception ex)
            {
                Interactivity.SetStatus("Judge status update failed.");
                Logger.Add(ex.Message, "Judge Status | webClient1_DownloadDataCompleted");
            }
            finally
            {
                LastUpdate = DateTime.Now;
            }
        }
コード例 #16
0
        public static string GetInputdata(UserInput user)
        {
            Interactivity.SetStatus("Loading user input data...");

            var url     = "https://www.udebug.com/udebug-custom-get-selected-input-ajax";
            var request = (HttpWebRequest)WebRequest.Create(url);

            var postData = "input_nid=" + user.InputNID;
            var data     = Encoding.ASCII.GetBytes(postData);

            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response       = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            var result = Newtonsoft.Json.JsonConvert.DeserializeObject <InputValue>(responseString);

            Interactivity.SetStatus("User's input data downloaded.");
            return(result.input_value);
        }
コード例 #17
0
ファイル: USER_STAT.cs プロジェクト: oneshadab/UVA-Arena
        void webClient2_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (this.IsDisposed)
            {
                return;
            }
            if (e.Cancelled)
            {
                return;
            }

            UserRanklist currentRank = null;

            try
            {
                if (e.Error != null)
                {
                    throw e.Error;
                }

                string result = System.Text.Encoding.UTF8.GetString(e.Result);

                if (worldRanks != null)
                {
                    worldRanks.Clear();
                }
                worldRanks = JsonConvert.DeserializeObject <List <UserRanklist> >(result);

                foreach (UserRanklist usub in worldRanks)
                {
                    if (LocalDatabase.ContainsUser(usub.username))
                    {
                        RegistryAccess.SetUserRank(usub);
                        if (usub.username == currentUser.uname)
                        {
                            currentRank = usub;
                        }
                    }
                }

                worldRanklist.SetObjects(worldRanks);
                worldRanklist.Sort(rankRANK, SortOrder.Ascending);


                Interactivity.SetStatus(currentUser.uname + "'s rank-list downloaded.");
                Logger.Add("World rank downloaded - " + currentUser.uname, "World Rank | webClient2_DownloadDataCompleted");
            }
            catch (Exception ex)
            {
                TaskQueue.AddTask(new TaskQueue.Function2(ShowWorldRank), e.UserState, 500);
                Interactivity.SetStatus("Rank-list download failed due to an error. Please try again.");
                Logger.Add(ex.Message, "World Rank | webClient2_DownloadDataCompleted");
            }

            if ((int)e.UserState == -1)
            {
                BringUserToMiddle(currentRank);
            }
        }
コード例 #18
0
        public async Task TempMuteUser([RequireHierarchy] UserRef userRef, TimeSpan time, [Remainder] string reason)
        {
            if (time.TotalMinutes < 1)
            {
                await ReplyAsync("Can't temp-mute for less than a minute");

                return;
            }
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>();

            if (!(Context.Message.Author as IGuildUser).HasAdmin())
            {
                if (settings?.maxTempAction != null && time > settings.maxTempAction)
                {
                    await ReplyAsync("You are not allowed to punish for that long");

                    return;
                }
            }
            if (settings == null || settings.mutedRole == 0 || Context.Guild.GetRole(settings.mutedRole) == null)
            {
                await ReplyAsync("Muted role is null or invalid");

                return;
            }
            TempActionList actions = Context.Guild.LoadFromFile <TempActionList>(true);
            TempAct        oldAct  = actions.tempMutes.FirstOrDefault(tempMute => tempMute.User == userRef.ID);

            if (oldAct != null)
            {
                if (!(Context.Message.Author as IGuildUser).HasAdmin() && (oldAct.Length - (DateTime.UtcNow - oldAct.DateBanned)) >= time)
                {
                    await ReplyAsync($"{Context.User.Mention} please contact your admin(s) in order to shorten length of a punishment");

                    return;
                }
                string text    = $"{userRef.Name()} is already temp-muted for {oldAct.Length.LimitedHumanize()} ({(oldAct.Length - (DateTime.UtcNow - oldAct.DateBanned)).LimitedHumanize()} left), are you sure you want to change the length?";
                var    request = new ConfirmationBuilder()
                                 .WithContent(new PageBuilder().WithText(text))
                                 .Build();
                var result = await Interactivity.SendConfirmationAsync(request, Context.Channel, TimeSpan.FromMinutes(2));

                if (result.Value)
                {
                    actions.tempMutes.Remove(oldAct);
                    actions.SaveToFile();
                }
                else
                {
                    await ReplyAsync("Command canceled");

                    return;
                }
            }

            await userRef.TempMute(time, reason, Context, settings, actions);

            Context.Message.DeleteOrRespond($"Temporarily muted {userRef.Mention()} for {time.LimitedHumanize(3)} because of {reason}", Context.Guild);
        }
コード例 #19
0
    public void ducTime(float _to, float _duration, iTween.EaseType easeType = iTween.EaseType.easeOutCubic, bool bDucAudio = false)
    {
        Interactivity interactivity = null;

        if (bDucAudio == true)
        {
            var go = GameObject.Find("__Interactivity");
            if (go)
            {
                interactivity = go.GetComponent <Interactivity>();
            }

            if (interactivity == null)
            {
                Debug.LogError("Unable to find __Interactivity");
            }
        }

        var fullSpeed = playbackSpeedInFramesPerSecond / 30.0f;
        var from      = Time.timeScale;

        Debug.Log(string.Format("duc {0} > {1}", from, _to));
        if (from == _to)
        {
            return;
        }

        var id = "CinematronDucTween";

        iTween.StopByName(gameObject, id);
        iTween.ValueTo(gameObject, iTween.Hash("name", id, "from", 0.0f, "to", 1.0f, "time", _duration, "easetype", easeType, "ignoretimescale", true,
                                               "onUpdate", (System.Action <object>)((x) =>
        {
            float f = Mathf.Clamp01((float)x);
            var ts  = Mathf.Lerp(from, _to, f);

            Time.timeScale = ts;

            if (bDucAudio == true)
            {
                AudioListener.volume = Mathf.Clamp(f, 0.0f, 1.0f);
                foreach (var a in interactivity.allAudios)
                {
                    if (a.isPlaying && a.gameObject.activeInHierarchy && a.gameObject.activeSelf)
                    {
                        a.pitch = ts * (1 / fullSpeed) * (playbackSpeedInFramesPerSecond / musicSpeedInFramesPerSecond);
                    }
                }
            }
        }),
                                               "onComplete", (System.Action <object>)((x) =>
        {
            Time.timeScale = _to;
            if (bDucAudio == true)
            {
                resyncMusic();
            }
        })));
    }
コード例 #20
0
ファイル: ProblemViewer.cs プロジェクト: maestrofx/UVA-Arena
 private void submitButton_Click(object sender, EventArgs e)
 {
     if (current == null)
     {
         return;
     }
     Interactivity.SubmitCode(current.pnum);
 }
コード例 #21
0
ファイル: USER_STAT.cs プロジェクト: oneshadab/UVA-Arena
        void webClient1_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Interactivity.SetProgress(e.ProgressPercentage);
            string msg = "Downloading {0}'s submissions... [{1} out of {2}]";

            Interactivity.SetStatus(string.Format(msg, e.UserState,
                                                  Functions.FormatMemory(e.BytesReceived), Functions.FormatMemory(e.TotalBytesToReceive), true));
        }
コード例 #22
0
        private void dt_progressChanged(DownloadTask task)
        {
            string status = string.Format("Downloading submission data on problem... [{0} of {1} received]",
                                          Functions.FormatMemory(task.Received), Functions.FormatMemory(task.Total));

            Interactivity.SetStatus(status);
            Interactivity.SetProgress(task.ProgressPercentage);
        }
コード例 #23
0
        public List <WorldObject> NearbyObject(WorldObject @object, int range, Interactivity interactivity)
        {
            var objects = from worldObject in _worldObjects
                          where worldObject.Interactivity == interactivity && (int)Math.Round(@object.Position.Distance(worldObject.Position)) <= range && worldObject != @object
                          orderby @object.Position.Distance(worldObject.Position)
                          select worldObject;

            return(objects.ToList());
        }
コード例 #24
0
ファイル: USER_STAT.cs プロジェクト: oneshadab/UVA-Arena
        void webClient1_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (this.IsDisposed)
            {
                return;
            }
            try
            {
                Interactivity.SetProgress();
                if (e.Cancelled)
                {
                    throw new OperationCanceledException();
                }
                if (e.Error != null)
                {
                    throw e.Error;
                }

                string result = System.Text.Encoding.UTF8.GetString(e.Result);

                if (currentUser != null)
                {
                    if (currentUser.uname != (string)e.UserState)
                    {
                        return;
                    }
                    currentUser.AddSubmissions(result);
                }
                else
                {
                    currentUser = JsonConvert.DeserializeObject <UserInfo>(result);
                    currentUser.Process();
                }

                string file = LocalDirectory.GetUserSubPath(currentUser.uname);
                string data = currentUser.GetJSONData();
                File.WriteAllText(file, data);

                ShowDataByTab();

                string msg = string.Format("Downloaded {0}'s submissions", e.UserState);
                Interactivity.SetStatus(msg);
                if (currentUser.LastSID == 0)
                {
                    Logger.Add(msg, "User Statistics");
                }
            }
            catch (Exception ex)
            {
                Interactivity.SetStatus(string.Format("Error while downloading {0}'s submissions.", e.UserState));
                Logger.Add(ex.Message, "UserStat | webClient1_DownloadDataCompleted");
            }
            finally
            {
                LastUpdate = DateTime.Now;
            }
        }
コード例 #25
0
        private void ProgressChanged(Internet.DownloadTask task)
        {
            string file = Path.GetFileName(task.FileName);
            string text = string.Format("Downloading file : \"{0}\"... {1}% [{2} out of {3}] completed.",
                                        file, task.ProgressPercentage, Functions.FormatMemory(task.Received), Functions.FormatMemory(task.Total));

            Interactivity.SetStatus(text);
            Interactivity.SetProgress(task.Received, task.Total);
        }
コード例 #26
0
 private void submitButton_Click(object sender, EventArgs e)
 {
     if (current == null)
     {
         MessageBox.Show("Select a problem first.");
         return;
     }
     Interactivity.SubmitCode(current.pnum);
 }
コード例 #27
0
        public override void OnChooseGeneralReply(Room room, Interactivity client)
        {
            Player        player      = room.GetPlayers(client.ClientId)[0];
            List <string> options     = JsonUntity.Json2List <string>((string)player.GetTag("generals"));
            List <string> reply       = client.ClientReply;
            bool          success     = true;
            string        generalName = string.Empty;

            if (!client.IsClientResponseReady || reply == null || reply.Count == 0 || string.IsNullOrEmpty(reply[0]))
            {
                success = false;
            }
            else
            {
                generalName = reply[0];
                string[] generals = generalName.Split('+');
                if (generals.Length != 2)
                {
                    success = false;
                }
                else
                {
                    General general1 = Engine.GetGeneral(generals[0], "Hegemony");
                    General general2 = Engine.GetGeneral(generals[1], "Hegemony");
                    if (general1 == null || general1.Hidden || general2 == null || general2.Hidden ||
                        !room.Setting.GeneralPackage.Contains(general1.Package) ||
                        !room.Setting.GeneralPackage.Contains(general2.Package) ||
                        (!options.Contains(generals[0]) && room.GetClient(player).UserRight < 3) ||
                        (!options.Contains(generals[1]) && room.GetClient(player).UserRight < 3) ||
                        !SetPlayerGeneral(room, player, generals[0], true) ||
                        !SetPlayerGeneral(room, player, generals[1], false))
                    {
                        success = false;
                    }
                }
            }

            if (!success)
            {
                List <string> default_generals = GeneralSelctor.GeInstance().SelectGenerals(room, options);
                SetPlayerGeneral(room, player, default_generals[0], true);
                SetPlayerGeneral(room, player, default_generals[1], false);
            }

            if (!string.IsNullOrEmpty(player.General1))
            {
                string name    = player.General1;
                string kingdom = General.GetKingdom(Engine.GetGeneral(name, room.Setting.GameMode).Kingdom[0]);
                room.NotifyProperty(room.GetClient(player), player, "ActualGeneral1", name);
                room.NotifyProperty(room.GetClient(player), player, "Kingdom", kingdom);
            }
            if (!string.IsNullOrEmpty(player.General2))
            {
                room.NotifyProperty(room.GetClient(player), player, "ActualGeneral2", player.General2);
            }
        }
コード例 #28
0
        public async Task PlayerStatisticsAsync([Name("PlayerName")][Remainder] string name)
        {
            SendConstructionMessage();

            var players = await ScrapClient.GetPlayersByNameAsync(name, 10);

            await DeleteConstructionMessageAsync();

            if (players.Length == 0)
            {
                await ReplyAsync(embed : EmbedUtils.NotFoundEmbed("Player", name));

                return;
            }
            if (players.Length == 1)
            {
                var player = players[0];
                var team   = await player.GetTeamAsync();

                var member = team != null
                    ? await team.GetMemberAsync(player.Id)
                    : null;

                await ReplyAsync(embed : EmbedUtils.PlayerEmbed(player, team, member));

                return;
            }

            var sortedPlayers = players.OrderBy(x => x.Name).ToList();

            var selection = new MessageSelectionBuilder <Player>()
                            .WithSelectables(sortedPlayers.Take(12).ToArray())
                            .WithUsers(Context.User)
                            .WithTitle("Pick your player!")
                            .WithAllowCancel(false)
                            .WithDeletion(DeletionOptions.AfterCapturedContext | DeletionOptions.Valid)
                            .WithStringConverter(x => $"{x.Name} ({x.Trophies}:trophy:)")
                            .Build();

            var result = await Interactivity.SendSelectionAsync(selection, Context.Channel);

            if (result.IsCancelled || result.IsTimeouted)
            {
                return;
            }

            var selectedPlayer = result.Value;
            var selectedTeam   = await selectedPlayer.GetTeamAsync();

            var selectedMember = selectedTeam != null
                ? await selectedTeam.GetMemberAsync(selectedPlayer.Id)
                : null;

            await ReplyAsync(embed : EmbedUtils.PlayerEmbed(selectedPlayer, selectedTeam, selectedMember));
        }
コード例 #29
0
        private static void __DownloadProblemDatabaseProgress(DownloadTask task)
        {
            string msg = "Downloading problem list... [{0}/{1} completed]";

            msg = string.Format(msg, Functions.FormatMemory(task.Received), Functions.FormatMemory(task.Total));
            Interactivity.SetStatus(msg);

            int percent = task.ProgressPercentage;

            Interactivity.SetProgress(task.ProgressPercentage);
        }
コード例 #30
0
        private static void __DownloadCategoryIndexProgress(DownloadTask task)
        {
            string msg = msg = "Downloading category index... [{0}/{1} completed]";

            msg = string.Format(msg, Functions.FormatMemory(task.Received), Functions.FormatMemory(task.Total));
            Interactivity.SetStatus(msg);

            int percent = task.ProgressPercentage;

            Interactivity.SetProgress(task.ProgressPercentage);
        }
コード例 #31
0
ファイル: Plotter.cs プロジェクト: hakgagik/CRYLAB
 public void DrawDislocation()
 {
     if (isPaused) return;
     interactivity = Interactivity.Dislocation;
     rotationLocked = true;
     pointBuffer = new List<Vector3d>();
 }
コード例 #32
0
 private void RootGotFocus(object sender, Interactivity.RoutedEventArgs e)
 {
     UnmanagedMethods.SetFocus(_root.PlatformImpl.Handle.Handle);
 }