Example #1
0
def viewProblem(request, *args, **kwargs):
    problem = Problem.get(kwargs.get('id'))
    user = User.getCurrent(request)

    contest = Contest.getCurrent()

    if not problem:
        return JsonResponse(data='', safe=False)

    if not user.isAdmin():
        # Hide the problems till the contest begins for non-admin users
        if not Contest.getCurrent():
            return JsonResponse(data='', safe=False)
        if problem not in Contest.getCurrent().problems:
            return JsonResponse(data='', safe=False)
    contents = []
    if contest == None or contest.showProblInfoBlocks == "On":
        contents = [
            Card("Problem Statement", formatMD(problem.statement), cls="stmt"),
            Card("Input Format", formatMD(problem.input), cls="inp"),
            Card("Output Format", formatMD(problem.output), cls="outp"),
            Card("Constraints",
                 formatMD(problem.constraints),
                 cls="constraints"),
        ]
    contents.append(
        div(cls="samples",
            contents=list(
                map(lambda x: getSample(x[0], x[1]),
                    zip(problem.sampleData, range(problem.samples))))))

    return HttpResponse(
        Page(
            h.input(type="hidden", id="problem-id", value=problem.id),
            h2(problem.title, cls="page-title"),
            div(cls="problem-description", contents=contents), CodeEditor(),
            div(cls="stmt card ui-sortable-handle blk-custom-input",
                contents=[
                    div(cls="card-header",
                        contents=[h2("Custom Input", cls="card-title")]),
                    div(cls="card-contents",
                        contents=[h.textarea(id="custom-input", cls="col-12")])
                ]),
            div(cls="align-right",
                id="custom-code-text",
                contents=[
                    h.input("Custom Input",
                            type="checkbox",
                            id="use-custom-input"),
                    h.button("Test Code",
                             cls="button test-samples button-white"),
                    h.button("Submit Code", cls="button submit-problem")
                ])))
def getSubmissions(request, *args, **kwargs):
    submissions = []

    cont = Contest.getCurrent()
    if not cont:
        return HttpResponse(
            Page(h1(" "), h1("Contest is Over", cls="center")))

    user = User.getCurrent(request)
    Submission.forEach(lambda x: submissions.append(x) if x.user.id == user.id
                       and cont.start <= x.timestamp <= cont.end else None)
    if len(submissions) == 0:
        return HttpResponse(Page(h1("No Submissions Yet", cls="page-title"), ))
    return HttpResponse(
        Page(
            h2("Your Submissions", cls="page-title"),
            SubmissionTable(
                sorted(submissions,
                       key=lambda sub: (sub.problem.title, -sub.timestamp))),
            div(cls="modal",
                tabindex="-1",
                role="dialog",
                contents=[
                    div(cls="modal-dialog",
                        role="document",
                        contents=[div(id="modal-content")])
                ])))
Example #3
0
def getUsers(request):
    userLists = []
    tmp = []

    for user in User.all():
        tmp.append(user)
        if len(tmp) == 16:
            userLists.append(tmp)
            tmp = []

    if tmp != []:
        userLists.append(tmp)

    users = []
    for lst in userLists:
        users.append(div(*map(UserCard, lst), cls="page-break row"))

    return HttpResponse(
        Page(
            h2("Users", cls="page-title"),
            div(cls="actions",
                contents=[
                    h.button("+ Create Admin",
                             cls="button button-blue create-admin",
                             onclick="createUser('admin')"),
                    h.button("+ Create Participant",
                             cls="button create-participant",
                             onclick="createUser('participant')")
                ]), div(cls="user-cards", contents=users)))
Example #4
0
def setup(request, *args, **kwargs):
    return HttpResponse(Page(
        h2("Setup", cls="page-title"),
        Card("Problems", "Create problems to go in the contests", "/problems_mgmt"),
        Card("Contests", "Create contests", "/contests"),
        Card("Users", "Create users who will participate in contests, as well as other admin users who can create and judge contests and problems", "/users")
    ))
Example #5
0
def judge(request):
    cont = Contest.getCurrent() or Contest.getPast()
    if not cont:
        return HttpResponse(
            Page(h1("&nbsp;"), h1("No Contest Available", cls="center")))
    return HttpResponse(
        Page(
            h2("Judge Submissions", cls="page-title judge-width"),
            div(cls="actions",
                contents=[
                    h.button("Reset Filter",
                             cls="button",
                             onclick="resetJudgeFilter()"),
                ]),
            div(id="judge-table",
                cls="judge-width",
                contents=[SubmissionTable(cont)]),
            div(cls="modal",
                tabindex="-1",
                role="dialog",
                contents=[
                    div(cls="modal-dialog",
                        role="document",
                        contents=[div(id="modal-content")])
                ]),
            cls='wide-content'  # Use a wide format for this page
        ))
