コード例 #1
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)
コード例 #2
0
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")])
                ])))
コード例 #3
0
ファイル: page.py プロジェクト: thecavemanlogic/open-contest
 def __init__(self, *bodyData, cls='main-content'):
     cont = Contest.getCurrent()
     title = cont.name if cont else "OpenContest"
     self.html = h.html(
         head(
             h.title(title),
             h.link(rel="stylesheet",
                    href="/static/lib/fontawesome/css/all.css",
                    type="text/css"),
             h.link(rel="stylesheet",
                    href="/static/lib/bootstrap/css/bootstrap.min.css",
                    type="text/css"),
             h.link(rel="stylesheet",
                    href="/static/lib/jqueryui/jquery-ui.min.css",
                    type="text/css"),
             h.link(rel="stylesheet",
                    href="/static/lib/simplemde/simplemde.min.css",
                    type="text/css"),
             h.link(rel="stylesheet",
                    href="/static/styles/style.css?" + cachecontrol(),
                    type="text/css"),
             h.link(rel="shortcut icon", href="/static/favicon.ico"),
             h.script(src="/static/lib/jquery/jquery.min.js"),
             h.script(src="/static/lib/bootstrap/js/bootstrap.min.js"),
             h.script(src="/static/lib/jqueryui/jquery-ui.min.js"),
             h.script(src="/static/lib/ace/ace.js"),
             h.script(src="/static/lib/simplemde/simplemde.min.js"),
             h.script(src="/static/scripts/script.js?" + cachecontrol()),
             h.script(src="/static/lib/tablefilter/tablefilter.js"),
             h.script(src="/static/lib/FileSaver.min.js"),
         ),
         body(Header(title, cont.end if cont else None), Menu(),
              div(cls="message-alerts"), div(*bodyData, cls=cls), Footer()))
コード例 #4
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
        ))
コード例 #5
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.")
             )
        )
    ))
コード例 #6
0
 def __init__(self, q, a):
     id = str(uuid4())
     self.html = div(
         h.h4(q, cls="qa-question collapsed", **{"data-toggle": "collapse", "data-target": f"#qa-{id}"}),
         div(a, id=f"qa-{id}", cls="collapse"),
         cls="faq"
     )
コード例 #7
0
 def __init__(self, submission: Submission):
     subTime = submission.timestamp
     probName = submission.problem.title
     cls = "gray" if submission.status == Submission.STATUS_REVIEW else "red" if submission.result != "ok" else ""
     self.html = div(
         cls="modal-content",
         contents=[
             div(cls=f"modal-header {cls}",
                 contents=[
                     h.h5(f"Submission to {probName} at ",
                          h.span(subTime, cls="time-format")), """
             <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                 <span aria-hidden="true">&times;</span>
             </button>"""
                 ]),
             div(cls="modal-body",
                 contents=[
                     h.strong(
                         "Language: <span class='language-format'>{}</span>"
                         .format(submission.language)),
                     h.br(),
                     h.strong("Result: "),
                     verdict_name[submission.getContestantResult()],
                     h.br(),
                     h.br(),
                     h.strong("Code:"),
                     h.code(code_encode(submission.code), cls="code"),
                 ])
         ])
コード例 #8
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)))
コード例 #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)))
コード例 #10
0
    def __init__(self, x, sub):
        num, input, output, error, answer = x
        if input == None: input = ""
        if output == None: output = ""
        if error == None: error = ""

        contents = [
            div(cls="row",
                id="judge-viewDiffButton",
                contents=[
                    div(cls="col-12",
                        contents=[
                            h.button(
                                "View Diff",
                                onclick=
                                f"window.open('viewDiff/{sub.id}#case{num}diff', '_blank');",
                                target="_blank",
                            )
                        ])
                ]),
            div(cls="row",
                contents=[
                    div(cls="col-12",
                        contents=[h.h4("Input"),
                                  h.code(code_encode(input))])
                ]),
            div(cls="row",
                contents=[
                    div(cls="col-6",
                        contents=[h.h4("Output"),
                                  h.code(code_encode(output))]),
                    div(cls="col-6",
                        contents=[
                            h.h4("Correct Answer"),
                            h.code(code_encode(answer))
                        ])
                ]),
        ]

        if error != "":
            contents.append(
                div(cls="row",
                    contents=[
                        div(cls="col-12",
                            contents=[
                                h.h4("Standard Error"),
                                h.code(code_encode(error))
                            ])
                    ]), )

        self.html = div(id=f"tabs-{sub.id}-{num}", contents=contents)
コード例 #11
0
ファイル: page.py プロジェクト: thecavemanlogic/open-contest
 def __init__(self):
     self.html = div(cls="menu",
                     contents=[
                         div(cls="menu-items",
                             contents=[
                                 MenuItem("/problems", "Problems"),
                                 MenuItem("/leaderboard", "Leaderboard"),
                                 MenuItem("/submissions",
                                          "My Submissions",
                                          role="participant"),
                                 MenuItem("/messages/inbox", "Messages"),
                                 MenuItem("/judge", "Judge", role="admin"),
                                 MenuItem("/setup", "Setup", role="admin"),
                                 MenuItem("/logout", "Logout")
                             ])
                     ])
コード例 #12
0
ファイル: page.py プロジェクト: thecavemanlogic/open-contest
 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"))
                 ])
         ])
コード例 #13
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)
                     ])
コード例 #14
0
def getSample(datum, num: int) -> Card:
    if datum.input == None: datum.input = ""
    if datum.output == None: datum.output = ""
    return Card(
        "Sample #{}".format(num),
        div(cls="row",
            contents=[
                div(cls="col-12",
                    contents=[
                        h.p("Input:", cls="no-margin"),
                        h.code(code_encode(datum.input))
                    ]),
                div(cls="col-12",
                    contents=[
                        h.p("Output:", cls="no-margin"),
                        h.code(code_encode(datum.output))
                    ])
            ]))
