// //Submission Status Listview // private void AssignAspectFunctions() { subtimeSUB.AspectGetter = delegate(object row) { JudgeStatus last = (JudgeStatus)row; return(UnixTimestamp.FormatUnixTime(last.sbt)); }; lanSUB.AspectToStringConverter = delegate(object dat) { return(Functions.GetLanguage((Language)dat)); }; verSUB.AspectToStringConverter = delegate(object dat) { return(Functions.GetVerdict((Verdict)dat)); }; runSUB.AspectToStringConverter = delegate(object dat) { return(Functions.FormatRuntime((long)dat)); }; memSUB.AspectToStringConverter = delegate(object dat) { return(Functions.FormatMemory((long)dat)); }; rankSUB.AspectToStringConverter = delegate(object dat) { if ((long)dat == -1) { return("-"); } return(((long)dat).ToString()); }; }
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); } } }
/// <summary> /// 判定結果の表示 /// </summary> /// <param name="judge"></param> private void DispJudge(JudgeStatus judge) { switch (judge) { case JudgeStatus.Ready: labelJudge.Text = "Please Click [スタート] !"; labelJudge.ForeColor = Color.Tomato; break; case JudgeStatus.Start: labelJudge.Text = "G o G o !"; labelJudge.ForeColor = Color.White; break; case JudgeStatus.Pass: labelJudge.Text = "O K !"; labelJudge.ForeColor = Color.LawnGreen; break; case JudgeStatus.Fail: labelJudge.Text = "M i s s !"; labelJudge.ForeColor = Color.Magenta; break; case JudgeStatus.Clear: // 結果表示 labelJudge.Text = "C l e a r !"; labelJudge.ForeColor = Color.Aquamarine; break; } // その時点のメッセージを保管しておく CurrentJudgeMessage = labelJudge.Text; }
/// <summary> /// 判定結果の表示 /// </summary> /// <param name="judge"></param> private void DispJudge(JudgeStatus judge) { switch (judge) { case JudgeStatus.Start: labelJudge.Text = ""; labelJudge.ForeColor = Color.White; break; case JudgeStatus.Pass: labelJudge.Text = "O K !"; labelJudge.ForeColor = Color.LawnGreen; break; case JudgeStatus.Fail: labelJudge.Text = "M i s s !"; labelJudge.ForeColor = Color.Magenta; break; case JudgeStatus.Clear: labelJudge.Text = "C l e a r !"; labelJudge.ForeColor = Color.Aquamarine; break; } }
private async Task <bool> IsStatusCouldBeHacked(JudgeStatus status, ContestExecutorFactory cef, CancellationToken token) { if (User.IsSignedIn() && User.Current.Id == status.UserId) { return(false); } return(await IsStatusCodeCouldBeViewed(status, cef, token)); }
public override bool IsStatusHackable(JudgeStatus status) { var signedIn = User.IsSignedIn(); var hackStatus = DB.ContestProblemLastStatuses.FirstOrDefault(x => x.ContestId == ContestId && x.StatusId == status.Id && x.IsHackable); var statusIsHackable = hackStatus != null; var cpls = DB.ContestProblemLastStatuses.FirstOrDefault(x => x.ContestId == ContestId && x.UserId == User.Current.Id && x.ProblemId == status.ProblemId && x.IsLocked); var problemLocked = cpls != null; return(signedIn && statusIsHackable && problemLocked && (!cpls.IsVirtual && !hackStatus.IsVirtual || cpls.IsVirtual)); }
public override void OnJudgeCompleted(JudgeStatus status) { var attendee = DB.Attendees .Single(x => x.ContestId == status.ContestId && x.UserId == status.UserId); var cpls = DB.ContestProblemLastStatuses .Include(x => x.Status) .SingleOrDefault(x => x.ProblemId == status.ProblemId && x.UserId == status.UserId && x.ContestId == status.ContestId); var contestProblem = DB.ContestProblems.Single(x => x.ContestId == status.ContestId && x.ProblemId == status.ProblemId); var duration = ComputeTimeSpan(status.CreatedTime, status.UserId); var validTestCases = GetValidTestCasesAsync(status.ProblemId, status.UserId, default(CancellationToken)).Result; bool isHackable = false; if (validTestCases.Count() == 0) { isHackable = true; } else { isHackable = status.SubStatuses.Where(x => validTestCases.Contains(x.TestCaseId.Value)).Select(x => x.Result).Max() == JudgeResult.Accepted; } if (cpls == null) { cpls = new ContestProblemLastStatus { ProblemId = status.ProblemId, ContestId = status.ContestId, UserId = status.UserId, StatusId = status.Id, Point = status.Result == JudgeResult.Accepted ? CaculatePoint(contestProblem.Point, duration, 1) : 0, Point2 = 0, Point3 = 0, Point4 = 1, TimeSpan = duration, IsAccepted = status.Result == JudgeResult.Accepted, IsVirtual = attendee.IsVirtual, IsHackable = isHackable }; DB.ContestProblemLastStatuses.Add(cpls); } else { cpls.StatusId = status.Id; cpls.Point4++; cpls.Point = status.Result == JudgeResult.Accepted ? CaculatePoint(contestProblem.Point, ComputeTimeSpan(status.CreatedTime, status.UserId), cpls.Point4) : 0; cpls.TimeSpan = duration; cpls.IsAccepted = status.Result == JudgeResult.Accepted; cpls.IsHackable = isHackable; cpls.IsHacked = isHackable ? false : cpls.IsHacked; } DB.SaveChanges(); }
private void BindScores(JudgeStatus js) { ScoreType type = ScoreService.GetScoreType(js.Portfolio.Status); var list = from s in js.Portfolio.Scores where s.Type == type && s.Judge.Id == Judge.Id select s; totalScore = ScoreService.ComputeScore(Judge, js.Portfolio); gvScores.DataSource = list; gvScores.DataBind(); }
public override void OnShowJudgeResult(JudgeStatus status) { if (status.SubStatuses != null) { status.SubStatuses.Clear(); status.SubStatuses.Add(new SubJudgeStatus { Result = status.Result, SubId = 1, Hint = "ACM/ICPC 赛制不支持查看测试点详情" }); } }
private void LoadApplication() { JudgeStatus js = ScoreService.GetJudgeStatus(Id); lblName.Text = js.Portfolio.User.FullName; lblSchool.Text = js.Portfolio.School.Name; lblCategory.Text = js.Portfolio.Category.Name; lblStatus.Text = ScoreService.GetScoreType(js.Portfolio.Status).ToDescription(); lblRank.Text = js.Portfolio.Ranking.ToString(); lblPhase.Text = js.Phase.ToDescription(); BindScores(js); lnkPortfolio.NavigateUrl = "../ReportView.aspx?report=profile&id=" + js.Portfolio.Id.ToString(); }
protected void lnkBack_Click(object sender, EventArgs e) { UpdateScores(); DateTime dt = DateTime.Now; JudgeStatus js = ScoreService.GetJudgeStatus(Id); ScoreService.ComputeTotalScore(js.Portfolio); TimeSpan ts = DateTime.Now - dt; log.Debug("ComputeTotalScore took: " + ts.ToString()); ScoreService.ComputeRanking(js.Portfolio.Status, js.Portfolio.Category, js.Judge.Area); ts = DateTime.Now - dt; log.Debug("ComputeRanking took: " + ts.ToString()); Response.Redirect("~/Judge/Default.aspx"); }
protected void btnShowPortfolio_OnClick(object sender, EventArgs e) { JudgeStatus js = ScoreService.GetJudgeStatus(Id); if (ShowPdf1.Visible) { ShowPdf1.Visible = false; btnShowPortfolio.Text = "Show Portfolio"; } else { btnShowPortfolio.Text = "Hide Portfolio"; ShowPdf1.Visible = true; ShowPdf1.FilePath = "../ReportView.aspx?report=profile&id=" + js.Portfolio.Id.ToString(); } }
public override void OnShowJudgeResult(JudgeStatus status) { if (status.SubStatuses != null) { status.SubStatuses.Clear(); status.SubStatuses.Add(new SubJudgeStatus { Result = JudgeResult.Hidden, SubId = 1 }); } status.Hint = "You can not view the result now."; status.Result = JudgeResult.Hidden; status.TimeUsedInMs = 0; status.MemoryUsedInByte = 0; }
public void SetStatus(JudgeStatus status) { if (SIDtoStatus.ContainsKey(status.sid)) { if (status.id > SIDtoStatus[status.sid].id) { StatusList.Remove(SIDtoStatus[status.sid]); SIDtoStatus[status.sid] = status; StatusList.Add(status); } } else { StatusList.Add(status); SIDtoStatus.Add(status.sid, status); } }
protected void gvNominees_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { for (int i = 0; i < e.Row.Cells.Count; i++) { DataControlFieldHeaderCell obj = (DataControlFieldHeaderCell)e.Row.Cells[i]; if (!String.IsNullOrEmpty(this.SortColumn) && obj.ContainingField.SortExpression == this.SortColumn) { GridHelper.AddSortImage(obj, SortDirection); } } } if (e.Row.RowType == DataControlRowType.DataRow) { JudgeStatus js = e.Row.DataItem as JudgeStatus; if (null != js) { Label labStatus = e.Row.FindControl("labStatus") as Label; Label labScore = e.Row.FindControl("labScore") as Label; Label labTotalScore = e.Row.FindControl("labTotalScore") as Label; Label labRanking = e.Row.FindControl("labRanking") as Label; HyperLink btnScores = e.Row.FindControl("btnScores") as HyperLink; labStatus.Text = js.Phase.ToDescription(); labScore.Text = js.Score.ToString("F"); labTotalScore.Text = js.Portfolio.TotalScore.ToString("F"); labRanking.Text = js.Portfolio.Ranking.ToString(); if (js.Score == 0) { labScore.ForeColor = System.Drawing.Color.Red; } else { //labStatus.Text = js.Application.Status.ToDescription(); labScore.Text = ScoreService.ComputeScore(Judge, js.Portfolio).ToString("F"); } //labScore.Attributes.Add("onmouseover", "tooltip.show('" + GetOtherScores(js.Application) + "');"); //labScore.Attributes.Add("onmouseout", "tooltip.hide();"); btnScores.Visible = !js.Submitted; } } }
public override void OnJudgeCompleted(JudgeStatus status) { var attendee = DB.Attendees .Single(x => x.ContestId == status.ContestId && x.UserId == status.UserId); var cpls = DB.ContestProblemLastStatuses .Include(x => x.Status) .SingleOrDefault(x => x.ProblemId == status.ProblemId && x.UserId == status.UserId && x.ContestId == status.ContestId); if (cpls != null && cpls.Status.Result == JudgeResult.Accepted || status.Result == JudgeResult.CompileError || status.Result == JudgeResult.SystemError) { return; } var contestProblem = DB.ContestProblems.Single(x => x.ContestId == status.ContestId && x.ProblemId == status.ProblemId); if (cpls == null) { cpls = new ContestProblemLastStatus { ProblemId = status.ProblemId, ContestId = status.ContestId, UserId = status.UserId, StatusId = status.Id, Point = status.Result == JudgeResult.Accepted ? 1 : 0, Point3 = status.Result == JudgeResult.Accepted ? 0 : 1, TimeSpan = status.Result == JudgeResult.Accepted ? ComputeTimeSpan(status.CreatedTime, status.UserId) : default(TimeSpan), IsAccepted = status.Result == JudgeResult.Accepted, IsVirtual = attendee.IsVirtual }; DB.ContestProblemLastStatuses.Add(cpls); } else { cpls.StatusId = status.Id; cpls.Point = status.Result == JudgeResult.Accepted ? 1 : 0; cpls.Point3 += status.Result == JudgeResult.Accepted ? 0 : 1; cpls.TimeSpan = status.Result == JudgeResult.Accepted ? ComputeTimeSpan(status.CreatedTime, status.UserId).Add(new TimeSpan(0, 20 * cpls.Point3, 0)) : default(TimeSpan); cpls.IsAccepted = status.Result == JudgeResult.Accepted; } DB.SaveChanges(); }
private string GetOtherScores(Portfolio portfolio) { StringBuilder html = new StringBuilder("<table><tr><th colspan=\"2\">Judges Scores</th></tr>"); IList <Judge> judges = ScoreService.GetJudgesByCategory(Judge, Judge.Category); if (judges.Count == 0) { html.Append("<tr><td>No other judges found</td></tr>"); } foreach (Judge j in judges) { JudgeStatus js = ScoreService.GetJudgeStatus(j, portfolio); if (null != js) { html.Append(string.Format("<tr><td>{0:s}</td><td align=\"right\"> {1:F}</td></tr>", j.User.FullName, js.Score)); } } html.Append("</table>"); return(html.ToString()); }
public static string Translate(this JudgeStatus value) { switch (value) { case JudgeStatus.Available: return("Aktiv"); case JudgeStatus.OnLeave: return("Beurlaubt"); case JudgeStatus.Resigned: return("Zurück- oder Ausgetreten"); case JudgeStatus.Unavailable: return("Inaktiv oder unerreichbar"); default: throw new InvalidOperationException(); } }
public override void OnJudgeCompleted(JudgeStatus status) { var attendee = DB.Attendees .Single(x => x.ContestId == status.ContestId && x.UserId == status.UserId); var cpls = DB.ContestProblemLastStatuses .Include(x => x.Status) .SingleOrDefault(x => x.ProblemId == status.ProblemId && x.UserId == status.UserId && x.ContestId == status.ContestId); if (cpls != null && status.CreatedTime <= cpls.Status.CreatedTime) { return; } var contestProblem = DB.ContestProblems.Single(x => x.ContestId == status.ContestId && x.ProblemId == status.ProblemId); if (cpls == null) { cpls = new ContestProblemLastStatus { ProblemId = status.ProblemId, ContestId = status.ContestId, UserId = status.UserId, StatusId = status.Id, Point = status.SubStatuses == null ? 0 : status.SubStatuses.Count(x => x.Result == JudgeResult.Accepted) * contestProblem.Point / status.SubStatuses.Count, Point3 = 1, IsAccepted = status.Result == JudgeResult.Accepted, IsVirtual = attendee.IsVirtual }; DB.ContestProblemLastStatuses.Add(cpls); } else { cpls.StatusId = status.Id; cpls.Point = status.SubStatuses == null ? 0 : status.SubStatuses.Count(x => x.Result == JudgeResult.Accepted) * contestProblem.Point / status.SubStatuses.Count; cpls.Point3++; cpls.IsAccepted = status.Result == JudgeResult.Accepted; } DB.SaveChanges(); }
protected void lvScores_ItemDataBound(object sender, ListViewItemEventArgs e) { ListViewDataItem dataItem = (ListViewDataItem)e.Item; if (e.Item.ItemType == ListViewItemType.DataItem) { JudgeStatus js = dataItem.DataItem as JudgeStatus; Label lblName = e.Item.FindControl("lblName") as Label; Label labStatus = e.Item.FindControl("labStatus") as Label; Label labScore = e.Item.FindControl("labScore") as Label; Label labSubmitted = e.Item.FindControl("labSubmitted") as Label; lblName.Text = js.Judge.User.FullName; labStatus.Text = js.Phase.ToDescription(); labScore.Text = js.Score.ToString("F"); labSubmitted.Text = (js.Submitted) ? "Yes" : "No"; if (!js.Submitted) { labSubmitted.ForeColor = System.Drawing.Color.Red; labScore.ForeColor = System.Drawing.Color.Red; } } }
public override void OnShowJudgeResult(JudgeStatus status) { if (IsContestInProgress(status.User.UserName) || IsContestInProgress(User.Current?.UserName)) { var testCases = GetValidTestCasesAsync(status.ProblemId, status.UserId, default(CancellationToken)).Result; var hack = DB.HackStatuses.FirstOrDefault(x => x.ContestId == ContestId && x.JudgeStatusId == status.Id && x.Result == HackResult.Succeeded); status.SubStatuses = DB.SubJudgeStatuses .Where(x => x.StatusId == status.Id) .Where(x => testCases.Contains(x.TestCase.Id)) .ToList(); foreach (var x in status.SubStatuses) { x.Hint = "Codeforces赛制不提供详细测试点信息"; } status.Result = status.SubStatuses.Max(x => x.Result); status.TimeUsedInMs = status.SubStatuses.Sum(x => x.TimeUsedInMs); status.MemoryUsedInByte = status.SubStatuses.Max(x => x.MemoryUsedInByte); } }
private async Task <bool> IsStatusCodeCouldBeViewed(JudgeStatus status, ContestExecutorFactory cef, CancellationToken token) { if (!User.IsSignedIn() || status.IsSelfTest) { return(false); } if (!string.IsNullOrEmpty(status.ContestId)) { var ce = cef.Create(status.ContestId); if (ce.IsContestInProgress(status.User.UserName) || ce.IsContestInProgress(User.Current?.UserName)) { return(ce.IsStatusHackable(status)); } } if (Constants.HackInvalidResults.Contains(status.Result)) { return(false); } return(await DB.JudgeStatuses.AnyAsync(x => x.UserId == User.Current.Id && x.ProblemId == status.ProblemId && string.IsNullOrEmpty(x.ContestId) && x.Result == JudgeResult.Accepted, token)); }
public override void OnShowJudgeResult(JudgeStatus status) { }
public virtual void OnJudgeCompleted(JudgeStatus status) { throw new NotImplementedException(); }
private void submissionStatus_FormatCell(object sender, BrightIdeasSoftware.FormatCellEventArgs e) { string font = "Segoe UI"; float size = 9.0F; FontStyle style = FontStyle.Regular; Color fore = Color.Black; //highlight item JudgeStatus js = (JudgeStatus)e.Model; if (js.uname == RegistryAccess.DefaultUsername) { for (int i = 0; i < e.Item.SubItems.Count; ++i) { e.Item.SubItems[i].BackColor = Color.Turquoise; } } else if (LocalDatabase.ContainsUser(js.uname)) { for (int i = 0; i < e.Item.SubItems.Count; ++i) { e.Item.SubItems[i].BackColor = Color.LightBlue; } } //highlight other if (e.Column == sidSUB) { font = "Consolas"; fore = Color.Teal; size = 8.5F; } else if (e.Column == unameSUB) { fore = Color.Navy; style = FontStyle.Italic; } else if (e.Column == fullnameSUB) { font = "Segoe UI Semibold"; } else if (e.Column == pnumSUB) { font = "Consolas"; fore = Color.Navy; style = FontStyle.Italic; } else if (e.Column == ptitleSUB) { font = "Segoe UI Semibold"; fore = Functions.GetProblemTitleColor(js.pnum); } else if (e.Column == runSUB) { fore = Color.SlateBlue; } else if (e.Column == memSUB) { font = "Consolas"; fore = Color.Blue; size = 8.5F; } else if (e.Column == subtimeSUB) { fore = Color.Maroon; } else if (e.Column == rankSUB) { fore = Color.Navy; font = "Segoe UI Semibold"; } else if (e.Column == verSUB) { font = "Segoe UI"; fore = Functions.GetVerdictColor(js.ver); style = FontStyle.Bold; } else if (e.Column == lanSUB) { style = FontStyle.Bold; fore = Color.Navy; } else { return; } e.SubItem.ForeColor = fore; e.SubItem.Font = new Font(font, size, style); }
private async Task HandleSingleHackAsync(IEnumerable <ActorInfo> actors, HackStatus hack, JudgeStatus judge, Problem problem, Guid?testCaseId, CancellationToken token) { var sub = new SubJudgeStatus(); var isBadData = false; if (actors.Count(x => x.Name == "CompareActor") == 0) { var rangeValidateActor = actors.FirstOrDefault(x => x.Stage == "ValidateData"); var rangeRunner = rangeValidateActor == null ? null : await _mgmt.ReadBlobAsObjectAsync <Runner>(rangeValidateActor.Outputs.Single(x => x.Name == "runner.json").Id, token); var runActor = actors.FirstOrDefault(x => x.Stage == "GenerateHackeeAnswer"); var runRunner = runActor == null ? null : await _mgmt.ReadBlobAsObjectAsync <Runner>(runActor.Outputs.Single(x => x.Name == "runner.json").Id, token); if (rangeRunner != null && rangeRunner.ExitCode != 0) { isBadData = true; sub.TimeUsedInMs = 0; sub.MemoryUsedInByte = 0; sub.Result = JudgeResult.Accepted; sub.Hint = string.Join(Environment.NewLine, rangeValidateActor.Exceptions) + Environment.NewLine + rangeRunner.Error; } else if (runRunner.IsTimeout) { sub.TimeUsedInMs = problem.TimeLimitationPerCaseInMs; sub.MemoryUsedInByte = runRunner.PeakMemory; sub.Result = JudgeResult.TimeExceeded; sub.Hint = string.Join(Environment.NewLine, runActor.Exceptions) + Environment.NewLine + runRunner.Error; } else if (runRunner.ExitCode == 139 || runActor.Exceptions.Any(x => x.Contains("May cause by out of memory")) || runRunner.Error.Contains("std::bad_alloc") || runRunner.PeakMemory > problem.MemoryLimitationPerCaseInByte) { sub.TimeUsedInMs = runRunner.UserTime; sub.MemoryUsedInByte = problem.MemoryLimitationPerCaseInByte; sub.Result = JudgeResult.MemoryExceeded; sub.Hint = string.Join(Environment.NewLine, runActor.Exceptions) + Environment.NewLine + runRunner.Error; } else if (runRunner.ExitCode != 0) { sub.TimeUsedInMs = runRunner.UserTime; sub.MemoryUsedInByte = runRunner.PeakMemory; sub.Result = JudgeResult.RuntimeError; sub.Hint = string.Join(Environment.NewLine, runActor.Exceptions) + Environment.NewLine + runRunner.Error + Environment.NewLine + $"User process exited with code { runRunner.ExitCode }"; } } else if (actors.Count(x => x.Name == "CompareActor") > 0) { var runners = actors.Where(x => x.Name == "CompareActor").Select(x => x.Outputs.Single(y => y.Name == "runner.json")); var runnerResults = runners.Select(x => _mgmt.ReadBlobAsObjectAsync <Runner>(x.Id, token).Result); var exitCodes = runnerResults.Select(x => x.ExitCode); if (exitCodes.Distinct().Count() > 1) { isBadData = true; } else { var runActor = actors.First(x => x.Stage == "GenerateHackeeAnswer"); var runRunner = await _mgmt.ReadBlobAsObjectAsync <Runner>(runActor.Outputs.Single(x => x.Name == "runner.json").Id, token); var compareActor = actors.Last(x => x.Name == "CompareActor"); var runner = await _mgmt.ReadBlobAsObjectAsync <Runner>(compareActor.Outputs.Single(x => x.Name == "runner.json").Id, token); if (runner.ExitCode < 0 || runner.ExitCode > 2) { sub.TimeUsedInMs = 0; sub.MemoryUsedInByte = 0; sub.Result = JudgeResult.SystemError; sub.Hint = string.Join(Environment.NewLine, runActor.Exceptions) + Environment.NewLine + runner.Error; } else { var validatorOutput = Encoding.UTF8.GetString((await _mgmt.GetBlobAsync(compareActor.Outputs.Single(x => x.Name == "stdout.txt").Id)).Body); sub.TimeUsedInMs = runRunner.UserTime; sub.MemoryUsedInByte = runRunner.PeakMemory; sub.Result = (JudgeResult)runner.ExitCode; sub.Hint = validatorOutput + Environment.NewLine + string.Join(Environment.NewLine, runActor.Exceptions) + Environment.NewLine + runner.Error; } } } else { isBadData = true; } if (hack == null && actors.Count(x => x.Stage == "GenerateHackeeAnswer") > 0 && testCaseId.HasValue) { var runActor = actors.First(x => x.Stage == "GenerateHackeeAnswer"); var statusId = Guid.Parse(runActor.Tag); var testCase = await _db.TestCases.SingleAsync(x => x.Id == testCaseId.Value, token); var testCases = await _db.TestCases .Where(x => x.ProblemId == problem.Id) .Select(x => x.Id) .ToListAsync(token); var status = await _db.JudgeStatuses .Include(x => x.SubStatuses) .SingleAsync(x => x.Id == statusId, token); sub.StatusId = statusId; sub.TestCaseId = testCaseId.Value; sub.InputBlobId = testCase.InputBlobId; sub.OutputBlobId = testCase.OutputBlobId; sub.SubId = testCases.IndexOf(testCaseId.Value); status.SubStatuses.Add(sub); status.MemoryUsedInByte = status.SubStatuses.Max(x => x.MemoryUsedInByte); status.TimeUsedInMs = status.SubStatuses.Sum(x => x.TimeUsedInMs); status.Result = status.SubStatuses.Max(x => x.Result); _db.SaveChanges(); } if (hack != null) { _db.HackStatuses .Where(x => x.Id == hack.Id) .SetField(x => x.HackeeResult).WithValue(isBadData ? JudgeResult.Accepted : sub.Result) .SetField(x => x.TimeUsedInMs).WithValue(sub.TimeUsedInMs) .SetField(x => x.MemoryUsedInByte).WithValue(sub.MemoryUsedInByte) .SetField(x => x.Result).WithValue(isBadData ? (HackResult.BadData) : (sub.Result == JudgeResult.Accepted ? HackResult.Failed : HackResult.Succeeded)) .SetField(x => x.Hint).WithValue(sub.Hint) .Update(); } }
public SolveStatus SolveProblem(int problemID, int maxRetry) { WriteMessage(string.Format("正在自动AC{0}的{1}题目", client.OJName, problemID)); SolveStatus solveStatus; solveStatus.Solved = false; solveStatus.Detail = "UnknownError"; solveStatus.Code = "已AC,无需爬取,因此无代码"; if (client.IsAccepted(problemID, Username))//题目已经AC { solveStatus.Solved = true; solveStatus.Detail = "AlreadyAccepted"; return(solveStatus); } int retryCount = 0; //尝试次数 while (!client.IsAvailable(problemID)) //问题是否可用 { if (++retryCount >= 3) { solveStatus.Detail = "ProblemNotFound"; return(solveStatus); } } WriteMessage("正在爬取题目代码"); List <string> articlesList = crawler.GetACArticleLinks(problemID, client.OJName);//抓取题解链接 List <string> acCodeList = new List <string>(); foreach (string artLink in articlesList)//抓取题解代码 { string code = crawler.GetCodeByArticleLink(artLink, problemID, client.OJName); if (!string.IsNullOrEmpty(code)) { acCodeList.Add(code); } } if (articlesList.Count == 0 || acCodeList.Count == 0)//无代码 { solveStatus.Detail = "AcCodeNotFound"; return(solveStatus); } WriteMessage("共爬取到" + acCodeList.Count.ToString() + "份代码"); JudgeStatus status = JudgeStatus.Unknown; foreach (string code in acCodeList) //尝试所有代码,直到AC为止 { if (maxRetry-- <= 0) //最大尝试次数 { solveStatus.Detail = "RetryLimitExceeded"; WriteMessage("超出最大尝试次数"); return(solveStatus); } WriteMessage(maxRetry.ToString()); WriteMessage(string.Format("正在提交题目{0},代码长度{1}", problemID, code.Length)); retryCount = 0; while (!client.Submit(problemID, code)) { if (++retryCount >= 3) { continue; } } WriteMessage("正在取回判题结果"); System.Threading.Thread.Sleep(6000);//提交后先等待 status = client.GetJudgeStatus(problemID, Username); while (status == JudgeStatus.Queuing || status == JudgeStatus.Compiling || status == JudgeStatus.Running) { status = client.GetJudgeStatus(problemID, Username); System.Threading.Thread.Sleep(2000); } WriteMessage(string.Format("OJ:{0}\tProblemID:{1}\tResult:{2}", client.OJName, problemID, status)); if (status == JudgeStatus.Accepted) { solveStatus.Solved = true; solveStatus.Detail = "Accepted"; solveStatus.Code = Regex.Replace(code, "\r\n|\r|\n", Environment.NewLine); return(solveStatus); } else { solveStatus.Detail = status.ToString(); } } return(solveStatus); }
/// <summary> /// 筛选给定的评测状态。 /// </summary> /// <param name="status">要筛选的评测状态。</param> public SubmissionFilterBuilder Status(JudgeStatus status) { AddFilter(Builders <Submission> .Filter.Eq(s => s.Status, status)); return(this); }
public virtual void OnShowJudgeResult(JudgeStatus status) { }
public async Task <IActionResult> Put( [FromServices] IConfiguration Config, [FromServices] IServiceScopeFactory scopeFactory, [FromServices] StateMachineAwaiter awaiter, [FromServices] ManagementServiceClient MgmtSvc, [FromServices] IHubContext <OnlineJudgeHub> hub, [FromServices] ContestExecutorFactory cef, CancellationToken token) { var request = JsonConvert.DeserializeObject <JudgeRequest>(RequestBody); var problem = await DB.Problems .Include(x => x.TestCases) .SingleOrDefaultAsync(x => x.Id == request.problemId, token); if (problem == null) { return(Result(400, "The problem is not exist.")); } if (!problem.IsVisible && string.IsNullOrWhiteSpace(request.contestId) && !await HasPermissionToProblemAsync(problem.Id, token)) { return(Result(403, "You have no permission to the problem.")); } if (IsGroupRequest() && !await IsGroupMemberAsync(token)) { return(Result(401, "You are not a member of this group.")); } if (!Constants.SupportedLanguages.Contains(request.language)) { return(Result(400, "The language has not been supported.")); } if (string.IsNullOrEmpty(request.code)) { return(Result(400, "Code could not be empty.")); } if (!string.IsNullOrEmpty(request.contestId)) { var ce = cef.Create(request.contestId); if (!ce.IsContestInProgress(User.Current?.UserName)) { return(Result(400, "The contest is inactive.")); } if (request.isSelfTest) { return(Result(400, "You could not do a self test during the contest is in progress.")); } if (await DB.ContestProblemLastStatuses.AnyAsync(x => x.IsLocked && x.ContestId == request.contestId && User.Current.Id == x.UserId && x.ProblemId == request.problemId, token)) { return(Result(400, "You have locked this problem.")); } } if (!Constants.SupportedLanguages.Contains(request.language) && !Constants.UnsupportedLanguages.Contains(request.language) && problem.Source == ProblemSource.Local) { return(Result(400, "The programming language which you selected was not supported")); } if (request.isSelfTest && request.data.Count() == 0) { return(Result(400, "The self testing data has not been found")); } if (problem.Source != ProblemSource.Local && request.isSelfTest) { return(Result(400, "You could not use self data to test with a remote problem.")); } if (IsGroupRequest() && !await DB.GroupProblems.AnyAsync(x => x.ProblemId == problem.Id && x.GroupId == CurrentGroup.Id) && string.IsNullOrEmpty(request.contestId)) { return(Result(404, "The problem does not exist.")); } #region Local Judge if (problem.Source == ProblemSource.Local) { var blobs = new ConcurrentDictionary <int, BlobInfo[]>(); blobs.TryAdd(-1, new[] { new BlobInfo { Id = await MgmtSvc.PutBlobAsync("Main" + Constants.GetSourceExtension(request.language), Encoding.UTF8.GetBytes(request.code)), Name = "Main" + Constants.GetSourceExtension(request.language), Tag = "Problem=" + problem.Id } }); blobs.TryAdd(-2, new[] { new BlobInfo { Id = await MgmtSvc.PutBlobAsync("limit.json", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { UserTime = problem.TimeLimitationPerCaseInMs, PhysicalTime = problem.TimeLimitationPerCaseInMs * 4, Memory = problem.MemoryLimitationPerCaseInByte }))), Name = "limit.json", Tag = "Problem=" + problem.Id } }); if (!problem.ValidatorBlobId.HasValue) { blobs.TryAdd(-3, new[] { new BlobInfo { Id = Guid.Parse(Config["JoyOI:StandardValidatorBlobId"]), Name = "Validator.out" } }); } else { blobs.TryAdd(-3, new[] { new BlobInfo { Id = problem.ValidatorBlobId.Value, Name = "Validator" + Constants.GetBinaryExtension(problem.ValidatorLanguage) } }); } List <TestCase> testCases = null; if (request.isSelfTest) { Parallel.For(0, request.data.Count(), i => { // Uploading custom data var inputId = MgmtSvc.PutBlobAsync($"input_{ i }.txt", Encoding.UTF8.GetBytes(request.data.ElementAt(i).input), token).Result; var outputId = MgmtSvc.PutBlobAsync($"output_{ i }.txt", Encoding.UTF8.GetBytes(request.data.ElementAt(i).output), token).Result; blobs.TryAdd(i, new[] { new BlobInfo { Id = inputId, Name = $"input_{ i }.txt", Tag = i.ToString() }, new BlobInfo { Id = outputId, Name = $"output_{ i }.txt", Tag = i.ToString() } }); }); } else { testCases = await DB.TestCases .Where(x => x.ProblemId == problem.Id && (x.Type == TestCaseType.Small || x.Type == TestCaseType.Large || x.Type == TestCaseType.Hack)) .ToListAsync(token); if (testCases.Count == 0) { return(Result(400, "No test case found.")); } for (var i = 0; i < testCases.Count; i++) { blobs.TryAdd(i, new[] { new BlobInfo { Id = testCases[i].InputBlobId, Name = $"input_{ i }.txt", Tag = i.ToString() }, new BlobInfo { Id = testCases[i].OutputBlobId, Name = $"output_{ i }.txt", Tag = i.ToString() } }); } } var stateMachineId = await MgmtSvc.PutStateMachineInstanceAsync("JudgeStateMachine", Config["ManagementService:CallBack"], blobs.SelectMany(x => x.Value), await CalculatePriorityAsync(), token); var substatuses = blobs .Where(x => x.Key >= 0) .Select(x => new SubJudgeStatus { SubId = x.Key, Result = JudgeResult.Pending, InputBlobId = x.Value.Single(y => y.Name.StartsWith("input_")).Id, OutputBlobId = x.Value.Single(y => y.Name.StartsWith("output_")).Id, TestCaseId = testCases != null ? (Guid?)testCases[x.Key].Id : null }) .ToList(); var status = new JudgeStatus { Code = request.code, Language = request.language, Result = JudgeResult.Pending, CreatedTime = DateTime.UtcNow, ContestId = request.contestId, SubStatuses = substatuses, ProblemId = problem.Id, UserId = User.Current.Id, IsSelfTest = request.isSelfTest, RelatedStateMachineIds = new List <JudgeStatusStateMachine> { new JudgeStatusStateMachine { StateMachine = new StateMachine { CreatedTime = DateTime.UtcNow, Name = "JudgeStateMachine", Id = stateMachineId }, StateMachineId = stateMachineId } }, }; if (IsGroupRequest()) { status.GroupId = CurrentGroup.Id; } DB.JudgeStatuses.Add(status); await DB.SaveChangesAsync(token); hub.Clients.All.InvokeAsync("ItemUpdated", "judge", status.Id); // For debugging if (Config["ManagementService:Mode"] == "Polling") { Task.Factory.StartNew(async() => { using (var scope = scopeFactory.CreateScope()) using (var db = scope.ServiceProvider.GetService <OnlineJudgeContext>()) { try { await awaiter.GetStateMachineResultAsync(stateMachineId); var handler = scope.ServiceProvider.GetService <JudgeStateMachineHandler>(); await handler.HandleJudgeResultAsync(stateMachineId, default(CancellationToken)); } catch (Exception ex) { Console.Error.WriteLine(ex); } } }); } return(Result(status.Id)); } #endregion #region Bzoj, LeetCode, CodeVS else if (problem.Source == ProblemSource.Bzoj || problem.Source == ProblemSource.LeetCode || problem.Source == ProblemSource.CodeVS) { var metadata = new { Source = problem.Source.ToString(), Language = request.language, Code = request.code, ProblemId = problem.Id.Replace(problem.Source.ToString().ToLower() + "-", "") }; var metadataBlob = new BlobInfo { Id = await MgmtSvc.PutBlobAsync("metadata.json", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metadata)), token), Name = "metadata.json", Tag = "Problem=" + problem.Id }; var stateMachineId = await MgmtSvc.PutStateMachineInstanceAsync("VirtualJudgeStateMachine", Config["ManagementService:Callback"], new[] { metadataBlob }, await CalculatePriorityAsync(), token); var status = new JudgeStatus { Code = request.code, ContestId = request.contestId, Language = request.language, ProblemId = problem.Id, IsSelfTest = false, UserId = User.Current.Id, Result = JudgeResult.Pending, RelatedStateMachineIds = new List <JudgeStatusStateMachine> { new JudgeStatusStateMachine { StateMachine = new StateMachine { CreatedTime = DateTime.UtcNow, Name = "JudgeStateMachine", Id = stateMachineId }, StateMachineId = stateMachineId } } }; if (IsGroupRequest()) { status.GroupId = CurrentGroup.Id; } DB.JudgeStatuses.Add(status); await DB.SaveChangesAsync(token); // For debugging if (Config["ManagementService:Mode"] == "Polling") { Task.Factory.StartNew(async() => { using (var scope = scopeFactory.CreateScope()) { try { await awaiter.GetStateMachineResultAsync(stateMachineId); var handler = scope.ServiceProvider.GetService <JudgeStateMachineHandler>(); await handler.HandleJudgeResultAsync(stateMachineId, default(CancellationToken)); } catch (Exception ex) { Console.Error.WriteLine(ex); } } }); } hub.Clients.All.InvokeAsync("ItemUpdated", "judge", status.Id); return(Result(status.Id)); } #endregion #region Others else { throw new NotSupportedException(problem.Source.ToString() + " has not been supported yet."); } #endregion }