Example #6
0
def about(request):
    return HttpResponse(Page(
        h2("About", cls="page-title"),
        Card("The Creator", """
        OpenContest was written by Nathan Collins, a senior computer science student at BJU,
        as an independent study project in the fall of 2018.
        """),
        Card("Enhancements", """
        Dr. Schaub's Internet Application Development class added several features in the
        spring of 2019. The following students contributed enhancements:
        <ul>
        <li>Andrew Avinante, Carter Shean, Zac Hayes, and Robert Meyer contributed additional reports.</li>
        <li>Noah Mansfield contributed the Auto Rejudge.</li>
        <li>Ryan Longacre and Levi Lohmeyer contributed bug fixes.</li>
        <li>Zac Hayes implemented the judge review queue.</li>
        <li>Robert Meyer contributed the test with custom input feature.</li>
        <li>Cole Stegall contributed the initial judge diff view.</li>
        <li>Tim Kephart enhanced the autojudge and contributed the submission download feature.</li>
        <li>Michael Bruno implemented per-problem time limits.</li>
        <li>Michael Johannes implemented configurable problem information blocks.</li>
        <li>Heather East Duke ported the system to the Django framework.</li>
        <li>Caedmon Evans improved the judge diff view and made several other enhancements.</li>
        </ul>
        """)
    ))
Example #7
0
def login(request):
    if request.method == 'GET':
        return HttpResponse(
            Page(
                div(cls="login-box",
                    contents=[
                        h2("Login", cls="login-header"),
                        h.label("Username", cls="form-label"),
                        h.input(name="username", cls="form-control"),
                        h.label("Password", cls="form-label"),
                        h.input(name="password",
                                cls="form-control",
                                type="password"),
                        div(cls="align-right",
                            contents=[
                                h.button("Login", cls="button login-button")
                            ])
                    ])))
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = checkPassword(username, password)
        if user:
            resp = JsonResponse('ok', safe=False)
            resp.set_cookie('id', user.id)
            resp.set_cookie('user', user.username)
            resp.set_cookie('userType', user.type)
            resp.set_cookie('userLoginTime', time.time() * 1000)
            return resp
        else:
            return JsonResponse('Incorrect username / password', safe=False)
Example #8
0
def privacy(request):
    return HttpResponse(Page(
        h2("Privacy Policy", cls="page-title"),
        Card("TL;DR", "OpenContest as an organization is too lazy to steal your data (we're busy enough keeping track of our own). " +
             "However, the organizers of your contest may collect any data you submit, " +
             "including your name (which the organizers provide) and any code submissions, which they may use for any purpose."),
        Card("Data collected",
             div(
                h.span("OpenContest collects the following data:"),
                h.ul(
                    h.li("Your name as provided by the contest organizers"),
                    h.li("Your password as generated by the app"),
                    h.li("Any problem statements written by the contest organizers"),
                    h.li("Any contest details created by the contest organizers"),
                    h.li("Any code submissions by contest participants")
                )
             )
        ),
        Card("Data usage",
             div(
                h.span("Any data collected by OpenContest may be accessible to"),
                h.ul(
                    h.li("The contest organizers"),
                    h.li("Anyone with access to the server that OpenContest is running on"),
                    h.li("Anyone in the world, though we have tried to eliminate this possibility")
                ),
                h.span("Any data collected in OpenContest is stored in plain text on the server that OpenContest is running on. " +
                       "No data is not sent to the developers of OpenContest.")
             )
        )
    ))
Example #9
0
def listContests(request):
    contests = [*map(ContestCard, Contest.all())]
    return HttpResponse(
        Page(
            h2("Contests", cls="page-title"),
            div(cls="actions",
                contents=[
                    h.button("+ Create Contest",
                             cls="button create-contest",
                             onclick="window.location='/contests/new'")
                ]), div(cls="contest-cards", contents=contests)))
Example #10
0
def viewDiff(request, *args, **kwargs):
    submission = Submission.get(kwargs.get('id'))
    user = User.getCurrent(request)
    problem = submission.problem

    answers = submission.readFilesForDisplay('out')

    diffTables = []
    for i in range(len(problem.testData)):
        if i < problem.samples:
            caseType = "Sample"
            caseNo = i
        else:
            caseType = "Judge"
            caseNo = i - problem.samples

        diffTables.append(
            h.div(
                h.
                h3(f"{caseType} Case #{caseNo} (Expected Output | Contestant Output)",
                   id=f"case{i}diff"),
                h.div(
                    h.script(
                        f"document.getElementById('case{i}result').innerHTML = 'Result: ' + verdict_name.{submission.results[i]}"
                    ),
                    id=f"case{i}result",
                ),
                generateDiffTable(problem.testData[i].output, answers[i]),
            ))
        pass

    return HttpResponse(
        div(cls="center",
            contents=[
                h.link(
                    rel="stylesheet",
                    href=
                    "/static/styles/style.css?642ab0bc-f075-4c4c-a2ba-00f55392dafc",
                    type="text/css"),
                h.script(src="/static/lib/jquery/jquery.min.js"),
                h.script(src="/static/lib/jqueryui/jquery-ui.min.js"),
                h.script(
                    src=
                    "/static/scripts/script.js?75c1bf1e-10e8-4c8d-9730-0903f6540439"
                ),
                h2(f"Diffs for {submission.id}", cls="center"),
                h.
                em("Insertions are in <span style=color:darkgreen;background-color:palegreen>green</span>, deletions are in <span style=color:darkred;background-color:#F6B0B0>red</span>"
                   ),
                h.div(contents=diffTables)
            ]))
