Ejemplo n.º 1
0
def format_scoreboard(aug=lambda y, x: x):
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        try:
            data = bj.scoreboard(url, cookie)
        except BruteError as e:
            bottle.response.status = 500
            return aug(True, '<pre>' + html.escape(str(e)) + '</pre>')
        except:
            bottle.response.status = 500
            return aug(True, '<pre>Internal server error</pre>')
        tasks = bj.task_list(url, cookie)
    task = pkgutil.get_data('ejui', 'scoreboard_task.html').decode('utf-8')
    tasks = ''.join(task.format(name=html.escape(i)) for i in tasks)
    contestant = pkgutil.get_data('ejui', 'contestant.html').decode('utf-8')
    contestant_task = pkgutil.get_data('ejui',
                                       'contestant_task.html').decode('utf-8')
    contestants = []
    for index, (data, scores) in enumerate(data):
        cur_tasks = ''.join(
            '<td></td>' if i == None else contestant_task.
            format(kind=(('ok' if i['attempts'] >= 0 else 'fail'
                          ) if 'attempts' in i else 'unknown'),
                   score=sb_format_single(i)) for i in scores)
        contestants.append(
            contestant.format(index=index + 1,
                              nickname=data['name'],
                              tasks=cur_tasks))
    return aug(
        False,
        pkgutil.get_data('ejui', 'scoreboard.html').decode('utf-8').format(
            tasks=tasks, contestants=''.join(contestants)))
Ejemplo n.º 2
0
def task_page(task):
    task = int(task)
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        tl = bj.task_list(url, cookie)
        td = task_data(task, tl=tl)
        t1 = pkgutil.get_data('ejui', 'task.html').decode('utf-8')
        t2 = pkgutil.get_data('ejui', 'compiler.html').decode('utf-8')
        subms, any_subms, json_subms = format_submissions(td['name'])
        if any_subms:
            subms = pkgutil.get_data(
                'ejui', 'task_subms.html').decode('utf-8').format(subms=subms)
        else:
            subms = ''
        compilers = ''
        for a, b, c in td['compilers']:
            compilers += t2.format(id=a,
                                   short_name=html.escape(b),
                                   long_name=html.escape(c))
        if td['compilers']:
            compilers = pkgutil.get_data(
                'ejui',
                'compilers.html').decode('utf-8').format(data=compilers)
        return format_page('task%d' % task,
                           t1.format(id=task,
                                     name=html.escape(td['name']),
                                     subms=subms,
                                     compilers=compilers),
                           tl=tl,
                           subms=json_subms)
Ejemplo n.º 3
0
def submission_list():
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        return {
            "list": bj.submission_list(url, cookie),
            "status": bj.status(url, cookie),
            "scores": bj.scores(url, cookie)
        }
Ejemplo n.º 4
0
def submission_list_item(id):
    id = int(id)
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        score = bj.submission_score(url, cookie, id)
        status = bj.submission_status(url, cookie, id)
        gsc = bj.scores(url, cookie)
        gst = bj.status(url, cookie)
    data = {'status': status}
    if score != None:
        data['score'] = score
    data['global'] = {'status': gst, 'scores': gsc}
    return data
Ejemplo n.º 5
0
def task_data(task, tl=None):
    task = int(task)
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        if tl == None: tl = bj.task_list(url, cookie)
        if task not in range(len(tl)):
            abort(404)
        name = tl[task]
        tids = bj.task_ids(url, cookie)
        try:
            tid = tids[task]
        except IndexError:
            compilers = []
        else:
            try:
                compilers = bj.compiler_list(url, cookie, tid)
            except BruteError:
                compilers = []
        return {'name': name, 'compilers': compilers}
Ejemplo n.º 6
0
def format_source(id):
    id = int(id)
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        src = bj.submission_source(url, cookie, id).decode('utf-8', 'replace')
        subms = list(zip(*bj.submission_list(url, cookie)))
        try:
            task = [j for i, j in subms if int(i) == id][0]
        except IndexError:
            task = None
        if src == None:
            ans = pkgutil.get_data('ejui', 'no_source.html').decode('utf-8')
        else:
            ans = pkgutil.get_data(
                'ejui', 'source.html').decode('utf-8').format(
                    subm_id=id,
                    task=(' (task %s)' %
                          html.escape(task) if task != None else ''),
                    code=html.escape(src))
        return format_page('subms', ans)
