Beispiel #1
0
def rejudgeSubmission( request, sid):
    logger.info(str(request).replace("\n\r","\t"))
    """
    rejudge the very submission with the specific sid
    """
    try:
        sid = int( sid)
        u = User.getSessionUser( request.session)
        if not u:
            raise Err( request, err='not login')

        try:
            s = Submission.getById( sid)
        except:
            raise Err( request, err='no submission',
                    log_format=( '{0}'.format( sid), ''),
                    user_format=( u'{0}'.format( sid), u'不要搞笑!!'),
                    )

        if not s.problem_index.contest.course_class.canBeManaged( u):
            raise Err( request, err = 'no priv')

        Submission.rejudgeSubmission( s)

        return redirect( 'Submission:contest_status', contest_id=s.problem_index.contest.cid) 

    except Exception as e:
        logger.error(str(e).replace("\n\r","\t"))
        return render( request, Const.NEW_ERROR_PAGE, { 'errmsg': unicode(e), }, )
Beispiel #2
0
def rejudgeSubmission( request, sid):
    logger.info(str(request).replace("\n\r","\t"))
    """
    rejudge the very submission with the specific sid
    """
    try:
        sid = int( sid)
        u = User.getSessionUser( request.session)
        if not u:
            raise Err( request, err='not login')

        try:
            s = Submission.getById( sid)
        except:
            raise Err( request, err='no submission',
                    log_format=( '{0}'.format( sid), ''),
                    user_format=( u'{0}'.format( sid), u'不要搞笑!!'),
                    )

        if not s.problem_index.contest.course_class.canBeManaged( u):
            raise Err( request, err = 'no priv')

        Submission.rejudgeSubmission( s)

        return redirect( 'Submission:contest_status', contest_id=s.problem_index.contest.cid) 

    except Exception as e:
        logger.error(str(e).replace("\n\r","\t"))
        return render( request, Const.NEW_ERROR_PAGE, { 'errmsg': unicode(e), }, )
Beispiel #3
0
    def getScore(self):
        from Submission.models import Submission
        acUserCount = Submission.submissionList(cp=self).filter(status='Accepted').values('user').distinct().count()
        allUser = self.contest.course_class.getAllStudents()

        # eliminate users not in this contest, eg: admin
        allUidWithSubmission = set([u['user'] for u in Submission.submissionList(c=self.contest).values('user')])
        userWithSubmissionCount = len(filter(lambda u: u.uid in allUidWithSubmission, allUser))
        score = 0
        while acUserCount <= userWithSubmissionCount and score != 3000:
            score += 500
            acUserCount *= 2
        return score