Example #11
0
    def __init__(self,
                 title,
                 contents,
                 link=None,
                 cls=None,
                 delete=None,
                 reply=None,
                 rejudge=None,
                 edit=None):
        if cls == None:
            cls = "card"
        else:
            cls += " card"
        deleteLink = ""
        if delete:
            deleteLink = div(h.i("clear", cls="material-icons"),
                             cls="delete-link",
                             onclick=delete)
        elif reply:
            deleteLink = div(h.button("Reply",
                                      cls="btn btn-primary",
                                      onclick=reply),
                             cls="delete-link")
        if rejudge:
            deleteLink = div(h.button("Rejudge All",
                                      cls="btn btn-primary",
                                      onclick=rejudge),
                             cls="delete-link")

            # Add a pencil to the card if one is desired
        editLink = ""
        if edit:
            editLink = div(h.i("edit", cls="material-icons", onclick=edit),
                           cls="delete-link")

        self.html = h.div(cls=cls,
                          contents=[
                              div(cls="card-header",
                                  contents=[
                                      h2(contents=[title], cls="card-title"),
                                      deleteLink, editLink
                                  ]),
                              div(cls="card-contents", contents=contents)
                          ])
        if link != None:
            self.html = div(a(href=link, cls="card-link"),
                            self.html,
                            cls="card-link-box")
def generateLogReport(request):
    user = User.getCurrent(request)
    contest = Contest.getCurrent() or Contest.getPast()
    if not contest:
        return HttpResponse(
            Page(h1("&nbsp;"), h1("No Contest Available", cls="center")))
    elif contest.isScoreboardOff(user):
        return HttpResponse(
            Page(h1("&nbsp;"), h1("Scoreboard is off.", cls="center")))

    start = contest.start
    end = contest.end

    users = {}

    for sub in Submission.all():
        if start <= sub.timestamp <= end and not sub.user.isAdmin(
        ) and sub.result == "ok":
            username = User.get(sub.user.id).username
            problemName = Problem.get(sub.problem.id).title

            if username not in users.keys():
                users[username] = {}
            if problemName not in users[username].keys():
                users[username][problemName] = sub
            if sub.timestamp < users[username][problemName].timestamp:
                users[username][problemName] = sub

    correctSubmissions = []
    for user in users.keys():
        for problem in users[user].keys():
            correctSubmissions.append(
                (user, problem, users[user][problem].timestamp))

    correctSubmissions.sort(key=lambda entry: entry[2])

    tableRows = constructTableRows(correctSubmissions)

    return HttpResponse(
        Page(
            h2("Correct Submissions Log", cls="page-title"),
            h.table(
                h.thead(
                    h.tr(
                        h.th("Contestant Name"),
                        h.th("Problem title"),
                        h.th("Time"),
                    )), h.tbody(*tableRows))))
Example #13
0
 def __init__(self):
     self.html = div(
         cls="footer",
         contents=[
             h2('Copyright &copy; {} by <a href="https://nathantheinventor.com" target="_blank">Nathan Collins</a> and BJU'
                .format(datetime.now().year)),
             div(cls="footer-links",
                 contents=[
                     h.span(h.a("System Status", href="/status")),
                     h.span(
                         h.a("Privacy Policy",
                             href="/privacy",
                             target="_blank")),
                     h.span(h.a("About", href="/about", target="_blank")),
                     h.span(h.a("FAQs", href="/faqs", target="_blank"))
                 ])
         ])
Example #14
0
def systemStatus(request):
    contestName = Contest.getCurrent().name if Contest.getCurrent() else "None"
    submissionsTesting = OC_MAX_CONCURRENT_SUBMISSIONS - Submission.runningSubmissions._value
    if Status.instance().isRejudgeInProgress():
        progress = Status.instance().rejudgeProgress
        problem = Problem.get(progress[0])
        rejudgeProgress = f"Rejudged {progress[1]} of {progress[2]} submissions of {problem.title}"
    else:
        rejudgeProgress = "none"

    return HttpResponse(
        Page(
            h2("System Status", cls="page-title"),
            h.table(
                h.tr(h.th("Current contest:"), h.td(contestName)),
                h.tr(h.th("Submissions testing:"), h.td(submissionsTesting)),
                h.tr(h.th("Rejudge progress:"), h.td(rejudgeProgress)),
            )))