Ejemplo n.º 7
0
def format_protocol(id):
    id = int(id)
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        tests, any_tests = format_tests(id)
        if not any_tests:
            tests = ''
        try:
            err = bj.compile_error(url, cookie, id)
        except:
            import traceback
            err = traceback.format_exc()
    if not err:
        err = ''
    else:
        err = pkgutil.get_data(
            'ejui',
            'compile_error.html').decode('utf-8').format(err=html.escape(err))
    return pkgutil.get_data('ejui', 'protocol.html').decode('utf-8').format(
        id=id, err=err, tests=tests)
Ejemplo n.º 8
0
def format_submissions(task=None):
    url, cookie = force_session()
    json_data = {}
    with bj.may_cache(url, cookie):
        a, b = bj.submission_list(url, cookie)
        json_data['list'] = [a, b]
        ans = ''
        have_score = False
        status_arr = []
        stats_arr = []
        for i, t in zip(a, b):
            status = bj.submission_status(url, cookie, i)
            stats = bj.submission_score(url, cookie, i)
            status_arr.append(status)
            if stats != None and task in (t, None): have_score = True
            stats_arr.append(stats)
        tt = pkgutil.get_data(
            'ejui', 'subm.html'
            if have_score else 'subm_no_score.html').decode('utf-8')
        status_arr = iter(status_arr)
        stats_arr = iter(stats_arr)
        any_subms = False
        for i, t in zip(a, b):
            status = next(status_arr)
            stats = next(stats_arr)
            json_item = {'status': status}
            if stats != None: json_item['score'] = stats
            else: stats = ''
            json_data[i] = json_item
            if task in (t, None):
                any_subms = True
                ans += tt.format(id=i,
                                 task=html.escape(t),
                                 status=html.escape(status),
                                 score=stats,
                                 color=get_submission_color(status, stats))
        return (pkgutil.get_data(
            'ejui', 'subms_t.html' if have_score else
            'subms_no_score.html').decode('utf-8').format(data=ans), any_subms,
                json_data)
Ejemplo n.º 9
0
def format_page(page,
                text,
                tl=None,
                subms=None,
                clars=None,
                status=None,
                scores=None,
                jjs_devmode=None):
    url, cookie = force_session()
    with bj.may_cache(url, cookie):
        if tl == None: tl = bj.task_list(url, cookie)
        if clars == None:
            try:
                clars = list(zip(*bj.clars(url, cookie)))
            except:
                clars = []
        if status == None:
            try:
                status = bj.status(url, cookie)
            except:
                status = {}
        if scores == None:
            try:
                scores = bj.scores(url, cookie)
            except:
                scores = {}
        if subms == None: subms = format_submissions(None)[2]
        if jjs_devmode == None:
            jjs_devmode = get_contest_info(url, cookie)[2].get(
                'jjs_devmode', False)
    data = [('main', '', '/', '<b>ejui</b>', '')]
    dyn_style = ''
    for i, j in enumerate(tl):
        if status.get(j, None) != None or scores.get(j, None) != None:
            st = status.get(j, 'True')
            sc = scores.get(j, 0)
            c1 = get_submission_color(st, sc, 1)
            c2 = get_submission_color(st, sc, 2)
            c = 'data-color1="%s" data-color2="%s" data-taskid="%s"' % (
                c1, c2, html.escape(j))
            dyn_style += '#toolbar_item_task%d\n{\n    background: %s !important;\n}\n\n' % (
                i, c2 if page == 'task%d' % i else c1)
        else:
            c = 'data-taskid="%s"' % html.escape(j)
        data.append(('task%d' % i, '', '/task/%d' % i, html.escape(j), c))
    if dyn_style:
        dyn_style = '<style id="dyn_style">\n' + dyn_style.strip(
        ) + '\n</style>'
    data2 = [('error', '', '', '<div id="error_btn">!</div>', ''),
             ('subms', '', '/submissions', 'Submissions', ''),
             ('scoreboard', '', '/scoreboard', 'Scoreboard', ''),
             ('logout', 'toolbar_icon', '/logout',
              '<img src="/logout.png" alt="Log out" />', '')]
    if clars or page == 'clars':
        data2.insert(3, ('clars', 'toolbar_icon', '/clars',
                         '<img src="/mail.png" alt="Clarifications" />', ''))
    head = ''
    for a, b, c, d, e in data:
        if a == page:
            b += ' selected'
        head += '<a id="toolbar_item_' + a + '" class="' + b + '" href="' + c + '" onclick="ajax_load(this); return false"'
        if e:
            head += ' ' + e
        head += '>' + d + '</a>'
    head += '</td><td align=right>'
    for a, b, c, d, e in data2:
        head += '<a id="toolbar_item_' + a + '" class="' + b + '" href="' + c + '" onclick="ajax_load(this); return false"'
        if a == page:
            head += ' class=selected'
        if e:
            head += ' ' + e
        head += '>' + d + '</a>'
    head += ''
    if page.startswith('task'):
        curr_task = repr(tl[int(page[4:])])
    else:
        curr_task = 'null'
    return pkgutil.get_data('ejui', 'skel.html').decode('utf-8').format(
        body_style=(' style="background: url(/jjs_devmode.svg)"'
                    if jjs_devmode else ''),
        task=curr_task,
        subm_preload=json.dumps(subms),
        dynamic_styles=dyn_style,
        head=head,
        body=text)