コード例 #15
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"])
                 ])
         ])
コード例 #16
0
ファイル: page.py プロジェクト: thecavemanlogic/open-contest
 def __init__(self, title, endtimestamp=None):
     timeRemaining = ""
     if endtimestamp:
         timeRemaining = str(int(((endtimestamp / 1000) - time.time())))
     self.html = div(
         cls="top",
         contents=[
             div(cls="header",
                 contents=[
                     h1(title),
                     div(cls="spacer"),
                     div(cls="header-right",
                         contents=[
                             h.span(cls="time-remaining",
                                    data_timeremaining=timeRemaining),
                             h.br(),
                             h.span(cls="login-user")
                         ])
                 ])
         ])
コード例 #17
0
 def __init__(self, contest: Contest):
     self.html = Card(contest.name,
                      div(
                          h.span(contest.start,
                                 cls='time-format',
                                 data_timestamp=contest.start), " - ",
                          h.span(contest.end,
                                 cls='time-format',
                                 data_timestamp=contest.end)),
                      link=f"/contests/{contest.id}",
                      delete=f"deleteContest('{contest.id}')",
                      cls=contest.id)
コード例 #18
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)
            ]))
コード例 #19
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")
                ])))
コード例 #20
0
ファイル: page.py プロジェクト: thecavemanlogic/open-contest
    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")
コード例 #21
0
ファイル: page.py プロジェクト: thecavemanlogic/open-contest
 def __init__(self, title, body, footer, modalID=""):
     '''
     modalID - used to uniquely identify different modals. Only necessary when
               two or more modals are present on page
     '''
     # taken from https://getbootstrap.com/docs/4.1/components/modal/
     self.html = div(
         cls=f"modal {modalID}",
         role="dialog",
         contents=[
             div(cls="modal-dialog",
                 role="document",
                 contents=[
                     div(cls="modal-content",
                         contents=[
                             div(cls="modal-header",
                                 contents=[
                                     h.h5(title, cls="modal-title"),
                                     h.button(**{
                                         "type": "button",
                                         "class": "close",
                                         "data-dismiss": "modal",
                                         "arial-label": "close"
                                     },
                                              contents=[
                                                  h.span(
                                                      "&times;", **{
                                                          "aria-hidden":
                                                          "true"
                                                      })
                                              ])
                                 ]),
                             div(body, cls="modal-body"),
                             div(footer, cls="modal-footer")
                         ])
                 ])
         ])
コード例 #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),
        ))
コード例 #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))
コード例 #24
0
 def __init__(self, submission: Submission, user, force):
     subTime = submission.timestamp
     probName = submission.problem.title
     cls = "red" if submission.result != "ok" else ""
     self.html = div(
         cls="modal-content",
         contents=[
             div(cls=f"modal-header {cls}",
                 contents=[
                     h.h5(
                         f"{probName} from {submission.user.username} at ",
                         h.span(subTime, cls="time-format"),
                         f" (id {submission.id})",
                     ), """
             <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                 <span aria-hidden="true">&times;</span>
             </button>"""
                 ]),
             div(cls="modal-body",
                 contents=[
                     h.input(type="hidden",
                             id="version",
                             value=f"{submission.version}"),
                     h.strong(
                         "Result: ",
                         h.select(
                             cls=f"result-choice {submission.id}",
                             contents=[*resultOptions(submission.result)])),
                     h.strong(
                         "&emsp;Status: ",
                         h.select(
                             cls=f"status-choice {submission.id}",
                             contents=[*statusOptions(submission.status)])),
                     h.span("&emsp;"),
                     h.button(
                         "Save",
                         type="button",
                         onclick=
                         f"changeSubmissionResult('{submission.id}', '{submission.version}')",
                         cls="btn btn-primary"),
                     h.span(" "),
                     h.button("Retest",
                              type="button",
                              onclick=f"rejudge('{submission.id}')",
                              cls="btn btn-primary rejudge"),
                     h.span(" "),
                     h.button("Download",
                              type="button",
                              onclick=f"download('{submission.id}')",
                              cls="btn btn-primary rejudge"),
                     h.br(),
                     h.br(),
                     h.strong(
                         f"Language: <span class='language-format'>{submission.language}</span>"
                     ),
                     h.code(code_encode(submission.code), cls="code"),
                     div(cls="result-tabs",
                         id="result-tabs",
                         contents=[
                             h.ul(*map(lambda x: TestCaseTab(x, submission),
                                       enumerate(submission.results))),
                             *map(
                                 lambda x: TestCaseData(x, submission),
                                 zip(
                                     range(submission.problem.tests),
                                     submission.readFilesForDisplay('in'),
                                     submission.readFilesForDisplay('out'),
                                     submission.readFilesForDisplay(
                                         'error'),
                                     submission.readFilesForDisplay(
                                         'answer')))
                         ])
                 ])
         ])
コード例 #25
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 []
        )
    ))
コード例 #26
0
 def __init__(self, x, cont):
     num, prob = x
     subs = filter(
         lambda sub: sub.problem == prob and cont.start <= sub.timestamp <=
         cont.end, Submission.all())
     self.html = div(*map(SubmissionCard, subs), id=f"tabs-{num}")
コード例 #27
0
ファイル: page.py プロジェクト: thecavemanlogic/open-contest
 def __init__(self, url, title, role="any"):
     self.html = div(role=role,
                     cls="menu-item",
                     contents=[a(href=url, contents=[title])])