Example #15
0
 def __init__(self, user: User):
     cls = "blue" if user.isAdmin() else ""
     self.html = div(cls="col-3",
                     contents=[
                         Card(div(
                             h.strong(h.i("Username:"******"username-hidden"),
                             h.br(cls="username-hidden"),
                             h.p("&quot;", cls="username-hidden"),
                             h2(user.username, cls="card-title"),
                             h.p("&quot;", cls="username-hidden")),
                              div(h.strong(h.i("Fullname:")), h.br(),
                                  f"&quot;{user.fullname}&quot;", h.br(),
                                  h.strong(h.i("Password:"******"&quot;{user.password}&quot;"),
                              delete=f"deleteUser('{user.username}')",
                              cls=cls)
                     ])
Example #16
0
 def __init__(self):
     self.html = div(
         cls="code-editor card",
         contents=[
             div(cls="card-header",
                 contents=[
                     h2("Code Editor", cls="card-title"),
                     h.select(
                         cls=
                         "language-picker custom-select col-2 custom-select-sm"
                     )
                 ]),
             div(cls="ace-editor-wrapper",
                 contents=[
                     div(id="ace-editor",
                         cls="ace-editor",
                         contents=["#Some Python code"])
                 ])
         ])
Example #17
0
def listProblems(request):
    user = User.getCurrent(request)
    if Contest.getCurrent() or (Contest.getPast() and user.isAdmin()):
        contest = Contest.getCurrent() or Contest.getPast()
        probCards = []
        for prob in contest.problems:
            probCards.append(ProblemCard(prob, user))

        return HttpResponse(Page(h2("Problems", cls="page-title"), *probCards))
    elif Contest.getFuture():
        contest = Contest.getFuture()
        return HttpResponse(
            Page(h1("&nbsp;"), h1("Contest Starts in", cls="center"),
                 h1(contest.start, cls="countdown jumbotron center")))
    elif Contest.getPast():
        return HttpResponse(
            Page(h1("&nbsp;"), h1("Contest is Over", cls="center")))
    return HttpResponse(
        Page(h1("&nbsp;"), h1("No Contest Created", cls="center")))
Example #18
0
def fake_privacy(request):
    return HttpResponse(Page(
        h2("Privacy Policy", cls="page-title"),
        h1("LOL", cls="jumbotron center"),
        h1("After all, you use Facebook", cls="center")
    ))
Example #19
0
def leaderboard(request):
    contest = Contest.getCurrent() or Contest.getPast()
    user = User.getCurrent(request)
    if not contest:
        return HttpResponse(Page(
            h1("&nbsp;"),
            h1("No Contest Available", cls="center")
        ))
    elif contest.isScoreboardOff(user):
        return HttpResponse(Page(
            h1("&nbsp;"),
            h1("Scoreboard is off.", cls="center")
        ))

    start = contest.start
    end = contest.end

    subs = get_user_subs_map(contest)
    
    problemSummary = {}
    for prob in contest.problems:
        problemSummary[prob.id] = [0, 0]

    scores = []
    for userid in subs:
        usersubs = subs[userid]
        scor = score(usersubs, contest, problemSummary)

        # Set displayName to fullname if displayFullname option is true,
        # otherwise, use the username
        displayName = User.get(userid).fullname if contest.displayFullname == True else User.get(userid).username
        
        scores.append((
            displayName,
            scor[0],
            scor[1],
            scor[2],
            scor[3]
        ))
    scores = sorted(scores, key=lambda score: score[1] * 1000000000 + score[2] * 10000000 - score[3], reverse=True)
    
    ranks = [i + 1 for i in range(len(scores))]
    for i in range(1, len(scores)):
        u1 = scores[i]
        u2 = scores[i - 1]
        if (u1[1], u1[2], u1[3]) == (u2[1], u2[2], u2[3]):
            ranks[i] = ranks[i - 1]
    
    scoresDisplay = []
    for (name, solved, samples, points, attempts), rank in zip(scores, ranks):
        scoresDisplay.append(h.tr(
            h.td(rank, cls="center"),
            h.td(name),
            h.td(attempts, cls="center"),
            h.td(solved, cls="center"),
            h.td(samples, cls="center"),
            h.td(points, cls="center")
        ))

    problemSummaryDisplay = []
    for problem in contest.problems:
        problemSummaryDisplay.append(h.tr(
            h.td(problem.title),
            h.td(problemSummary[problem.id][0], cls="center"),
            h.td(problemSummary[problem.id][1], cls="center")
        ))

    return HttpResponse(Page(
        h2("Leaderboard", cls="page-title"),
        div(cls="actions", contents=[
            h.button("Detailed Contest Report", cls="button create-message", onclick="window.location.href='/contestreport'")
        ]),
        h.table(cls="banded", contents=[
            h.thead(
                h.tr(
                    h.th("Rank", cls="center"),
                    h.th("User"),
                    h.th("Attempts", cls="center"),
                    h.th("Problems Solved", cls="center"),
                    h.th("Sample Cases Solved", cls="center"),
                    h.th("Penalty Points", cls="center")
                )
            ),
            h.tbody(
                *scoresDisplay
            )
        ]),
        h2("Problem Summary", cls="page-title"),
        h.table(cls="banded", contents=[
            h.thead(
                h.tr(
                    h.th("Problem", cls="center"),
                    h.th("Attempts", cls="center"),
                    h.th("Solved", cls="center"),
                )
            ),
            h.tbody(
                *problemSummaryDisplay
            )
        ]),
        div(cls="align-right", contents=[
            h.br(),
            h.button("Correct Log", cls="button", onclick="window.location='/correctlog'")
        ] if user and user.isAdmin() else []
        )
    ))
Example #20
0
def contestreport(request):
    contest = Contest.getCurrent() or Contest.getPast()
    user = User.getCurrent(request)
    if not contest:
        return HttpResponse(Page(
            h1("&nbsp;"),
            h1("No Contest Available", cls="center")
        ))
    elif contest.isScoreboardOff(user):
        return HttpResponse(Page(
            h1("&nbsp;"),
            h1("Scoreboard is off.", cls="center")
        ))

    start = contest.start
    end = contest.end
    problemSummaryreport = []
    
    subs = get_user_subs_map(contest) 

    if start <= time.time() <= end:
        reportcols = [h.th("Rank"), h.th("Contestant"), h.th("Contestant ID"), h.th("Correct"), h.th("Penalty"), ]
    else:
        reportcols = [h.th("Rank"), h.th("Contestant ID"), h.th("Correct"), h.th("Penalty"), ]

    problemSummary = {}
    problems = []
    problemNum = 0
    for prob in contest.problems:
        problemSummary[prob.id] = [0, 0]
        problemNum += 1
        problems.append(prob.id)
        problemSummaryreport.append({"id":prob.id,"title":prob.title,"attempts":0,"correct":0}) 
        reportcols.append(h.th(f"{problemNum}", cls="center"))
    
    scores = []
    for user in subs:
        usersubs = subs[user]
        scor = score(usersubs, contest, problemSummary)
        scores.append((
            User.get(user).username,
            scor[0],
            scor[1],
            scor[2],
            scor[3],
            user
        ))
    
    scores = sorted(scores, key=lambda score: score[1] * 1000000000 + score[2] * 10000000 - score[3], reverse=True)
    ranks = [i + 1 for i in range(len(scores))]
    for i in range(1, len(scores)):
        u1 = scores[i]
        u2 = scores[i - 1]
        if (u1[1], u1[2], u1[3]) == (u2[1], u2[2], u2[3]):
            ranks[i] = ranks[i - 1]

    log = []
    for (name, solved, samples, points, attempts, userid), rank in zip(scores, ranks):
        log.append({"rank": rank, "name": name, "userid": userid, "solved": solved, "points": points})
    
    detailedContestDisplay = []
    for person in log:
        outproblems = []
        submissions = sorted(subs[person["userid"]], key=lambda sub: sub.timestamp) 
        for p in problems:
            p_trys = 0
            earliest_time = 0
            for s in submissions:
                if p == s.problem.id:
                    p_trys += 1
                    if s.result == "ok":
                        earliest_time = s.timestamp
                        break

            if earliest_time: 
                outproblems.append(h.td(f"({p_trys}) {datetime.utcfromtimestamp((earliest_time - start) / 1000).strftime('%H:%M')}"))
                for prob in problemSummaryreport:
                    if prob['id'] == p:
                        prob["attempts"] += p_trys
                        prob["correct"] += 1
                        prob[s.language] = prob.get(s.language, 0) + 1
                        
            elif p_trys:      
                outproblems.append(h.td(f"({p_trys}) -- "))
                for prob in problemSummaryreport:
                    if prob['id'] == p:
                        prob["attempts"] += p_trys
                
            else:
                outproblems.append(h.td(f""))
        
        # Previous logic checked to make sure user was a valid object
        # before retrieving its members. That is why this code does as
        # well
        user = User.getByName(person["name"])
        if user:
            # Set displayName to fullname if displayFullname option is true,
            # otherwise, use the username
            displayName = user.fullname if contest.displayFullname == True else user.username
        else:
            displayName = person["name"]
        
        detailedContestDisplay.append(h.tr(
            h.td(person["rank"]),
            h.td(displayName),
            h.td(person["name"]) if start  <= time.time() <=  end else "",
            h.td(person["solved"]),
            h.td(person["points"]),
            *outproblems
        ))

    lang_col = [h.td("#"), h.td("Title")]
    for lan in all_languages:
        lang_col.append(h.td(all_languages[lan]))
    lang_col.append(h.td("Total Count"))
    problemSummaryDisplay =[]
    LanguageDisplay = []
    i = 0
    for prob in problemSummaryreport:

        i += 1
        problemSummaryDisplay.append(h.tr(
            h.td(i),
            h.td(prob["title"]),
            h.td(prob["attempts"]),
            h.td(prob["correct"]),
        ))

        langcount = []
        total = 0
        for lan in all_languages:
            if lan in prob:
                total += prob[lan]
                langcount.append(h.td(prob[lan]))
            else: langcount.append(h.td(""))

        LanguageDisplay.append(h.tr(
            h.td(i),
            h.td(prob["title"]),
            *langcount,
            h.td(total) if total > 0 else h.td("")
        ))

    return HttpResponse(Page(
        h2("DETAILED STANDINGS", cls="page-title"),
        h.table(cls="banded", contents=[
            h.thead(h.tr(*reportcols)),
            h.tbody(*detailedContestDisplay)
        ]),
        h2("Problem Summary", cls="page-title"),
        h.table(cls="banded", contents=[
            h.thead(
                h.tr(
                    h.td("#"),
                    h.td("Title"),
                    h.td("Attempts"),
                    h.td("Correct")
                )
            ),
            h.tbody(*problemSummaryDisplay)
        ]),
        h2("Language Breakdown", cls="page-title"),
        h.table(cls="banded", contents=[
            h.thead(h.tr(*lang_col)
            ),h.tbody(*LanguageDisplay)
        ]),
        cls='wide-content' # Use a wide format for this page
    ))
Example #21
0
def faqs(request):
    return HttpResponse(Page(
        h2("FAQs", cls="page-title"),
        FAQ("What is a programming contest?", """A programming contest is a contest where programmers 
            attempt to solve problems by writing programs. These problems are typically posed as a 
            problem statement to describe the problem, input that the program must process, and 
            output that the program must produce. The goal of solving the problem is to write a 
            program that produces the same output for a given input as the judge's solution."""),
        FAQ("What happens when I submit code for a problem?", """When you submit code for a problem, 
            your code is automatically run against secret test data and judged based on the output
            it produces. Your code can recieve the following verdicts:
            <ul><li><i>Accepted</i>: Your code produced the correct output for all test cases.</li>
                <li><i>Wrong Answer</i>: Your code produced incorrect output for some test case.</li>
                <li><i>Runtime Error</i>: Your code threw an exception and exited with a non-zero exit code.</li>
                <li><i>Time Limit Exceeded</i>: Your code ran longer than the time allowed.</li></ul>
            """),
        FAQ("How does scoring work?", """Your score is determined by two factors: the number of problems 
            you solve and the number of penalty points you accrue. Contestants are ranked first on 
            problems solved and then on penalty points. A contestant who solves 5 problems will always
            rank higher than a contestant who solves 4 problems, but two contestants 
            who each solve 4 problems will be ranked against each other by penalty points.<br/><br/>
            Penalty points are determined by the time it takes you to solve the problems and the number 
            of incorrect submissions that you make. When you solve a problem, you accrue 1 penalty point 
            for each minute that has elapsed from the beginning of the contest and 20 penalty points 
            for each incorrect submission you made to that problem. For example, if you solve a problem 
            137 minutes into the contest after making 2 incorrect submissions, you will accrue 177 
            penalty points. You do not accrue penalty points for incorrect submissions to a problem 
            if you never solve that problem.<br/><br/>
            For example, if Jim and Bob solve problems at the following times,<br/><br/>
            <table>
                <thead><tr><th>Problem</th>
                    <th class="center">1</th><th class="center">2</th><th class="center">3</th>
                    <th class="center">4</th><th class="center">5</th></tr></thead>
                <tbody>
                    <tr><td>Jim</td>
                        <td class="center">37 minutes,<br/>1 wrong<br/>57 points</td>
                        <td class="center">14 minutes,<br/>2 wrong<br/>54 points</td>
                        <td class="center">43 minutes,<br/>0 wrong<br/>43 points</td>
                        <td class="center"><br/>5 wrong<br/>0 points</td>
                        <td class="center">59 minutes,<br/>1 wrong<br/>79 points</td>
                    </tr>
                    <tr><td>Bob</td>
                        <td class="center">7 minutes,<br/>0 wrong<br/>7 points</td>
                        <td class="center">23 minutes,<br/>1 wrong<br/>43 points</td>
                        <td class="center"><br/><br/>0 points</td>
                        <td class="center">53 minutes,<br/>2 wrong<br/>93 points</td>
                        <td class="center">41 minutes,<br/>1 wrong<br/>61 points</td>
                    </tr>
                </tbody>
            </table><br/>
            Jim will receive a total of 233 points, and Bob will receive a total of 204 points.
            Since Bob has fewer penalty points, he will rank above Jim.
            """),
        FAQ("Where can I find information about my language?", """There is language documentation available for the following languages:
            <ul><li><a target="_blank" href="https://en.cppreference.com/w/c/language">C</a></li>
                <li><a target="_blank" href="https://en.cppreference.com/w/">C++</a></li>
                <li><a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/">C#</a></li>
                <li><a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/">Java</a></li>
                <li><a target="_blank" href="https://docs.python.org/3/library/">Python 3</a></li>
                <li><a target="_blank" href="https://ruby-doc.org/stdlib-2.5.3/">Ruby</a></li>
                </ul>"""),
        FAQ("What compiler flags are being used?", """The following languages are compiled with non-default compiler flags:
            <ul><li>C: -std=c11 -O2</li>
                <li>C++: -std=c++17 -O2</li>
                </ul>"""),
        FAQ("Why am I getting the Wrong Answer verdict?", """There are several reasons you could be getting Wrong Answer, but here are the two of the most common:
            <ul><li>Your output formatting does not match the judge's. Output formatting must exactly match.</li>
                <li>Your method of solving the problem is incorrect.</li>
                </ul>"""),
        FAQ("Why am I getting the Runtime Error verdict?", """There are several reasons you could be getting Runtime Error, but here are a few of the most common:
            <ul><li>Your code divided by zero or took the square root of a negative number.</li>
                <li>Your code read or wrote to an array at an index that was out of bounds.</li>
                <li>Your C/C++ code dereferenced an invalid pointer, such as nullptr or a pointer to an object that had been deleted.</li>
                <li>Your Java code called a method on a null object.</li>
                <li>Your Python code exceeded Python's recursion depth limit. Python allows only a few hundred recursive calls to a function.</li>
                <li>Your C/C++ code failed to return 0 from the main function.</li>
                </ul>"""),
    ))
Example #22
0
def displayMessages(request, *args, **kwargs):
    user = User.getCurrent(request)

    messages = []
    if INBOX in request.path:
        if user.isAdmin():
            inbox = {}
            Message.forEach(lambda msg: inbox.update({msg.id: msg})
                            if msg.isAdmin else None)

            # Remove from inbox messages that have been responded to
            Message.forEach(lambda msg: inbox.pop(msg.replyTo)
                            if msg.replyTo in inbox else None)
            messages = list(inbox.values())
        else:
            Message.forEach(lambda msg: messages.append(msg)
                            if (msg.toUser and msg.toUser.id == user.id or msg.
                                fromUser == user or msg.isGeneral) else None)

    elif PROCESSED in request.path:

        def addReply(msg):
            if msg.replyTo in replies:
                replies[msg.replyTo].append(msg)
            else:
                replies[msg.replyTo] = [msg]

        # Find replies
        replies = {}
        Message.forEach(lambda msg: addReply(msg) if msg.replyTo else None)

        messages = [[Message.get(id)] + replies[id] for id in replies.keys()]

    elif ANNOUNCEMENT in request.path:
        Message.forEach(lambda msg: messages.append(msg)
                        if msg.isGeneral else None)

    if len(messages) > 0 and not isinstance(messages[0], list):
        messages = [[msg] for msg in messages]

    messages = [
        *map(lambda msglist: MessageCard(msglist, user),
             sorted(messages, key=lambda msglist: -msglist[0].timestamp))
    ]

    adminDetails = []
    if user.isAdmin():
        userOptions = [
            *map(lambda usr: h.option(usr.username, value=usr.id), User.all())
        ]
        adminDetails = [
            h.h5("To"),
            h.select(cls="form-control recipient",
                     contents=[h.option("general"), *userOptions]),
            h.input(type="hidden", id="replyTo"),
            h.h5("Message")
        ]

    if user.isAdmin():
        filter = div(
            a(href='inbox', contents="Inbox"),
            ' | ',
            a(href='processed', contents="Handled"),
            ' | ',
            a(href='announcements', contents="Announcements"),
        )
    else:
        filter = div()

    return HttpResponse(
        Page(
            h2("Messages", cls="page-title"),
            div(cls="actions",
                contents=[
                    h.button("+ Send Message",
                             cls="button create-message",
                             onclick="createMessage()")
                ]),
            filter,
            Modal(
                "Send Message",
                div(*adminDetails, h.textarea(cls="message col-12")),
                div(
                    h.button(
                        "Cancel", **{
                            "type": "button",
                            "class": "button button-white",
                            "data-dismiss": "modal"
                        }),
                    h.button(
                        "Send", **{
                            "type": "button",
                            "class": "button",
                            "onclick": "sendMessage()"
                        }))),
            div(cls="message-cards", contents=messages),
        ))
Example #23
0
def editContest(request, *args, **kwargs):
    id = kwargs.get('id')
    contest = Contest.get(id)

    title = "New Contest"
    chooseProblem = ""
    existingProblems = []
    start = time.time() * 1000
    end = (time.time() + 3600) * 1000
    scoreboardOff = end
    displayFullname = False
    showProblInfoBlocks = ""

    showProblInfoBlocks_option = [
        h.option("On", value="On"),
        h.option("Off", value="Off")
    ]

    tieBreaker = False
    if contest:
        title = contest.name
        start = contest.start
        end = contest.end
        scoreboardOff = contest.scoreboardOff

        displayFullname = contest.displayFullname

        showProblInfoBlocks = contest.showProblInfoBlocks
        if showProblInfoBlocks == "Off":
            showProblInfoBlocks_option = [
                h.option("Off", value="Off"),
                h.option("On", value="On")
            ]
        tieBreaker = contest.tieBreaker

        chooseProblem = div(cls="actions",
                            contents=[
                                h.button("+ Choose Problem",
                                         cls="button",
                                         onclick="chooseProblemDialog()")
                            ])

        problems = [ProblemCard(prob) for prob in contest.problems]
        problemOptions = [
            h.option(prob.title, value=prob.id) for prob in Problem.all()
            if prob not in contest.problems
        ]

        existingProblems = [
            Modal(
                "Choose Problem",
                h.select(cls="form-control problem-choice",
                         contents=[h.option("-"), *problemOptions]),
                div(
                    h.button(
                        "Cancel", **{
                            "type": "button",
                            "class": "button button-white",
                            "data-dismiss": "modal"
                        }),
                    h.button(
                        "Add Problem", **{
                            "type": "button",
                            "class": "button",
                            "onclick": "chooseProblem()"
                        }))),
            div(cls="problem-cards", contents=problems)
        ]

    return HttpResponse(
        Page(
            h.input(type="hidden", id="contest-id", value=id),
            h.input(type="hidden", id="pageId", value="Contest"),
            h2(title, cls="page-title"),
            chooseProblem,
            Card(
                "Contest Details",
                div(
                    cls="contest-details",
                    contents=[
                        h.form(
                            cls="row",
                            contents=[
                                div(cls="form-group col-12",
                                    contents=[
                                        h.label(
                                            **{
                                                "for": "contest-name",
                                                "contents": "Name"
                                            }),
                                        h.input(cls="form-control",
                                                name="contest-name",
                                                id="contest-name",
                                                value=title)
                                    ]),
                                h.input(type="hidden", id="start",
                                        value=start),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for": "contest-start-date",
                                                "contents": "Start Date"
                                            }),
                                        h.input(cls="form-control",
                                                name="contest-start-date",
                                                id="contest-start-date",
                                                type="date")
                                    ]),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for": "contest-start-time",
                                                "contents": "Start Time"
                                            }),
                                        h.input(cls="form-control",
                                                name="contest-start-time",
                                                id="contest-start-time",
                                                type="time")
                                    ]),
                                h.input(type="hidden", id="end", value=end),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for": "contest-end-date",
                                                "contents": "End Date"
                                            }),
                                        h.input(cls="form-control",
                                                name="contest-end-date",
                                                id="contest-end-date",
                                                type="date")
                                    ]),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for": "contest-end-time",
                                                "contents": "End Time"
                                            }),
                                        h.input(cls="form-control",
                                                name="contest-end-time",
                                                id="contest-end-time",
                                                type="time")
                                    ]),
                                h.input(type="hidden",
                                        id="showProblInfoBlocks",
                                        value=showProblInfoBlocks),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for":
                                                "show-problem-info-blocks",
                                                "contents":
                                                "Show Problem Info Blocks"
                                            }),
                                        h.select(
                                            cls="form-control custom-select",
                                            name="show-problem-info-blocks",
                                            id="show-problem-info-blocks",
                                            contents=showProblInfoBlocks_option
                                        )
                                    ]),
                                h.input(type="hidden",
                                        id="scoreboardOff",
                                        value=scoreboardOff),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for":
                                                "scoreboard-off-time",
                                                "contents":
                                                "Turn Scoreboard Off Time"
                                            }),
                                        h.input(cls="form-control",
                                                name="scoreboard-off-time",
                                                id="scoreboard-off-time",
                                                type="time")
                                    ]),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for":
                                                "scoreboard-tie-breaker",
                                                "contents":
                                                "Sample Data Breaks Ties"
                                            }),
                                        h.select(
                                            cls="form-control",
                                            name="scoreboard-tie-breaker",
                                            id="scoreboard-tie-breaker",
                                            contents=[
                                                *[
                                                    h.option(
                                                        text,
                                                        value=val,
                                                        selected="selected")
                                                    if tieBreaker == val else
                                                    h.option(text, value=val)
                                                    for text, val in zip(
                                                        ("On", "Off"), (True,
                                                                        False))
                                                ]
                                            ])
                                    ]),

                                # Option to display a users' fullname
                                h.input(type="hidden",
                                        id="displayFullname",
                                        value=displayFullname),
                                div(cls="form-group col-6",
                                    contents=[
                                        h.label(
                                            **{
                                                "for":
                                                "contest-display-fullname",
                                                "contents": "Show Full Name"
                                            }),
                                        h.select(
                                            cls="form-control",
                                            name="contest-display-fullname",
                                            id="contest-display-fullname",
                                            contents=[
                                                *[
                                                    h.option(
                                                        text,
                                                        value=val,
                                                        selected="selected") if
                                                    displayFullname == val else
                                                    h.option(text, value=val)
                                                    for text, val in zip(
                                                        ("On", "Off"), (True,
                                                                        False))
                                                ]
                                            ])
                                    ]),
                            ]),
                        div(cls="align-right col-12",
                            contents=[
                                h.button("Save",
                                         cls="button",
                                         onclick="editContest()")
                            ])
                    ])),
            *existingProblems))