Ejemplo n.º 10
0
def do_asubmit(self, cmd, *, afmt=False):
    """
    usage: asubmit [-w] [-x <extension>] <task> <lang_id> <file>

    Submit a new solution, using style-fixed version.
    Uses a specific style fixer if -x is specified.
    Waits until testing ends if -w is specified.
    """
    modname = ''
    wait = False
    sp = shlex.split(cmd)
    if len(sp) not in (range(3, 7) if not afmt else (1, 3)):
        return self.do_help('aformat' if afmt else 'asubmit')
    if not afmt and sp[0] == '-w':
        wait = True
        del sp[0]
    if len(sp) not in ((3, 5) if not afmt else (1, 3)):
        return self.do_help('aformat' if afmt else 'asubmit')
    if sp[0] == '-x':
        modname = sp[1]
        del sp[:2]
        if modname[:1] == '.':
            modname = 'brutejudge.commands.asubmit.format_' + modname[1:]
    if len(sp) != (1 if afmt else 3):
        return self.do_help('aformat' if afmt else 'asubmit')
    try:
        name = sp[-1]
        module = None
        ext = os.path.splitext(name)[1][1:]
        modname, *modargs = modname.split(',')
        modargs = set(modargs)
        if not modname: modname = 'brutejudge.commands.asubmit.format_' + ext
        try:
            module = __import__(modname, fromlist=True)
        except ImportError:
            pass
        if hasattr(module, 'cheats'):
            import brutejudge.cheats
            brutejudge.cheats.cheating(self)
        if not getattr(module, 'check_exists', check_exists)(name, modargs):
            raise BruteError("File not found.")
        if hasattr(module, 'read_file'):
            data = module.read_file(name, modargs)
        else:
            with open(name, 'rb') as file:
                data = file.read()
        if hasattr(module, 'format'):
            data = module.format(data, modargs)
    except UnicodeDecodeError:
        raise BruteError("File is binary.")
    if afmt:
        if isinstance(data, str): data = data.encode('utf-8')
        sys.stdout.buffer.write(data)
        sys.stdout.buffer.flush()
        return
    with may_cache(self.url, self.cookie):
        try:
            task_id = next(i.id for i in tasks(self.url, self.cookie)
                           if i.short_name == sp[0])
        except StopIteration:
            raise BruteError("No such task.")
        if not sp[1].isnumeric():
            sp[1] = get_lang_id(self, sp[1], task_id)
        before = submissions(self.url, self.cookie)
        submit_solution(self.url, self.cookie, task_id, int(sp[1]), data)
    after = submissions(self.url, self.cookie)
    if before == after:
        raise BruteError("Error while sending.")
    else:
        print('Submission ID is', after[0].id)
        if wait: self.do_astatus(str(after[0].id))