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)))
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 __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 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)
def judge(request): cont = Contest.getCurrent() or Contest.getPast() if not cont: return HttpResponse( Page(h1(" "), 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 ))
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)))
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)
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( "×", **{ "aria-hidden": "true" }) ]) ]), div(body, cls="modal-body"), div(footer, cls="modal-footer") ]) ]) ])
def leaderboard(request): contest = Contest.getCurrent() or Contest.getPast() user = User.getCurrent(request) if not contest: return HttpResponse(Page( h1(" "), h1("No Contest Available", cls="center") )) elif contest.isScoreboardOff(user): return HttpResponse(Page( h1(" "), 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 [] ) ))
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), ))
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">×</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( " Status: ", h.select( cls=f"status-choice {submission.id}", contents=[*statusOptions(submission.status)])), h.span(" "), 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'))) ]) ]) ])
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))