Beispiel #4
0
    def addRecord(cls, cp_set):

        formalSubmissions=[]
        for cp in cp_set:
            already = cls.objects.filter(contest_problem=cp)
            if already:
                continue
            submissions = Submission.submissionList(cp=cp, sta='Accepted').order_by('sid')
            usertable = {}
          #  submissions2 = []
            for ss in submissions:
                user = ss.user
                ok = usertable.get(user,0)
                if ok==0:
                    usertable[user] = ss.sid
            for i in submissions:
                if i.sid!=usertable[i.user]:
                    continue
                for j in submissions:
                    if j.sid==usertable[j.user] and i.sid<j.sid and i.code_language==j.code_language and i.user!=j.user:
                        ct = Cheat()
                        ct.contest_problem = cp
                        ct.sub1 = i
                        ct.sub2 = j
                        ct.status = -1
                        ct.ratio = 0
                        formalSubmissions.append(ct)
                        #ct.save()
        cls.objects.bulk_create(formalSubmissions)

        """
Beispiel #5
0
def getContestResult(c):
    try:
        allSub = Submission.submissionList(c=c)
        allProb = c.getContestProblem()
        ac_cnt = {}
        sub_cnt = {}
        for pinfo in allProb:
            ac_cnt[pinfo.problem_index] = 0
            sub_cnt[pinfo.problem_index] = 0

        for sinfo in allSub:
            if sinfo.status == "Accepted":
                ac_cnt[sinfo.problem_index.problem_index] += 1
            sub_cnt[sinfo.problem_index.problem_index] += 1
        res = []
        for pinfo in allProb:
            tdict = {}
            tdict["ac_cnt"] = ac_cnt[pinfo.problem_index]
            tdict["sub_cnt"] = sub_cnt[pinfo.problem_index]
            if sub_cnt[pinfo.problem_index] == 0:
                tdict["ac_ratio"] = 0.00
            else:
                tdict["ac_ratio"] = round(ac_cnt[pinfo.problem_index] * 100.0 / sub_cnt[pinfo.problem_index], 2)
            res.append(tdict)
        return res
    except Exception as e:
        return []
Beispiel #6
0
def getContestResult(c):
    try:
        allSub = Submission.submissionList(c=c)
        allProb = c.getContestProblem()
        ac_cnt={}
        sub_cnt={}
        for pinfo in allProb:
            ac_cnt[pinfo.problem_index]=0
            sub_cnt[pinfo.problem_index]=0
        
        for sinfo in allSub:
            if sinfo.status == "Accepted":
                ac_cnt[sinfo.problem_index.problem_index]+=1
            sub_cnt[sinfo.problem_index.problem_index]+=1
        res=[]
        for pinfo in allProb:
            tdict={}
            tdict["ac_cnt"]=ac_cnt[pinfo.problem_index]
            tdict["sub_cnt"]=sub_cnt[pinfo.problem_index]
            if sub_cnt[pinfo.problem_index] == 0:
                tdict["ac_ratio"]=0.00
            else:
                tdict["ac_ratio"]=round(ac_cnt[pinfo.problem_index]*100.0/sub_cnt[pinfo.problem_index],2)
            res.append(tdict)
        return res
    except Exception as e:
        return []
Beispiel #7
0
def board(request):
    cid = request.GET.get('cid', 1)
    contest = Contest.getById(cid)
    '''
    if contest == False :
        errmsg = u'不存在考试编号为' + str(cid) + u'的考试'
        return render(request, 'error.html', {'errmsg' : errmsg, 'user' : User.getSessionUser(request.session)})
    contestProblem = contest.getContestProblem()
    startTime = contest.start_time
    '''
    submission = Submission.submissionList(cid = cid)
    
    problemIndex = list()
    problemIndex.append('A')#
    problemIndex.append('B')#
    '''
    for i in contestProblem:
        problemIndex.append(i.problem_index)
    '''
    problemIndex.sort()
    
    data = dict()
    cnt = 0
    now = datetime.now()
    now = now - now
    for i in submission :
        if i.user.username not in data :
            data[i.user.username] = [cnt, i.user.username,  0, now] #id, username, solved, time, A, B, etc
            cnt = cnt + 1
            for j in problemIndex :
                data[i.user.username].append({'ac' : 0, 'pd' : 0, 'other' : 0})

        tmp = data[i.user.username]
        tp = tmp[i.problem_index.problem_index + 3]
        if tp['ac'] == 0 :
            if ('Accepted', 'Accepted') in i.status :
                tp['ac'] = 1
                tp['other'] = tp['other'] + 1
                tmp[3] += datetime.timedelta((tp['pd'] + tp['ac'] + tp['other']) * 20) + (i.submission_time - startTime)
                tmp[2] += 1
            elif ('Pending', 'Pending') in i.status :
                tp['pd'] = tp['tp'] + 1
            else :
                tp['other'] = tp['other'] + 1

    out = list()
    for i in data :
        out.append(data[i])
   
    out.append([0, 'zhangzhou', 12, -(datetime.now() - datetime.now()) , {'ac': 0, 'pd' : 2, 'other' : 0}, {'ac' : 0,'pd' : 0, 'other' : 0}])#
    out.append([-1, 'lyy', 12, -(datetime.now() - datetime.now()), {'ac': 1, 'pd' : 2, 'other' : 3}, {'ac': 0, 'pd' : 0, 'other' : 0}])#
    out.sort(cmp = mycmp)
    cnt = 1
    for i in out :
        i[0] = cnt
        cnt = cnt + 1
        i[3] = (datetime(2000, 1, 1, 0, 0, 0, 0) + i[3]).strftime("%H:%M:%S")

    return render(request, 'lyy/board.html', {'out' : out, 'problemIndex' : problemIndex, 'user' : User.getSessionUser(request.session)})
Beispiel #8
0
def showContestProblemStatistics(request, p_index=None, cid=None):
    logger.info(str(request).replace("\n", "\t"))
    """
    view used to show statistics of a problem in a contest
    """
    try:
        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, err='not login')

        cid = int(cid)
        c = Contest.getById(cid)

        p_index = p_index if p_index else ''

        try:
            contest_problem = ContestProblem.getBy(c, p_index)
        except:
            raise Err(
                request,
                err='no contestproblem',
                log_format=('{0}'.format(p_index), ''),
                user_format=(u'{0}'.format(p_index), u'搞错了什么吧!'),
            )

        if not contest_problem.contest.course_class.canBeManaged(u):
            raise Err(request, err='no priv')

        all_submissions = Submission.submissionList(cp=contest_problem)
        submissions = all_submissions.filter(
            status='Accepted').order_by('run_time')[:20]

        status_list = []
        for i in Const.STATUS_CN.iterkeys():
            status_list.append({
                'name':
                Const.STATUS_CN[i],
                'number':
                all_submissions.filter(status=i).count()
            })

        for sub_s in submissions:
            sub_s.status_color = Const.STATUS_COLOR[
                sub_s.status] if sub_s.status in Const.STATUS_COLOR else ''
            sub_s.status_cn = Const.STATUS_CN[sub_s.status]

        return render(
            request, 'newtpl/statistic/contest_problem.html', {
                'submissions': submissions,
                'contest_problem': contest_problem,
                'status_list': status_list,
                'tpl': {
                    'sp': True
                }
            })

    except Exception as e:
        logger.error(str(e).replace("\n", "\t"))
        return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
Beispiel #9
0
    def getScore(self):
        from Submission.models import Submission
        acUserCount = Submission.submissionList(cp=self).filter(
            status='Accepted').values('user').distinct().count()
        allUser = self.contest.course_class.getAllStudents()

        # eliminate users not in this contest, eg: admin
        allUidWithSubmission = set([
            u['user']
            for u in Submission.submissionList(c=self.contest).values('user')
        ])
        userWithSubmissionCount = len(
            filter(lambda u: u.uid in allUidWithSubmission, allUser))
        score = 0
        while acUserCount <= userWithSubmissionCount and score != 3000:
            score += 500
            acUserCount *= 2
        return score
Beispiel #10
0
def getSBC(c):
    ckey = 'Submission_csbc' + str(c.pk)

    sub_all = cache.get(ckey)
    #    with open('/home/buptacm/log2.txt', 'w') as f2:
    #        print >> f2, sub_all
    if sub_all == None:
        sub_all = Submission.submissionList(c=c)
        cache.set(ckey, sub_all, Const.CACHE_TIME_FIRST)
        #cache.set(ckey,sub_all,15)
    return sub_all
Beispiel #11
0
def getSBC(c):
    ckey = 'Submission_csbc' + str(c.pk)

    sub_all = cache.get(ckey)
#    with open('/home/buptacm/log2.txt', 'w') as f2:
#        print >> f2, sub_all
    if sub_all == None:
        sub_all = Submission.submissionList(c=c)
        cache.set(ckey,sub_all,Const.CACHE_TIME_FIRST)
        #cache.set(ckey,sub_all,15)
    return sub_all
Beispiel #12
0
def getContestUserResult(c, u):
    try:
        allSub = Submission.submissionList(c=c)
        allProb = c.getContestProblem()
        ac_cnt = {}
        for pinfo in allProb:
            ac_cnt[pinfo.problem_index] = 0

        for sinfo in allSub:
            if u != sinfo.user:
                continue
            if sinfo.status == "Accepted":
                ac_cnt[sinfo.problem_index.problem_index] = 1
        res = []
        for pinfo in allProb:
            res.append(ac_cnt[pinfo.problem_index])
        return res
    except Exception as e:
        return []
Beispiel #13
0
def getContestUserResult(c, u):
    try:
        allSub = Submission.submissionList(c=c)
        allProb = c.getContestProblem()
        ac_cnt={}
        for pinfo in allProb:
            ac_cnt[pinfo.problem_index]=0
        
        for sinfo in allSub:
            if u != sinfo.user:
                continue
            if sinfo.status == "Accepted":
                ac_cnt[sinfo.problem_index.problem_index] = 1
        res=[]
        for pinfo in allProb:
            res.append(ac_cnt[pinfo.problem_index])
        return res
    except Exception as e:
        return []
Beispiel #14
0
def showContestProblemStatistics( request, p_index=None, cid=None):
    logger.info(str(request).replace("\n","\t"))
    """
    view used to show statistics of a problem in a contest
    """
    try:
        u = User.getSessionUser(request.session)
        if not u:
            raise Err( request, err='not login')

        cid = int(cid)
        c = Contest.getById(cid)

        p_index = p_index if p_index else ''

        try:
            contest_problem = ContestProblem.getBy( c, p_index)
        except:
            raise Err( request, err='no contestproblem', 
                    log_format=( '{0}'.format(p_index), ''), 
                    user_format=( u'{0}'.format( p_index), u'搞错了什么吧!'),
                    )

        if not contest_problem.contest.course_class.canBeManaged( u):
            raise Err( request, err = 'no priv')

        all_submissions = Submission.submissionList( cp=contest_problem )
        submissions = all_submissions.filter( status='Accepted').order_by('run_time')[:20]

        status_list = []
        for i in Const.STATUS_CN.iterkeys():
            status_list.append( { 'name': Const.STATUS_CN[i], 'number': all_submissions.filter( status=i).count()} )

        for sub_s in submissions:
            sub_s.status_color = Const.STATUS_COLOR[sub_s.status] if sub_s.status in Const.STATUS_COLOR else ''
            sub_s.status_cn = Const.STATUS_CN[ sub_s.status]

        return render( request, 'newtpl/statistic/contest_problem.html', { 'submissions': submissions, 'contest_problem': contest_problem, 'status_list': status_list, 'tpl': { 'sp': True } })

    except Exception as e:
        logger.error(str(e).replace("\n","\t"))
        return render(request, Err.ERROR_PAGE, { 'errmsg': unicode(e) } )
Beispiel #15
0
    def addRecord(cls, cp_set):

        already = cls.objects.all()
        # return
        submissions = []
        cpLen = len(cp_set)
        for cp in cp_set:
            submissions.extend(list(Submission.submissionList(cp=cp, sta="Accepted")))
        #    print submissions
        # return
        is_user_in = {}
        records = []
        for ss in submissions:
            user = ss.user
            ok = is_user_in.get(user, 0)
            if ok == 0:
                is_user_in[user] = 1
                records.append(ss)

        #   print records

        length = len(records)

        for record1 in submissions:
            for record2 in submissions:
                if (
                    record1.sid < record2.sid
                    and record1.problem_index == record2.problem_index
                    and record1.code_language == record2.code_language
                    and record1.user != record2.user
                ):
                    ct = Cheat()
                    ct.contest_problem = record1.problem_index
                    ct.sub1 = record1
                    ct.sub2 = record2
                    ct.status = -1
                    ct.ratio = 0
                    already_one = already.filter(contest_problem=ct.contest_problem)
                    already_one = already_one.filter(sub1=ct.sub1)
                    already_one = already_one.filter(sub2=ct.sub2)
                    if already_one.count() == 0:
                        ct.save()
Beispiel #16
0
    def addRecord(cls, cp_set):

        already = cls.objects.all()
        #return
        submissions = []
        cpLen = len(cp_set)
        for cp in cp_set:
            submissions.extend(
                list(Submission.submissionList(cp=cp, sta='Accepted')))
    #    print submissions
    # return
        is_user_in = {}
        records = []
        for ss in submissions:
            user = ss.user
            ok = is_user_in.get(user, 0)
            if ok == 0:
                is_user_in[user] = 1
                records.append(ss)

    #   print records

        length = len(records)

        for record1 in submissions:
            for record2 in submissions:
                if record1.sid < record2.sid and record1.problem_index == record2.problem_index and record1.code_language == record2.code_language and record1.user != record2.user:
                    ct = Cheat()
                    ct.contest_problem = record1.problem_index
                    ct.sub1 = record1
                    ct.sub2 = record2
                    ct.status = -1
                    ct.ratio = 0
                    already_one = already.filter(
                        contest_problem=ct.contest_problem)
                    already_one = already_one.filter(sub1=ct.sub1)
                    already_one = already_one.filter(sub2=ct.sub2)
                    if already_one.count() == 0:
                        ct.save()
Beispiel #17
0
    def get_board(self, b):
        c = b.contest
        allSubmission = Submission.submissionList(c=c).order_by('sid')
        allUser = c.course_class.getAllStudents()
        allContestProblem = c.getContestProblem()

        problemInfos = {cp.problem_index:{'idx': cp.problem_index, 'total_score': cp.getScore(), 'score': 0, 'ac': 0} for cp in allContestProblem}
        userInfos = { userInfo.uid: {
            'uid': userInfo.uid,
            'username': userInfo.username,
            'nickname': userInfo.nickname,
            'score': 0,
            'problem_infos': copy.deepcopy(problemInfos)
            } for userInfo in allUser}

        for s in allSubmission:
            uid = s.user.uid
            if not uid in userInfos:
                continue
            idx = s.problem_index.problem_index
            if userInfos[uid]['problem_infos'][idx]['ac'] > 0 or s.status in Const.STATUS_NO_USE:
                continue
            submissionTime = int(math.ceil((s.submission_time-c.start_time).total_seconds()/60))
            if s.status == 'Accepted':
                userInfos[uid]['problem_infos'][idx]['ac'] = 1 - userInfos[uid]['problem_infos'][idx]['ac']
                userInfos[uid]['problem_infos'][idx]['ac_time'] = submissionTime
                userInfos[uid]['problem_infos'][idx]['score'] = max(problemInfos[idx]['total_score'] - problemInfos[idx]['total_score'] / 250 * submissionTime - 50 * (userInfos[uid]['problem_infos'][idx]['ac'] - 1), problemInfos[idx]['total_score'] / 250 * 75);
                userInfos[uid]['score'] += userInfos[uid]['problem_infos'][idx]['score']
            else:
                userInfos[uid]['problem_infos'][idx]['ac'] -= 1
                userInfos[uid]['problem_infos'][idx]['score'] = userInfos[uid]['problem_infos'][idx]['ac']

        problemInfos = sorted(problemInfos.values(), key=lambda problem: problem['idx'])
        userInfos = sorted(userInfos.values(), key=lambda user: user['score'], reverse=True)
        curRank = 0
        for idx, user in enumerate(userInfos):
            if idx == 0 or user['score'] != userInfos[idx-1]['score']: curRank += 1
            user['rank'] = curRank
        return {'problem_infos': problemInfos, 'user_infos': userInfos}
Beispiel #18
0
    def addRecord(cls, contestid):

        already = cls.objects.all()
        #return
        submissions = Submission.submissionList(c=contestid, sta='Accepted')
        # return
        is_user_in = {}
        record_list = []
        for ss in submissions:
            user = ss.user
            ok = is_user_in.get(user, 0)
            if ok == 0:
                is_user_in[user] = 1
                record = []
                record.append(ss.problem_index)
                record.append(ss.user)
                record.append(ss.code_file)
                record_list.append(record)

        length = len(record_list)

        for i in range(length):
            for j in range(length):
                if i < j and record_list[i][0] == record_list[j][
                        0] and record_list[i][1] != record_list[j][1]:
                    ct = Cheat()
                    ct.contest_problem = record_list[i][0]
                    ct.user1 = record_list[i][1]
                    ct.user2 = record_list[j][1]
                    ct.code_file1 = record_list[i][2]
                    ct.code_file2 = record_list[j][2]
                    ct.status = -1
                    ct.ratio = 0
                    already_one = already.filter(
                        contest_problem=ct.contest_problem)
                    already_one = already_one.filter(user1=ct.user1)
                    already_one = already_one.filter(user2=ct.user2)
                    if already_one.count() == 0:
                        ct.save()
Beispiel #19
0
    def addRecord(cls, contestid):

        already = cls.objects.all()
        # return
        submissions = Submission.submissionList(c=contestid, sta="Accepted")
        # return
        is_user_in = {}
        record_list = []
        for ss in submissions:
            user = ss.user
            ok = is_user_in.get(user, 0)
            if ok == 0:
                is_user_in[user] = 1
                record = []
                record.append(ss.problem_index)
                record.append(ss.user)
                record.append(ss.code_file)
                record_list.append(record)

        length = len(record_list)

        for i in range(length):
            for j in range(length):
                if i < j and record_list[i][0] == record_list[j][0] and record_list[i][1] != record_list[j][1]:
                    ct = Cheat()
                    ct.contest_problem = record_list[i][0]
                    ct.user1 = record_list[i][1]
                    ct.user2 = record_list[j][1]
                    ct.code_file1 = record_list[i][2]
                    ct.code_file2 = record_list[j][2]
                    ct.status = -1
                    ct.ratio = 0
                    already_one = already.filter(contest_problem=ct.contest_problem)
                    already_one = already_one.filter(user1=ct.user1)
                    already_one = already_one.filter(user2=ct.user2)
                    if already_one.count() == 0:
                        ct.save()
Beispiel #20
0
def showBoardByStatus(request, cId, balloon=False):
    df = open("/home/buptacm/log.txt", "w")
    print >> df, "111"

    logger.info(str(request).replace("\n", "\t"))
    try:
        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, 'not login')
        try:
            cId = int(cId)
            c = Contest.getById(cId)
        except:
            raise Err(request, 'no resource')

        can_manage = True
        try:
            c.canBeManaged(u)
        except:
            can_manage = False

        try:
            c.canEnterContest(u)
        except:
            raise Err(request, 'no priv')

        print >> df, "1"

        res = cache.get(cId)
        if res != None:
            info, rank, allProb = res
            if not can_manage and not c.contest_type == 0:
                rank = filter(lambda x: u.uid == x['uid'], info)
            if can_manage and balloon:
                return render(
                    request, "newtpl/statistic/board_test.html", {
                        'info':
                        info,
                        'board_body':
                        render_to_response("newtpl/statistic/board_body.html",
                                           {
                                               'rank': rank
                                           }).content,
                        'allProb':
                        allProb,
                        'contest':
                        c
                    })
                #return render(request,"newtpl/statistic/board2.html", {'info': info, 'rank': rank,'allProb': allProb, 'contest': c})
            else:
                return render(request, "newtpl/statistic/board.html", {
                    'info': info,
                    'rank': rank,
                    'allProb': allProb,
                    'contest': c
                })
                #return render(request,"newtpl/statistic/board_test.html", {'info': info, 'board_body': render_to_response("newtpl/statistic/board_body.html", {'rank': rank}).content,'allProb': allProb, 'contest': c})

        print >> df, "2"

        board_stop_time = c.start_time + timedelta(minutes=c.board_stop)
        allSub = Submission.submissionList(
            c=c, board_stop_time=board_stop_time).order_by('sid')
        #allSub = Submission.submissionList(c=c)
        #allSub = allSub.filter(submission_time < board_stop_time).order_by('sid')
        #allSub = Submission.objects.filter(c=c).filter(submission_time < board_stop_time).order_by('sid')
        allUser = c.course_class.getAllStudents()
        allProb = c.getContestProblem()

        pInfoDict = {
            pinfo.problem_index: {
                'idx': pinfo.problem_index,
                'ac': 0,
                'pen': 0,
                'sub': 0
            }
            for pinfo in allProb
        }
        info = {
            uinfo.uid: {
                'uid': uinfo.uid,
                'username': uinfo.username,
                'nickname': uinfo.nickname,
                'ac': 0,
                'pen': 0,
                'sub': 0,
                'pinfo': copy.deepcopy(pInfoDict)
            }
            for uinfo in allUser
        }

        print >> df, "3"

        if c.board_type == 0:  # acm style board
            for sinfo in allSub:
                if not sinfo.user.uid in info:
                    continue
                uid = sinfo.user.uid
                idx = sinfo.problem_index.problem_index
                if info[uid]['pinfo'][idx]['ac'] > 0:
                    continue
                if sinfo.status in [
                        'Pending', 'Rejudging', 'Compiling', 'System Error'
                ]:
                    continue
                td = sinfo.submission_time - c.start_time
                info[uid]['pinfo'][idx]['sub'] += 1
                if sinfo.status == "Accepted":
                    info[uid]['pinfo'][idx][
                        "ac"] = 1 - info[uid]['pinfo'][idx]["ac"]
                    info[uid]['pinfo'][idx]["ac_time"] = int(
                        math.ceil(td.total_seconds() / 60))
                    info[uid]['pinfo'][idx]["pen"] += int(
                        math.ceil(td.total_seconds() / 60))
                    if (not 'fb_time' in pInfoDict[idx]
                        ) or td < pInfoDict[idx]['fb_time']:
                        pInfoDict[idx]['fb_time'] = td
                        pInfoDict[idx]['fb_uid'] = uid
                else:
                    info[uid]['pinfo'][idx]["ac"] -= 1
                    info[uid]['pinfo'][idx]["pen"] += 20

            for idx, pinfo in pInfoDict.iteritems():
                if 'fb_time' in pinfo:
                    info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True

            info = info.values()
            for i in info:
                i['pinfo'] = i['pinfo'].values()
                i['pinfo'].sort(key=lambda x: x['idx'])
                if u.university_id != 5:
                    i['sub'] = 1
                for pinfo in i['pinfo']:
                    if pinfo['ac'] > 0:
                        i['ac'] += 1
                        i['pen'] += pinfo['pen']
                    i['sub'] += pinfo['sub']
        else:
            for sinfo in allSub:
                if not sinfo.user.uid in info:
                    continue
                uid = sinfo.user.uid
                idx = sinfo.problem_index.problem_index
                other_info = eval(sinfo.other_info)
                tscore = int(other_info['score'])

                if info[uid]['pinfo'][idx]['ac'] >= tscore:
                    continue
                if sinfo.status in [
                        'Pending', 'Rejudging', 'Compiling', 'System Error'
                ]:
                    continue
                td = sinfo.submission_time - c.start_time
                info[uid]['pinfo'][idx]['sub'] += 1
                info[uid]['pinfo'][idx]['ac'] = tscore
                info[uid]['pinfo'][idx]["pen"] += int(
                    math.ceil(td.total_seconds() /
                              60)) - info[uid]['pinfo'][idx].get("ac_time", 0)
                info[uid]['pinfo'][idx]["ac_time"] = int(
                    math.ceil(td.total_seconds() / 60))
                info[uid]['pinfo'][idx]['idx'] = idx
                if sinfo.status == "Accepted":
                    if (not 'fb_time' in pInfoDict[idx]
                        ) or td < pInfoDict[idx]['fb_time']:
                        pInfoDict[idx]['fb_time'] = td
                        pInfoDict[idx]['fb_uid'] = uid

            for idx, pinfo in pInfoDict.iteritems():
                if 'fb_time' in pinfo:
                    info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True

            info = info.values()
            for i in info:
                if u.university_id != 5:
                    i['sub'] = 1
                i['pinfo'] = i['pinfo'].values()
                for pinfo in i['pinfo']:
                    if pinfo['ac'] > 0:
                        i['ac'] += pinfo['ac']
                        i['pen'] += pinfo['pen']
                    i['sub'] += pinfo['sub']

        print >> df, "4"

        info.sort(
            key=lambda x: x['ac'] * 262144 * 2 - x['pen'] * 2 + bool(x['sub']),
            reverse=True)
        for r, i in enumerate(info, 1):
            i['rank'] = r

        rank = info
        cache.set(cId, (info, rank, allProb), 5)

        print >> df, "5"

        if not can_manage and not c.contest_type == 0:
            rank = filter(lambda x: u.uid == x['uid'], info)

        print >> df, "6"
        if can_manage and balloon:
            return render(
                request, "newtpl/statistic/board_test.html", {
                    'info':
                    info,
                    'board_body':
                    render_to_response("newtpl/statistic/board_body.html", {
                        'rank': rank
                    }).content,
                    'allProb':
                    allProb,
                    'contest':
                    c
                })
            #return render(request,"newtpl/statistic/board2.html", {'info': info, 'rank': rank,'allProb': allProb, 'contest': c})
        else:
            print >> df, info
            print >> df, rank
            print >> df, allProb
            print >> df, c
            return render(
                request, "newtpl/statistic/board_test.html", {
                    'info':
                    info,
                    'board_body':
                    render_to_response("newtpl/statistic/board_body.html", {
                        'rank': rank
                    }).content,
                    'allProb':
                    allProb,
                    'contest':
                    c
                })
            #return render(request,"newtpl/statistic/board.html", {'info': info, 'rank': rank,'allProb': allProb, 'contest': c})
    except Exception as e:
        logger.error(str(e).replace("\n", "\t"))
        return render(request, Err.ERROR_PAGE)
Beispiel #21
0
def addSubmission(request, contest_id=None, problem_index=None):
    logger.info(str(request).replace("\n\r","\t"))
    """
    view used to add submission
    """
    try:
        contest_id = int(contest_id)

        u = User.getSessionUser( request.session)
        if not u:
            raise Err( request, err='not login')

        if not contest_id:
            raise Err( request, err='request err', 
                    log_format=( 'contest id', 'UNDEFINED'), 
                    user_format=( u'考试编号', u'你吃了么!!!'),
                    )

        elif not problem_index:
            raise Err( request, err='request err', 
                    log_format=( 'problem index', 'UNDEFINED'), 
                    user_format=( u'题目序号', u'哪里去了!!'),
                    )
        else:
            try:
                c = Contest.getById( contest_id )
            except:
                raise Err( request, err='no contest', 
                        log_format=( '{0}'.format(cid), ''), 
                        user_format=( u'{0}'.format( cid), u'别做坏事!'),
                        )

            try:
                p_index = ContestProblem.getBy(c=c, idx=problem_index)
            except:
                raise Err( request, err='no contestproblem', 
                        log_format=( '{0}'.format( problem_index), ''), 
                        user_format=( u'{0}'.format( problem_index), u'别乱写好么!!'),
                        )

            p = p_index.problem
            
            if not Submission.canSubmitCode( u, p_index ):
                raise Err( request, err = 'submit err', 
                        log_format = ( 'no priv to submit', 'contest ended or no priv to attend the contest'),
                        user_format = ( u'您没有提交该题的权限', u'考试已结束或者您没有参加本场考试的权限')
                        )

        lang_list = []
        if c.lang_limit & 1 == 1:
            lang_list.append( ('gcc','GNU C'))
        if (c.lang_limit >> 1) & 1 == 1:
            lang_list.append( ('g++','GNU C++'))
        if (c.lang_limit >> 2) & 1 == 1:
            lang_list.append( ('java', 'JAVA'))
            
        if request.method == 'POST':
            form = addSubmissionForm(lang_list, request.POST)

            if form.is_valid():
                sub_name = str( datetime.now())
                time_str = sub_name.split('.')
                time_str.pop()

                for i in ['-',':','.',' ']:
                    sub_name = sub_name.replace(i,'_')

                import os
                code_file_path = os.path.join( Const.SUBMISSION_TMP_PATH, "{0:010d}_{1}".format( u.uid, sub_name))
                code_length = 0

                # head_details: details of the submission added at the head of the code file
                head_details = ''
                head_details += '/*\n'
                head_details += 'USER_ID: ' + str(u) + '\n'
                head_details += 'PROBLEM: ' + str(p.pid) + '\n'
                head_details += 'SUBMISSION_TIME: ' + time_str[0] + '\n'
                head_details += '*/\n'

                if 'code_file' in request.FILES:
                    default_storage.save( code_file_path, request.FILES['code_file'])
                else:
                    if form.cleaned_data['code']:
                        default_storage.save( code_file_path, ContentFile( head_details + form.cleaned_data['code']))
                    else:
                        raise Err( request, err='request err', 
                                log_format=( 'code', 'no input'), 
                                user_format=( u'代码呢!', u'不写代码交什么交!!'),
                                )

                code_length = default_storage.size( code_file_path)
                sub_lang = form.cleaned_data['language']

                if sub_lang not in map( lambda x: x[0], lang_list):
                    raise Err( request, err='illegal language', 
                            log_format=( '{0}'.format( sub_lang), 'blabla'), 
                            user_format=( u'{0}'.format( sub_lang), u'别瞎搞成不!!'),
                            )

                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
                if x_forwarded_for:
                    ip = x_forwarded_for.split(',')[0]
                else:
                    ip = request.META.get('REMOTE_ADDR')

                additional = { 'submit_ip': ip}
                Submission.addSubmission( u, p_index, code_file_path, sub_lang, code_length, additional)

                return redirect('Submission:contest_status',contest_id=contest_id) # could it be okay?
            else:
                raise Exception(u'form invalid')
            # the usage of url.name in urls.py
        # not POST method
        else:
            form = addSubmissionForm(lang_list)

        return render( request, 'newtpl/submission/submit.html', { 'form': form, 'tpl': {'sp':True}, 'contest': c, 'cp': p_index}, )# 'test_info': form.cleaned_data['language']})

    except Exception as e:
        logger.error(str(e).replace("\n\r","\t"))
        return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
Beispiel #22
0
def showBoardByStatus(request, cId):
    logger.info(str(request).replace("\n", "\t"))
    try:
        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, 'not login')
        try:
            cId = int(cId)
            c = Contest.getById(cId)
        except:
            raise Err(request, 'no resource')

        can_manage = True
        try:
            c.canBeManaged(u)
        except:
            can_manage = False

        try:
            c.canEnterContest(u)
        except:
            raise Err(request, 'no priv')

        allSub = Submission.submissionList(c=c).order_by('sid')
        allUser = c.course_class.getAllStudents()
        allProb = c.getContestProblem()

        pInfoDict = {
            pinfo.problem_index: {
                'idx': pinfo.problem_index,
                'ac': 0,
                'pen': 0,
                'sub': 0
            }
            for pinfo in allProb
        }
        info = {
            uinfo.uid: {
                'uid': uinfo.uid,
                'username': uinfo.username,
                'nickname': uinfo.nickname,
                'ac': 0,
                'pen': 0,
                'pinfo': copy.deepcopy(pInfoDict)
            }
            for uinfo in allUser
        }

        if c.board_type == 0:  # acm style board
            for sinfo in allSub:
                if not sinfo.user.uid in info:
                    continue
                uid = sinfo.user.uid
                idx = sinfo.problem_index.problem_index
                if info[uid]['pinfo'][idx]['ac'] > 0:
                    continue
                if sinfo.status in [
                        'Pending', 'Rejudging', 'Compiling', 'System Error'
                ]:
                    continue
                td = sinfo.submission_time - c.start_time
                info[uid]['pinfo'][idx]['sub'] += 1
                if sinfo.status == "Accepted":
                    info[uid]['pinfo'][idx][
                        "ac"] = 1 - info[uid]['pinfo'][idx]["ac"]
                    info[uid]['pinfo'][idx]["ac_time"] = int(
                        math.ceil(td.total_seconds() / 60))
                    info[uid]['pinfo'][idx]["pen"] += int(
                        math.ceil(td.total_seconds() / 60))
                    if (not 'fb_time' in pInfoDict[idx]
                        ) or td < pInfoDict[idx]['fb_time']:
                        pInfoDict[idx]['fb_time'] = td
                        pInfoDict[idx]['fb_uid'] = uid
                else:
                    info[uid]['pinfo'][idx]["ac"] -= 1
                    info[uid]['pinfo'][idx]["pen"] += 20

            for idx, pinfo in pInfoDict.iteritems():
                if 'fb_time' in pinfo:
                    info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True

            info = info.values()
            for i in info:
                i['pinfo'] = i['pinfo'].values()
                i['pinfo'].sort(key=lambda x: x['idx'])
                for pinfo in i['pinfo']:
                    if pinfo['ac'] > 0:
                        i['ac'] += 1
                        i['pen'] += pinfo['pen']
        else:
            for sinfo in allSub:
                if not sinfo.user.uid in info:
                    continue
                uid = sinfo.user.uid
                idx = sinfo.problem_index.problem_index
                other_info = eval(sinfo.other_info)
                tscore = int(other_info['score'])

                if info[uid]['pinfo'][idx]['ac'] >= tscore:
                    continue
                if sinfo.status in [
                        'Pending', 'Rejudging', 'Compiling', 'System Error'
                ]:
                    continue
                td = sinfo.submission_time - c.start_time
                info[uid]['pinfo'][idx]['sub'] += 1
                info[uid]['pinfo'][idx]['ac'] = tscore
                info[uid]['pinfo'][idx]["pen"] += int(
                    math.ceil(td.total_seconds() /
                              60)) - info[uid]['pinfo'][idx].get("ac_time", 0)
                info[uid]['pinfo'][idx]["ac_time"] = int(
                    math.ceil(td.total_seconds() / 60))
                if sinfo.status == "Accepted":
                    if (not 'fb_time' in pInfoDict[idx]
                        ) or td < pInfoDict[idx]['fb_time']:
                        pInfoDict[idx]['fb_time'] = td
                        pInfoDict[idx]['fb_uid'] = uid

            for idx, pinfo in pInfoDict.iteritems():
                if 'fb_time' in pinfo:
                    info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True

            info = info.values()
            for i in info:
                i['pinfo'] = i['pinfo'].values()
                for pinfo in i['pinfo']:
                    if pinfo['ac'] > 0:
                        i['ac'] += pinfo['ac']
                        i['pen'] += pinfo['pen']

        info.sort(key=lambda x: x['ac'] * 262144 - x['pen'], reverse=True)
        for r, i in enumerate(info, 1):
            i['rank'] = r

        if can_manage or c.contest_type == 0:
            rank = info
        else:
            rank = filter(lambda x: u.uid == x['uid'], info)

        return render(request, "newtpl/statistic/board.html", {
            'info': info,
            'rank': rank,
            'allProb': allProb,
            'contest': c
        })
    except Exception as e:
        logger.error(str(e).replace("\n", "\t"))
        return render(request, Err.ERROR_PAGE)
Beispiel #23
0
def showBoardByStatus(request, cId, balloon = False):
    logger.info(str(request).replace("\n","\t"))
    try:
        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, 'not login')
        try:
            cId = int(cId)
            c = Contest.getById(cId)
        except:
            raise Err(request, 'no resource')

        can_manage = True
        try:
            c.canBeManaged(u)
        except:
            can_manage = False

        try:
            c.canEnterContest(u)
        except:
            raise Err(request, 'no priv')

        key = str(cId)
        if not can_manage and not c.contest_type==0:
            key = str(cId) + ","+ str(u.uid)

        res = cache.get(key)
        if res!=None:
            info, allProb, board_body = res

            if can_manage and balloon:
                return render(request,"newtpl/statistic/board2.html", {'info': info, 'board_body': board_body, 'allProb': allProb, 'contest': c})
            else:
                return render(request,"newtpl/statistic/board_test.html", {'info': info, 'board_body': board_body, 'allProb': allProb, 'contest': c})

        board_stop_time = c.start_time + timedelta(minutes = c.board_stop)
        allSub = Submission.submissionList(c=c, board_stop_time = board_stop_time).order_by('sid')
        allUser = c.course_class.getAllStudents()
        allProb = c.getContestProblem()
        
        pInfoDict = {pinfo.problem_index:{'idx':pinfo.problem_index,'ac':0,'pen':0,'sub':0} for pinfo in allProb}
        info = {uinfo.uid:{
            'uid':uinfo.uid,
            'username':uinfo.username,
            'nickname':uinfo.nickname,
            'ac':0,'pen':0,'sub':0,
            'pinfo':copy.deepcopy(pInfoDict)
            } for uinfo in allUser}


        if c.board_type == 0:  # acm style board
            for sinfo in allSub:
                if not sinfo.user.uid in info:
                    continue
                uid = sinfo.user.uid
                idx = sinfo.problem_index.problem_index
                if info[uid]['pinfo'][idx]['ac'] > 0:
                    continue
                if sinfo.status in ['Pending', 'Rejudging', 'Compiling', 'System Error']:
                    continue
                td = sinfo.submission_time-c.start_time
                info[uid]['pinfo'][idx]['sub']+=1
                if sinfo.status == "Accepted":
                    info[uid]['pinfo'][idx]["ac"]=1-info[uid]['pinfo'][idx]["ac"]
                    info[uid]['pinfo'][idx]["ac_time"]=int(math.ceil(td.total_seconds()/60))
                    info[uid]['pinfo'][idx]["pen"]+=int(math.ceil(td.total_seconds()/60))
                    if (not 'fb_time' in pInfoDict[idx]) or td < pInfoDict[idx]['fb_time']:
                        pInfoDict[idx]['fb_time'] = td
                        pInfoDict[idx]['fb_uid'] = uid
                else:
                    info[uid]['pinfo'][idx]["ac"]-=1
                    info[uid]['pinfo'][idx]["pen"]+=20

            for idx, pinfo in pInfoDict.iteritems():
                if 'fb_time' in pinfo:
                    info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True

            info = info.values()
            for i in info:
                i['pinfo'] = i['pinfo'].values()
                i['pinfo'].sort(key=lambda x:x['idx'])
                if u.university_id!=5:
                    i['sub'] = 1
                for pinfo in i['pinfo']:
                    if pinfo['ac'] > 0:
                        i['ac'] += 1
                        i['pen'] += pinfo['pen']
                    i['sub'] += pinfo['sub']
        else:
            for sinfo in allSub:
                if not sinfo.user.uid in info:
                    continue
                uid = sinfo.user.uid
                idx = sinfo.problem_index.problem_index
                other_info = eval(sinfo.other_info)
                tscore = int(other_info['score'])

                if info[uid]['pinfo'][idx]['ac'] >= tscore:
                    continue
                if sinfo.status in ['Pending', 'Rejudging', 'Compiling', 'System Error']:
                    continue
                td = sinfo.submission_time-c.start_time
                info[uid]['pinfo'][idx]['sub']+=1
                info[uid]['pinfo'][idx]['ac']=tscore
                info[uid]['pinfo'][idx]["pen"]+=int(math.ceil(td.total_seconds()/60))-info[uid]['pinfo'][idx].get("ac_time",0)
                info[uid]['pinfo'][idx]["ac_time"]=int(math.ceil(td.total_seconds()/60))
                info[uid]['pinfo'][idx]['idx']=idx
                if sinfo.status == "Accepted":
                    if (not 'fb_time' in pInfoDict[idx]) or td < pInfoDict[idx]['fb_time']:
                        pInfoDict[idx]['fb_time'] = td
                        pInfoDict[idx]['fb_uid'] = uid

            for idx, pinfo in pInfoDict.iteritems():
                if 'fb_time' in pinfo:
                    info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True

            info = info.values()
            for i in info:
                if u.university_id!=5:
                    i['sub'] = 1
                i['pinfo'] = i['pinfo'].values()
                for pinfo in i['pinfo']:
                    if pinfo['ac'] > 0:
                        i['ac'] += pinfo['ac']
                        i['pen'] += pinfo['pen']
                    i['sub'] += pinfo['sub']


        info.sort(key=lambda x:x['ac']*262144*2-x['pen']*2+bool(x['sub']), reverse=True)
        for r, i in enumerate(info, 1):
            i['rank'] = r

        rank = info
        key = str(cId)
        if not can_manage and not c.contest_type==0:
            rank = filter(lambda x:u.uid==x['uid'], info)
            key = str(cId) + ","+ str(u.uid)

        board_body = render_to_response("newtpl/statistic/board_body.html", {'rank': rank}).content

        cache.set(key, (info, allProb, board_body), 10)

        if can_manage and balloon:
            return render(request,"newtpl/statistic/board2.html", {'info': info, 'board_body': board_body, 'allProb': allProb, 'contest': c})
        else:
            return render(request,"newtpl/statistic/board_test.html", {'info': info, 'board_body': board_body,'allProb': allProb, 'contest': c})
    except Exception as e:
        logger.error(str(e).replace("\n","\t"))
        return render(request, Err.ERROR_PAGE)
Beispiel #24
0
def viewCodeAndInfo(request, sid):
    logger.info(str(request).replace("\n\r", "\t"))
    """
    view used to see details of the very submission
    """
    try:
        sid = int(sid)
        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, err='not login')

        try:
            s = Submission.getById(sid)
        except:
            raise Err(
                request,
                err='no submission',
                log_format=('{0}'.format(sid), ''),
                user_format=(u'{0}'.format(sid), u'不要搞笑!!'),
            )

        if not Submission.canViewCode(s, u):
            raise Err(request, err='no priv')

        info = eval(s.other_info)

        if 'ce' in info:
            info['ce'] = info['ce'].replace('/${TOKISAKI_KURUMI}', '')

        info['brush'] = Const.BRUSH[s.code_language]
        info['lang'] = Const.LANG_REFLECT[s.code_language]

        info['judger'] = Const.JUDGER_NAME
        info['user'] = s.user.uid
        info['judge_time'] = str(s.submission_time)
        info['status_cn'] = Const.STATUS_CN[info['status']]
        info['status_color'] = Const.STATUS_COLOR[
            info['status']] if info['status'] in Const.STATUS_COLOR else ''
        # info['submit_ip'] = request.META['REMOTE_ADDR']

        if 'score_sum' not in info:
            case_dict = json.loads(s.problem_index.problem.case_info)
            # score_sum = 0
            # for score in case_dict:
            # score_sum += int( score)
            score_sum = sum(map(int, case_dict.values()))
            info['score_sum'] = score_sum
            s.other_info = str(info)
            s.save()

        if 'case_result' in info:
            score_obtained = 0
            for seq in info['case_result']:
                seq['res_cn'] = JUDGE_RES_CN[seq['res']]
                temp_res = 'status-' + seq['res']
                seq['res_color'] = temp_res
                if 'score' in seq:
                    score_obtained += int(seq['score'])

            info['score_obtained'] = score_obtained

            # seq['res_color'] = Const.STATUS_COLOR[temp_res] if temp_res in Const.STATUS_COLOR else ''

        return render(
            request,
            'newtpl/submission/code_and_info.html',
            {
                'submission':
                s,
                'info':
                info,
                'code_content':
                default_storage.open(s.code_file).read().decode(
                    'utf-8', 'ignore'),
                'tpl': {
                    'sp': True
                },
            },
        )

    except Exception as e:
        logger.error(str(e).replace("\n\r", "\t"))
        return render(
            request,
            Err.ERROR_PAGE,
            {
                'errmsg': unicode(e),
            },
        )
Beispiel #25
0
def submissionList(request, contest_id=None, page_id='1'):
    logger.info(str(request).replace("\n\r", "\t"))
    """
    @view: list submission of some contest
    """

    try:
        page_id = int(page_id)
        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, err='not login')

        cid = int(contest_id)

        try:
            c = Contest.getById(cid)
        except:
            raise Err(
                request,
                err='no contest',
                log_format=('{0}'.format(cid), ''),
                user_format=(u'{0}'.format(cid), u'别做坏事!'),
            )

        c.course_class_name = unicode(c.course_class.getFullName())
        c.description = unicode(c.contest_description)
        c.title = unicode(c.contest_title)
        now = datetime.now()
        if c.start_time + timedelta(minutes=c.length) < now:
            c.status = 'ended'
        elif c.start_time > now:
            c.status = 'scheduled'
        else:
            c.status = 'running'
        c.time_passed = min(
            max(int((now - c.start_time).total_seconds()) / 60, 0), c.length)
        c.time_passed_percent = 100 * c.time_passed / c.length
        c.time_left = c.length - c.time_passed

        isManager = c.course_class.canBeManaged(u)
        user = u if not isManager else None  # privilege for showing all submissions

        idxList = [(cp.problem_index, cp.problem_index)
                   for cp in c.getContestProblem()]
        langList = [('gcc', 'GNU C'), ('g++', 'GNU C++'), ('java', 'java')]
        form = submissionListForm(idxList, langList, request.GET)
        if form.is_valid():
            if form.cleaned_data['problem_index']:
                try:
                    contestProb = ContestProblem.getBy(
                        c, form.cleaned_data['problem_index'])
                except:
                    contestProb = None
                    # raise Exception(u'contest problem not found')
            else:
                contestProb = None
        else:
            raise Err(request,
                      err='example err',
                      log_format=('form invalid', ''),
                      user_format=(u'输入的内容不合法', ''))

        #sub_all_c = getSUB()
        #submissions = bigfilter( u=user, c=c, cp=contestProb, uname=form.cleaned_data['username'], lang=form.cleaned_data['language'], sta=form.cleaned_data['status'])
        submissions = Submission.submissionList(
            u=user,
            c=c,
            cp=contestProb,
            uname=form.cleaned_data['username'],
            lang=form.cleaned_data['language'],
            sta=form.cleaned_data['status'])

        submissions = Submission.submissionList(
            u=user,
            c=c,
            cp=contestProb,
            uname=form.cleaned_data['username'],
            lang=form.cleaned_data['language'],
            sta=form.cleaned_data['status'])
        if isManager and 'rejudge' in request.GET and c.board_type != 2:
            map(lambda x: Submission.rejudgeSubmission(x), submissions)

        paginator = Paginator(submissions, Const.STATUS_PER_PAGE)
        page_id = min(max(int(page_id), 1), paginator.num_pages)

        s = paginator.page(page_id)

        for sub_s in s:
            sub_s.status_color = Const.STATUS_COLOR[
                sub_s.status] if sub_s.status in Const.STATUS_COLOR else ''
            sub_s.status_cn = Const.STATUS_CN[sub_s.status]
        return render(
            request, 'newtpl/submission/status.html', {
                'sList': s,
                'form': form,
                'c': c,
                'tpl': {
                    'can_manage': True if isManager else False
                }
            })
        #return render(request, 'newtpl/submission/status.html', {'sList':s, 'form':form, 'c':c})

    except Exception as e:
        logger.error(str(e).replace("\n\r", "\t"))
        return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
Beispiel #26
0
def addSubmission(request, contest_id=None, problem_index=None):
    logger.info(str(request).replace("\n\r", "\t"))
    """
    view used to add submission
    """
    try:
        contest_id = int(contest_id)

        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, err='not login')

        if not contest_id:
            raise Err(
                request,
                err='request err',
                log_format=('contest id', 'UNDEFINED'),
                user_format=(u'考试编号', u'你吃了么!!!'),
            )

        elif not problem_index:
            raise Err(
                request,
                err='request err',
                log_format=('problem index', 'UNDEFINED'),
                user_format=(u'题目序号', u'哪里去了!!'),
            )
        else:
            try:
                c = Contest.getById(contest_id)
            except:
                raise Err(
                    request,
                    err='no contest',
                    log_format=('{0}'.format(cid), ''),
                    user_format=(u'{0}'.format(cid), u'别做坏事!'),
                )

            try:
                p_index = ContestProblem.getBy(c=c, idx=problem_index)
            except:
                raise Err(
                    request,
                    err='no contest problem',
                    log_format=('{0}'.format(problem_index), ''),
                    user_format=(u'{0}'.format(problem_index), u'别乱写好么!!'),
                )

            p = p_index.problem

            if not Submission.canSubmitCode(u, p_index):
                raise Err(
                    request,
                    err='submit err',
                    log_format=(
                        'no priv to submit',
                        'contest ended or no priv to attend the contest'),
                    user_format=(u'您没有提交该题的权限', u'考试已结束或者您没有参加本场考试的权限'))

        lang_list = []
        if c.lang_limit & 1 == 1:
            lang_list.append(('gcc', 'GNU C'))
        if (c.lang_limit >> 1) & 1 == 1:
            lang_list.append(('g++', 'GNU C++'))
        if (c.lang_limit >> 2) & 1 == 1:
            lang_list.append(('java', 'JAVA'))

        if request.method == 'POST':
            form = addSubmissionForm(lang_list, request.POST)

            if form.is_valid():
                sub_name = str(datetime.now())
                time_str = sub_name.split('.')
                time_str.pop()

                for i in ['-', ':', '.', ' ']:
                    sub_name = sub_name.replace(i, '_')

                import os
                code_file_path = os.path.join(
                    Const.SUBMISSION_TMP_PATH,
                    "{0:010d}_{1}".format(u.uid, sub_name))
                code_length = 0

                # head_details: details of the submission added at the head of the code file
                head_details = ''
                head_details += '/*\n'
                head_details += 'USER_ID: ' + str(u) + '\n'
                head_details += 'PROBLEM: ' + str(p.pid) + '\n'
                head_details += 'SUBMISSION_TIME: ' + time_str[0] + '\n'
                head_details += '*/\n'

                if 'code_file' in request.FILES:
                    default_storage.save(code_file_path,
                                         request.FILES['code_file'])
                else:
                    if form.cleaned_data['code']:
                        default_storage.save(
                            code_file_path,
                            ContentFile(head_details +
                                        form.cleaned_data['code']))
                    else:
                        raise Err(
                            request,
                            err='request err',
                            log_format=('code', 'no input'),
                            user_format=(u'代码呢!', u'不写代码交什么交!!'),
                        )

                code_length = default_storage.size(code_file_path)
                sub_lang = form.cleaned_data['language']

                if sub_lang not in map(lambda x: x[0], lang_list):
                    raise Err(
                        request,
                        err='illegal language',
                        log_format=('{0}'.format(sub_lang), 'blabla'),
                        user_format=(u'{0}'.format(sub_lang), u'别瞎搞成不!!'),
                    )

                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
                if x_forwarded_for:
                    ip = x_forwarded_for.split(',')[0]
                else:
                    ip = request.META.get('REMOTE_ADDR')

                additional = {'submit_ip': ip}
                Submission.addSubmission(u, p_index, code_file_path, sub_lang,
                                         code_length, additional,
                                         c.board_type == 2)

                return redirect('Submission:contest_status',
                                contest_id=contest_id)  # could it be okay?
            else:
                raise Exception(u'form invalid')
            # the usage of url.name in urls.py
        # not POST method
        else:
            form = addSubmissionForm(lang_list)

        return render(
            request,
            'newtpl/submission/submit.html',
            {
                'form': form,
                'tpl': {
                    'sp': True
                },
                'contest': c,
                'cp': p_index
            },
        )  # 'test_info': form.cleaned_data['language']})

    except Exception as e:
        logger.error(str(e).replace("\n\r", "\t"))
        return render(
            request,
            Err.ERROR_PAGE,
            {
                'errmsg': unicode(e),
            },
        )
Beispiel #27
0
def OLDaddSubmission(request, contest_id=None, problem_index=None): # problem_id=None, 
    logger.info(str(request).replace("\n\r","\t"))
    """
    @view: add submission to some contest
    """
    template_tags = { 'show_cid': True, 'show_problem_index': True} # 'is_contest': False, 'show_pid': True, 
    u = None

    try:
        u = User.getSessionUser( request.session)
        if not u:
            return render( request, 'error.html', { 'errmsg': Const.NOT_LOGGED_IN}, )

        if request.method == 'POST':
            form = addSubmissionForm( request.POST)
            if form.is_valid():

                sub_name = str( datetime.now())
                for i in ['-',':','.',' ']:
                    sub_name = sub_name.replace(i,'_')
                code_file_path = "{0}/{1}_{2}".format(Const.SUBMISSION_TMP_PATH, u.uid, sub_name)
                code_length = 0
                if 'code_file' in request.FILES:
                        #return render( request, 'error.html', { 'errmsg': u'请选择要上传的文件!', 'user': u }, )
                    default_storage.save( code_file_path, request.FILES['code_file'])
                   # code_file = request.FILES['code_file']
                   # dest = open( code_file_path, 'wb+')
                   # for chunk in code_file.chunks():
                   #     code_length += len(chunk)
                   #     dest.write(chunk.encode('utf')) # chinese encoding
                        # dest.write(chunk)
                else:
                    if not form.cleaned_data['code']:
                        return render( request, 'error.html', { 'errmsg': u'请填写要提交的代码!', 'user': u }, )
                    default_storage.save( code_file_path, ContentFile( form.cleaned_data['code']))

                code_length = default_storage.size( code_file_path)
                    #dest = open( code_file_path, 'wb+')
                    #code_length = len(request.POST['code'])
                    #for chunk in request.POST['code']:
                    #    dest.write(chunk.encode('utf')) # chinese encoding
                    #dest.close()
                # before we tran the very file object, we should turn it off first!!!!(bugs here! but solved)

                if not contest_id:
                    return render( request, 'error.html', { 'errmsg': u'该选择要提交题目的考试!', 'user': u }, )
                else:
                    c = Contest.getById( contest_id )
                    if not c:
                        return render( request, 'error.html', { 'errmsg': u'编号为{0}的考试不存在!'.format( contest_id), 'user': u }, )

                    p_index = ContestProblem.getByContestAndProblemIndex( contest_id, form.cleaned_data['problem_index'])
                    if not p_index:
                        return render( request, 'error.html', { 'errmsg': u'序号为{0}的题目不存在于考试{1}中!'.format(form.cleaned_data['problem_index'], contest_id), 'user': u }, )
                p = p_index.problem

                if not Submission.canSubmitCode( u, p.pid, contest_id):
                    return render( request, 'error.html', { 'errmsg': u'您没有提交本题的权限!', 'user': u}, )

                Submission.addSubmission( u, p_index, p.data_count, code_file_path, form.cleaned_data['language'], code_length)

                return redirect('Submission:contest_status',contest_id=contest_id) # could it be okay?
            # the usage of url.name in urls.py
        # not POST method
        else:
            form = addSubmissionForm()
            if not contest_id:
                return render( request, 'error.html', { 'errmsg': u'该选择要提交题目的考试!', 'user': u }, )
            else:
                c = Contest.getById( contest_id )
                if not c:
                    return render( request, 'error.html', { 'errmsg': u'编号为{0}的考试不存在!'.format( contest_id), 'user': u }, )

        if problem_index:
            form.fields['problem_index'].initial = problem_index
        else:
            form.fields['problem_index'].initial = ''

        return render( request, 'Submission/Submit.html', { 'form': form, 'show_tags': template_tags, 'user': u, 'contest': c, 'problem_index': problem_index}, )# 'test_info': form.cleaned_data['language']})

    except Exception as e:
        logger.error(str(e).replace("\n\r","\t"))
        return render( request, 'error.html', { 'errmsg': unicode(e), 'user': u}, )
Beispiel #28
0
    def get_board(self, b):
        c = b.contest
        allSubmission = Submission.submissionList(c=c).order_by('sid')
        allUser = c.course_class.getAllStudents()
        allContestProblem = c.getContestProblem()

        problemInfos = {
            cp.problem_index: {
                'idx': cp.problem_index,
                'total_score': cp.getScore(),
                'score': 0,
                'ac': 0
            }
            for cp in allContestProblem
        }
        userInfos = {
            userInfo.uid: {
                'uid': userInfo.uid,
                'username': userInfo.username,
                'nickname': userInfo.nickname,
                'score': 0,
                'problem_infos': copy.deepcopy(problemInfos)
            }
            for userInfo in allUser
        }

        for s in allSubmission:
            uid = s.user.uid
            if not uid in userInfos:
                continue
            idx = s.problem_index.problem_index
            if userInfos[uid]['problem_infos'][idx][
                    'ac'] > 0 or s.status in Const.STATUS_NO_USE:
                continue
            submissionTime = int(
                math.ceil(
                    (s.submission_time - c.start_time).total_seconds() / 60))
            if s.status == 'Accepted':
                userInfos[uid]['problem_infos'][idx][
                    'ac'] = 1 - userInfos[uid]['problem_infos'][idx]['ac']
                userInfos[uid]['problem_infos'][idx][
                    'ac_time'] = submissionTime
                userInfos[uid]['problem_infos'][idx]['score'] = max(
                    problemInfos[idx]['total_score'] -
                    problemInfos[idx]['total_score'] / 250 * submissionTime -
                    50 * (userInfos[uid]['problem_infos'][idx]['ac'] - 1),
                    problemInfos[idx]['total_score'] / 250 * 75)
                userInfos[uid]['score'] += userInfos[uid]['problem_infos'][
                    idx]['score']
            else:
                userInfos[uid]['problem_infos'][idx]['ac'] -= 1
                userInfos[uid]['problem_infos'][idx]['score'] = userInfos[uid][
                    'problem_infos'][idx]['ac']

        problemInfos = sorted(problemInfos.values(),
                              key=lambda problem: problem['idx'])
        userInfos = sorted(userInfos.values(),
                           key=lambda user: user['score'],
                           reverse=True)
        curRank = 0
        for idx, user in enumerate(userInfos):
            if idx == 0 or user['score'] != userInfos[idx - 1]['score']:
                curRank += 1
            user['rank'] = curRank
        return {'problem_infos': problemInfos, 'user_infos': userInfos}
Beispiel #29
0
def showCodeDiff(request, ct_id):
    """
    show codes of the two diffed submission
    """
    try:
        u = User.getSessionUser( request.session)
        if not u:
            raise Err( request, err='not login')

        ct_id = int( ct_id)
        ct = Cheat.objects.select_related('sub1__user', 'sub2__user').get(ctid=ct_id)

        # try:
        #     ct.contest.canBeManaged(u)
        # except:
        #     raise Err(request, err='no priv')

        s_a = ct.sub1
        s_b = ct.sub2
        #sid_a = int( sid_a)
        #sid_b = int( sid_b)

        #try:
        #    s_a = Submission.getById( sid_a)
        #except:
        #    raise Err( request, err='no submission',
        #            log_format=( '{0}'.format( sid_a), ''),
        #            user_format=( u'{0}'.format( sid_a), u'不要搞笑!!'),
        #            )

        #try:
        #    s_b = Submission.getById( sid_b)
        #except:
        #    raise Err( request, err='no submission',
        #            log_format=( '{0}'.format( sid_b), ''),
        #            user_format=( u'{0}'.format( sid_b), u'不要搞笑!!'),
        #            )

        if not Submission.canViewCode( s_a, u):
            raise Err( request, err = 'no priv')

        if not Submission.canViewCode( s_b, u):
            raise Err( request, err = 'no priv')

        info_a = eval( s_a.other_info)
        info_b = eval( s_b.other_info)

        ip_a = info_a['submit_ip']
        ip_b = info_b['submit_ip']

        brush_a = Const.BRUSH[s_a.code_language]
        brush_b = Const.BRUSH[s_b.code_language]

        # brush_a = s_a.code_language
        # brush_b = s_b.code_language

        # info['status_cn'] = Const.STATUS_CN[info['status']]
        #if 'case_result' in info:
        #    for seq in info['case_result']:
        #        seq['res_cn'] = JUDGE_RES_CN[seq['res']]

        return render( request, 'newtpl/cheat/code_diff.html', { 'ct_obj': ct, 'sub_a': s_a, 'sub_b': s_b, 'code_a': default_storage.open(s_a.code_file).read().decode('utf-8', 'ignore'), 'code_b': default_storage.open(s_b.code_file).read().decode('utf-8', 'ignore'), 'tpl': { 'sp': True },  'brush_a': brush_a, 'brush_b': brush_b, 'ip_a': ip_a, 'ip_b': ip_b})

    except Exception as e:
        return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
Beispiel #30
0
def viewCodeAndInfo( request, sid):
    logger.info(str(request).replace("\n\r","\t"))
    """
    view used to see details of the very submission
    """
    try:
        sid = int( sid)
        u = User.getSessionUser( request.session)
        if not u:
            raise Err( request, err='not login')

        try:
            s = Submission.getById( sid)
        except:
            raise Err( request, err='no submission',
                    log_format=( '{0}'.format( sid), ''),
                    user_format=( u'{0}'.format( sid), u'不要搞笑!!'),
                    )

        if not Submission.canViewCode( s, u):
            raise Err( request, err = 'no priv')

        info = eval( s.other_info)
        
        if 'ce' in info:
            info['ce'] = info['ce'].replace('/${TOKISAKI_KURUMI}', '')

        info['brush'] = Const.BRUSH[s.code_language]
        info['lang'] = Const.LANG_REFLECT[s.code_language]

        info['judger'] = Const.JUDGER_NAME
        info['user'] = s.user.uid
        info['judge_time'] = str(s.submission_time)
        info['status_cn'] = Const.STATUS_CN[info['status']]
        info['status_color'] = Const.STATUS_COLOR[info['status']] if info['status'] in Const.STATUS_COLOR else ''
        # info['submit_ip'] = request.META['REMOTE_ADDR']

        if 'score_sum' not in info:
            case_dict = json.loads(s.problem_index.problem.case_info)
            # score_sum = 0
            # for score in case_dict:
                # score_sum += int( score)
            score_sum = sum( map( int, case_dict.values()))
            info['score_sum'] = score_sum
            s.other_info = str( info)
            s.save()

        if 'case_result' in info:
            score_obtained = 0
            for seq in info['case_result']:
                seq['res_cn'] = JUDGE_RES_CN[seq['res']]
                temp_res = 'status-' + seq['res']
                seq['res_color'] = temp_res
                if 'score' in seq:
                    score_obtained += int(seq['score'])

            info['score_obtained'] = score_obtained

                # seq['res_color'] = Const.STATUS_COLOR[temp_res] if temp_res in Const.STATUS_COLOR else ''

        return render( request, 'newtpl/submission/code_and_info.html', { 'submission': s, 'info': info, 'code_content': default_storage.open(s.code_file).read().decode('utf-8','ignore'), 'tpl': { 'sp': True },  }, )

    except Exception as e:
        logger.error(str(e).replace("\n\r","\t"))
        return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
Beispiel #31
0
def submissionList(request, contest_id=None, page_id='1'):
    logger.info(str(request).replace("\n\r","\t"))
    """
    @view: list submission of some contest
    """

    try:
        page_id = int(page_id)
        u = User.getSessionUser(request.session)
        if not u:
            raise Err( request, err='not login')

        cid = int(contest_id)

        try:
            c = Contest.getById(cid)
        except:
            raise Err( request, err='no contest', 
                    log_format=( '{0}'.format(cid), ''), 
                    user_format=( u'{0}'.format( cid), u'别做坏事!'),
                    )

        c.course_class_name = unicode(c.course_class.getFullName())
        c.description = unicode(c.contest_description)
        c.title = unicode(c.contest_title)
        now = datetime.now()
        if c.start_time+timedelta(minutes=c.length) < now:
            c.status = 'ended'
        elif c.start_time > now:
            c.status = 'scheduled'
        else:
            c.status = 'running'
        c.time_passed = min(max(int((now-c.start_time).total_seconds())/60, 0), c.length)
        c.time_passed_percent = 100*c.time_passed/c.length
        c.time_left = c.length-c.time_passed

        isManager = c.course_class.canBeManaged(u)
        user = u if not isManager else None # privilege for showing all submissions

        idxList = [(cp.problem_index, cp.problem_index) for cp in c.getContestProblem()]
        langList = [('gcc','GNU C'), ('g++','GNU C++'), ('java','java')]
        form = submissionListForm(idxList, langList, request.GET)
        if form.is_valid():
            if form.cleaned_data['problem_index']:
                try:
                    contestProb = ContestProblem.getBy( c, form.cleaned_data['problem_index'])
                except:
                    contestProb=None
                    # raise Exception(u'contest problem not found')
            else:
                contestProb=None
        else:
            raise Err( request, err='example err', 
                    log_format=( 'form invalid', ''), 
                    user_format=( u'输入的内容不合法', '')
                    )

        submissions = Submission.submissionList( u=user, c=c, cp=contestProb, uname=form.cleaned_data['username'], lang=form.cleaned_data['language'], sta=form.cleaned_data['status'])

        if isManager and 'rejudge' in request.GET:
            map( lambda x: Submission.rejudgeSubmission( x), submissions)

        paginator = Paginator(submissions, Const.STATUS_PER_PAGE)
        page_id = min(max(int(page_id), 1), paginator.num_pages)

        s = paginator.page(page_id)

        for sub_s in s:
            sub_s.status_color = Const.STATUS_COLOR[sub_s.status] if sub_s.status in Const.STATUS_COLOR else ''
            sub_s.status_cn = Const.STATUS_CN[ sub_s.status]

        return render(request, 'newtpl/submission/status.html', {'sList':s, 'form':form, 'c':c, 'tpl':{'can_manage': True if isManager else False}})

    except Exception as e:
        logger.error(str(e).replace("\n\r","\t"))
        return render(request, Err.ERROR_PAGE, { 'errmsg': unicode(e) } )
Beispiel #32
0
def OLDaddSubmission(request,
                     contest_id=None,
                     problem_index=None):  # problem_id=None,
    logger.info(str(request).replace("\n\r", "\t"))
    """
    @view: add submission to some contest
    """
    template_tags = {
        'show_cid': True,
        'show_problem_index': True
    }  # 'is_contest': False, 'show_pid': True,
    u = None

    try:
        u = User.getSessionUser(request.session)
        if not u:
            return render(
                request,
                'error.html',
                {'errmsg': Const.NOT_LOGGED_IN},
            )

        if request.method == 'POST':
            form = addSubmissionForm(request.POST)
            if form.is_valid():

                sub_name = str(datetime.now())
                for i in ['-', ':', '.', ' ']:
                    sub_name = sub_name.replace(i, '_')
                code_file_path = "{0}/{1}_{2}".format(
                    Const.SUBMISSION_TMP_PATH, u.uid, sub_name)
                code_length = 0
                if 'code_file' in request.FILES:
                    #return render( request, 'error.html', { 'errmsg': u'请选择要上传的文件!', 'user': u }, )
                    default_storage.save(code_file_path,
                                         request.FILES['code_file'])
                # code_file = request.FILES['code_file']
                # dest = open( code_file_path, 'wb+')
                # for chunk in code_file.chunks():
                #     code_length += len(chunk)
                #     dest.write(chunk.encode('utf')) # chinese encoding
                # dest.write(chunk)
                else:
                    if not form.cleaned_data['code']:
                        return render(
                            request,
                            'error.html',
                            {
                                'errmsg': u'请填写要提交的代码!',
                                'user': u
                            },
                        )
                    default_storage.save(
                        code_file_path, ContentFile(form.cleaned_data['code']))

                code_length = default_storage.size(code_file_path)
                #dest = open( code_file_path, 'wb+')
                #code_length = len(request.POST['code'])
                #for chunk in request.POST['code']:
                #    dest.write(chunk.encode('utf')) # chinese encoding
                #dest.close()
                # before we tran the very file object, we should turn it off first!!!!(bugs here! but solved)

                no_judge = False
                if not contest_id:
                    return render(
                        request,
                        'error.html',
                        {
                            'errmsg': u'该选择要提交题目的考试!',
                            'user': u
                        },
                    )
                else:
                    c = Contest.getById(contest_id)
                    if not c:
                        return render(
                            request,
                            'error.html',
                            {
                                'errmsg': u'编号为{0}的考试不存在!'.format(contest_id),
                                'user': u
                            },
                        )

                    p_index = ContestProblem.getByContestAndProblemIndex(
                        contest_id, form.cleaned_data['problem_index'])
                    if not p_index:
                        return render(
                            request,
                            'error.html',
                            {
                                'errmsg':
                                u'序号为{0}的题目不存在于考试{1}中!'.format(
                                    form.cleaned_data['problem_index'],
                                    contest_id),
                                'user':
                                u
                            },
                        )
                    no_judge = c.board_type == 2
                    p = p_index.problem

                if not Submission.canSubmitCode(u, p.pid, contest_id):
                    return render(
                        request,
                        'error.html',
                        {
                            'errmsg': u'您没有提交本题的权限!',
                            'user': u
                        },
                    )

                Submission.addSubmission(u, p_index, p.data_count,
                                         code_file_path,
                                         form.cleaned_data['language'],
                                         code_length, no_judge)

                return redirect('Submission:contest_status',
                                contest_id=contest_id)  # could it be okay?
            # the usage of url.name in urls.py
        # not POST method
        else:
            form = addSubmissionForm()
            if not contest_id:
                return render(
                    request,
                    'error.html',
                    {
                        'errmsg': u'该选择要提交题目的考试!',
                        'user': u
                    },
                )
            else:
                c = Contest.getById(contest_id)
                if not c:
                    return render(
                        request,
                        'error.html',
                        {
                            'errmsg': u'编号为{0}的考试不存在!'.format(contest_id),
                            'user': u
                        },
                    )

        if problem_index:
            form.fields['problem_index'].initial = problem_index
        else:
            form.fields['problem_index'].initial = ''

        return render(
            request,
            'Submission/Submit.html',
            {
                'form': form,
                'show_tags': template_tags,
                'user': u,
                'contest': c,
                'problem_index': problem_index
            },
        )  # 'test_info': form.cleaned_data['language']})

    except Exception as e:
        logger.error(str(e).replace("\n\r", "\t"))
        return render(
            request,
            'error.html',
            {
                'errmsg': unicode(e),
                'user': u
            },
        )
Beispiel #33
0
def showBoardByScore(request, cId):# modified
    logger.info(str(request).replace("\n","\t"))
    try:
        u = User.getSessionUser(request.session)
        if not u:
            raise Err(request, 'not login')
        try:
            cId = int(cId)
            c = Contest.getById(cId)
        except:
            raise Err(request, 'no resource')

        can_manage = True
        try:
            c.canBeManaged(u)
        except:
            can_manage = False

        try:
            c.canEnterContest(u)
        except:
            raise Err(request, 'no priv')

        allSub = Submission.submissionList(c=c).order_by('sid')
        allUser = c.course_class.getAllStudents()
        allProb = c.getContestProblem()

        pInfoDict = {pinfo.problem_index:{'ac':0,'pen':0,'sub':0} for pinfo in allProb}
        info = {uinfo.uid:{
            'uid':uinfo.uid,
            'username':uinfo.username,
            'nickname':uinfo.nickname,
            'ac':0,'pen':0,
            'pinfo':copy.deepcopy(pInfoDict)
            } for uinfo in allUser}

        for sinfo in allSub:
            if not sinfo.user.uid in info:
                continue
            uid = sinfo.user.uid
            idx = sinfo.problem_index.problem_index
            other_info = eval(sinfo.other_info)
            tscore = int(other_info['score'])

            if info[uid]['pinfo'][idx]['ac'] >= tscore:
                continue
            if sinfo.status in ['Pending', 'Rejudging', 'Compiling', 'System Error']:
                continue
            td = sinfo.submission_time-c.start_time
            info[uid]['pinfo'][idx]['sub']+=1
            info[uid]['pinfo'][idx]['ac']=tscore
            info[uid]['pinfo'][idx]["pen"]+=int(math.ceil(td.total_seconds()/60))-info[uid]['pinfo'][idx].get("ac_time",0)
            info[uid]['pinfo'][idx]["ac_time"]=int(math.ceil(td.total_seconds()/60))
            if sinfo.status == "Accepted":
                if (not 'fb_time' in pInfoDict[idx]) or td < pInfoDict[idx]['fb_time']:
                    pInfoDict[idx]['fb_time'] = td
                    pInfoDict[idx]['fb_uid'] = uid

        for idx, pinfo in pInfoDict.iteritems():
            if 'fb_time' in pinfo:
                info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True

        info = info.values()
        for i in info:
            i['pinfo'] = i['pinfo'].values()
            for pinfo in i['pinfo']:
                if pinfo['ac'] > 0:
                    i['ac'] += pinfo['ac']
                    i['pen'] += pinfo['pen']

        info.sort(key=lambda x:x['ac']*262144-x['pen'], reverse=True)
        for r, i in enumerate(info, 1):
            i['rank'] = r

        if can_manage or c.contest_type==0:
            rank = info
        else:
            rank = filter(lambda x:u.uid==x['uid'], info)

        return render(request,"newtpl/statistic/board.html", {'info': info, 'rank': rank,'allProb': allProb, 'contest': c})
    except Exception as e:
        logger.error(str(e).replace("\n","\t"))
        return render(request, Err.ERROR_PAGE)
Beispiel #34
0
def board(request):
    cid = request.GET.get('cid', 1)
    contest = Contest.getById(cid)
    '''
    if contest == False :
        errmsg = u'不存在考试编号为' + str(cid) + u'的考试'
        return render(request, 'error.html', {'errmsg' : errmsg, 'user' : User.getSessionUser(request.session)})
    contestProblem = contest.getContestProblem()
    startTime = contest.start_time
    '''
    submission = Submission.submissionList(cid=cid)

    problemIndex = list()
    problemIndex.append('A')  #
    problemIndex.append('B')  #
    '''
    for i in contestProblem:
        problemIndex.append(i.problem_index)
    '''
    problemIndex.sort()

    data = dict()
    cnt = 0
    now = datetime.now()
    now = now - now
    for i in submission:
        if i.user.username not in data:
            data[i.user.username] = [cnt, i.user.username, 0, now
                                     ]  #id, username, solved, time, A, B, etc
            cnt = cnt + 1
            for j in problemIndex:
                data[i.user.username].append({'ac': 0, 'pd': 0, 'other': 0})

        tmp = data[i.user.username]
        tp = tmp[i.problem_index.problem_index + 3]
        if tp['ac'] == 0:
            if ('Accepted', 'Accepted') in i.status:
                tp['ac'] = 1
                tp['other'] = tp['other'] + 1
                tmp[3] += datetime.timedelta(
                    (tp['pd'] + tp['ac'] + tp['other']) *
                    20) + (i.submission_time - startTime)
                tmp[2] += 1
            elif ('Pending', 'Pending') in i.status:
                tp['pd'] = tp['tp'] + 1
            else:
                tp['other'] = tp['other'] + 1

    out = list()
    for i in data:
        out.append(data[i])

    out.append([
        0, 'zhangzhou', 12, -(datetime.now() - datetime.now()), {
            'ac': 0,
            'pd': 2,
            'other': 0
        }, {
            'ac': 0,
            'pd': 0,
            'other': 0
        }
    ])  #
    out.append([
        -1, 'lyy', 12, -(datetime.now() - datetime.now()), {
            'ac': 1,
            'pd': 2,
            'other': 3
        }, {
            'ac': 0,
            'pd': 0,
            'other': 0
        }
    ])  #
    out.sort(cmp=mycmp)
    cnt = 1
    for i in out:
        i[0] = cnt
        cnt = cnt + 1
        i[3] = (datetime(2000, 1, 1, 0, 0, 0, 0) + i[3]).strftime("%H:%M:%S")

    return render(
        request, 'lyy/board.html', {
            'out': out,
            'problemIndex': problemIndex,
            'user': User.getSessionUser(request.session)
        })