Example #1
0
 def save(self, commit=True):
     title = self.cleaned_data.get("contest_title")
     description = self.cleaned_data.get("description")
     password = self.cleaned_data.get("password")
     private = 1 if password else 0
     start_time = self.cleaned_data.get("start_time")
     end_time = self.cleaned_data.get("end_time")
     problem_data = self.cleaned_data.get("problem_data")
     contest = Contest(
         title=title,
         start_time=start_time,
         end_time=end_time,
         description=description,
         private=private,
         impose=0,
         type=self.judge_type,
         password=password,
         creator=self.user,
     )
     contest.save()
     for i in range(0, problem_data['number']):
         title = problem_data['titles'][i]
         if not title:
             title = self.problem[i].title
         new_problem = In_Problem(
             problem=self.problem[i],
             problem_new_id=i,
             title=title,
         )
         new_problem.save()
         contest.problem.add(new_problem)
     return contest
Example #2
0
def import_tree(path):
    paths = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('.contest'):
                paths.append(os.path.join(root, file))
                contest = Contest(path=os.path.join(root, file))
                contest.save()
                import_to_database(contest)
    return paths
Example #3
0
def import_tree(path):
    paths = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".contest"):
                paths.append(os.path.join(root, file))
                contest = Contest(path=os.path.join(root, file))
                contest.save()
                import_to_database(contest)
    return paths
Example #4
0
def addContest(request):
    if not request.user.is_superuser:
        return printError(
            'You have no permission to this page, please contact administration'
        )
    form = ContestForm()
    errors = []
    courseid = 0
    if request.method == "POST":
        courseid = request.POST['courseid']
        form = ContestForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            courseid = data['courseid']
            course = get_object_or_404(Course, courseid=courseid)
            if not hasPrivilageAddContest(request.user, courseid):
                return HttpResponseRedirect("/")

            contest = Contest(title=data['title'],
                              creater=request.user,
                              start_time=data['start_time'],
                              end_time=data['end_time'],
                              courseid=course)
            contest.save()

            problemList = data['problem_list'].split(',')
            for p in problemList:
                temp = Problem.objects.filter(pid=p)
                if len(temp) == 0:
                    return printError("problem ** %d ** is not exists" %
                                      int(p))
                relation = ContestProblem.objects.filter(
                    cid=contest, pid=Problem.objects.get(pid=int(p)))
                if len(relation) == 0:
                    relation = ContestProblem(
                        cid=contest, pid=Problem.objects.get(pid=int(p)))
                    relation.save()

            return HttpResponseRedirect("/courselist/course/%d" %
                                        int(courseid))

    elif request.method == 'GET':
        try:
            courseid = request.GET['courseid']
        except:
            return printError('You should add contest in course page')

        if not hasPrivilageAddContest(request.user, courseid):
            return HttpResponseRedirect("/")

    course = get_object_or_404(Course, courseid=courseid)
    context = {"form": form, "errors": errors, 'course': course}
    return render_to_response("addcontest.html",
                              context,
                              context_instance=RequestContext(request))
Example #5
0
 def save(self, user):
     if user is None or user.is_authenticated is False:
         return None
     try:
         contest = Contest(title=self.validated_data['title'],
                           user=str(user))
         contest.save()
         contest_problem_list = [
             ContestProblem(remote_id=problem['remote_id'],
                            remote_oj=problem['remote_oj'],
                            contest_id=contest.id)
             for problem in self.validated_data['problems']
         ]
         ContestProblem.objects.bulk_create(contest_problem_list)
         return contest
     except DatabaseError:
         return None
Example #6
0
def edit_or_create_contest_block(request, contest=None):
    is_success = False
    if request.method == 'POST' and 'Insert' not in request.POST:
        form = ContestEditForm(request.POST)
        if form.is_valid():
            if contest is None:
                if not os.path.exists(
                        os.path.dirname(form.cleaned_data["path"])):
                    raise NoDirectoryException("There is no such directory!")
                if os.path.exists(form.cleaned_data["path"]):
                    raise ContestExistsException("This contest already exists")
                contest = Contest()
                contest.path = form.cleaned_data["path"]
                command_create_contest(form.cleaned_data["path"][:-8], [])
            contest.name = form.cleaned_data["name"]
            contest.id_method = form.cleaned_data["id_method"]
            contest.statement_name = form.cleaned_data["statement_name"]
            contest.statement_location = form.cleaned_data[
                "statement_location"]
            contest.statement_date = form.cleaned_data["statement_date"]
            contest.statement_template = form.cleaned_data[
                "statement_template"]
            contest.save()
            export_from_database(contest)
            is_success = True
    else:
        if contest is None:
            form = ContestEditForm()
        else:
            form = ContestEditForm(
                initial={
                    'path': contest.path,
                    'name': contest.name,
                    'id_method': contest.id_method,
                    'statement_name': contest.statement_name,
                    'statement_location': contest.statement_location,
                    'statement_date': contest.statement_date,
                    'statement_template': contest.statement_template,
                })
    return {
        'form': form,
        'is_success': is_success,
    }
Example #7
0
def edit(request, contest_id):
    if request.method == "POST":
        form = forms.ContestForm(request.POST)
        if form.is_valid():
            if contest_id == "0":
                # new contest creation
                contest = Contest(
                    admin=request.user, title=form.cleaned_data["title"], description=form.cleaned_data["description"]
                )
                contest.save()
                contest_id = contest.id
            else:
                contest = get_object_or_404(Contest, pk=contest_id, admin=request.user)
                contest.title = form.cleaned_data["title"]
                contest.description = form.cleaned_data["description"]
                if form.cleaned_data["close"]:
                    if contest.is_submission_open():
                        contest.date_submission_closed = timezone.now()
                    elif contest.is_voting_open():
                        contest.date_voting_closed = timezone.now()
                    else:
                        # TODO: should probably log an error or something
                        pass
                contest.save()
            return redirect("contest", contest.id)
        else:  # form not valid
            if contest_id != "0":  # '0' is for new contest creation
                contest = get_object_or_404(Contest, pk=contest_id, admin=request.user)
            else:
                # creating new contest
                contest = Contest(id=0)

    else:  # GET request
        if contest_id != "0":  # '0' is for new contest creation
            contest = get_object_or_404(Contest, pk=contest_id, admin=request.user)
            # at this point we have the correct contest and the user is its admin
            form = forms.ContestForm(initial={"title": contest.title, "description": contest.description})
        else:
            # creating new contest
            form = forms.ContestForm()
            contest = Contest(id=0)

    return render(request, "contest/edit.html", {"form": form, "contest": contest})
Example #8
0
def add_contest_block(request):
    is_success, is_error = False, False
    if request.method == 'POST':
        form = AddContestForm(request.POST)
        if form.is_valid():
            filename = form.cleaned_data['path']
            if os.path.exists(filename):
                contest = Contest(path=filename)
                contest.save()
                import_to_database(contest)
                is_success = True
            else:
                is_error = True
    else:
        form = AddContestForm()
    return {
        'form': form,
        'is_success': is_success,
        'is_error': is_error,
    }
Example #9
0
def copy_contest_block(request):
    is_success, is_error = False, False
    if request.method == 'POST':
        form = CopyContestForm(request.POST)
        if form.is_valid():
            new_path = norm(form.cleaned_data['new_contest_file'])
            old_path = Contest.objects.get(id=form.cleaned_data['contest']).path
            copyfile(old_path, new_path)
            contest = Contest(path=new_path)
            contest.save()
            import_to_database(path=new_path)
            contest.save()
            is_success = True
    else:
        form = CopyContestForm()
    return {
        'form': form,
        'is_success': is_success,
        'is_error': is_error,
    }
Example #10
0
def add_contest_block(request):
    is_success, is_error = False, False
    if request.method == 'POST':
        form = AddContestForm(request.POST)
        if form.is_valid():
            filename = form.cleaned_data['path']
            if os.path.exists(filename):
                contest = Contest(path=filename)
                contest.save()
                import_to_database(contest)
                is_success = True
            else:
                is_error = True
    else:
        form = AddContestForm()
    return {
        'form': form,
        'is_success': is_success,
        'is_error': is_error,
    }
Example #11
0
def copy_contest_block(request):
    is_success, is_error = False, False
    if request.method == 'POST':
        form = CopyContestForm(request.POST)
        if form.is_valid():
            new_path = norm(form.cleaned_data['new_contest_file'])
            old_path = Contest.objects.get(
                id=form.cleaned_data['contest']).path
            copyfile(old_path, new_path)
            contest = Contest(path=new_path)
            contest.save()
            import_to_database(path=new_path)
            contest.save()
            is_success = True
    else:
        form = CopyContestForm()
    return {
        'form': form,
        'is_success': is_success,
        'is_error': is_error,
    }
Example #12
0
def edit_or_create_contest_block(request, contest=None):
    is_success = False
    if request.method == 'POST' and 'Insert' not in request.POST:
        form = ContestEditForm(request.POST)
        if form.is_valid():
            if contest is None:
                if not os.path.exists(os.path.dirname(form.cleaned_data["path"])):
                    raise NoDirectoryException("There is no such directory!")
                if os.path.exists(form.cleaned_data["path"]):
                    raise ContestExistsException("This contest already exists")
                contest = Contest()
                contest.path = form.cleaned_data["path"]
                command_create_contest(form.cleaned_data["path"][:-8], [])
            contest.name = form.cleaned_data["name"]
            contest.id_method = form.cleaned_data["id_method"]
            contest.statement_name = form.cleaned_data["statement_name"]
            contest.statement_location = form.cleaned_data["statement_location"]
            contest.statement_date = form.cleaned_data["statement_date"]
            contest.statement_template = form.cleaned_data["statement_template"]
            contest.save()
            export_from_database(contest)
            is_success = True
    else:
        if contest is None:
            form = ContestEditForm()
        else:
            form = ContestEditForm(initial={
                'path': contest.path,
                'name': contest.name,
                'id_method': contest.id_method,
                'statement_name': contest.statement_name,
                'statement_location': contest.statement_location,
                'statement_date': contest.statement_date,
                'statement_template': contest.statement_template,
            })
    return {
        'form': form,
        'is_success': is_success,
    }
Example #13
0
    def save(self, user):
        cid = self.cleaned_data.get("cid")
        from datetime import datetime
        from problem.models import Problem
        from contest.models import Contest, In_Problem

        try:
            contest = Contest.objects.get(clone=cid)
            flag = True
        except:
            contest = Contest(
                    title="None",
                    start_time=datetime.now(),
                    end_time=datetime.now(),
                    description="",
                    private=0,
                    impose=0,
                    type=1,
                    password="",
                    creator=user,
            )
            contest.save()
            flag = False
        if not flag:
            for i in range(self.number):
                p = Problem(oj="hdu_std", problem_id=i + 1001, judge_type=1, data_number=cid)
                p.save()
                new_problem = In_Problem(
                        problem=p,
                        problem_new_id=i,
                        title="None",
                )
                new_problem.save()
                contest.problem.add(new_problem)
        c = Connect()
        c.clone_contest(cid, contest.id)
Example #14
0
user = User()
user.username = '******'
user.set_password("123456")
user.email="*****@*****.**"
user.is_staff = True
user.save()


# 插入一个比赛
C = Contest()
C.description = '写脚本真累'
C.participant = 200
C.source = 'zwlin'
C.title = 'Testing_Contest'
C.create_user = User.objects.get(username='******')
C.save()

with open("./item.json", 'r') as f:
    problems = json.load(f)
    id = 1000
    for item in problems:
        p = Problem()
        p.problem_id = str(id)
        p.title = item.get('Title', '')
        p.description = item.get('ProblemDescription', '')
        p.input_description = item.get('Input', '')
        p.output_description = item.get('Output', '')
        p.sample_input = item.get('SampleInput', '')
        p.sample_output = item.get('SampleOutput', '')
        p.hint = item.get('Hint', '')
        p.source = item.get('Author', '')
Example #15
0
class SerializerTest(TestCase):
    def __init__(self, *args, **kwargs):
        TestCase.__init__(self, *args, **kwargs)
        self.user = '******'

    def setUp(self):
        Language.objects.filter(oj_name='unit_test_oj', oj_language='unit_test_language',
                                oj_language_name='unit_test_language_name').delete()
        Problem.objects.filter(remote_oj='unit_test_oj', remote_id='unit_test_pid').delete()
        Contest.objects.filter(title='unit_test_contest_title', user=self.user).delete()

        self.contest = Contest(title='unit_test_contest_title', user=self.user)
        self.contest.save()
        Language.objects.create(oj_name='unit_test_oj', oj_language='unit_test_language',
                                oj_language_name='unit_test_language_name').save()
        Problem.objects.create(remote_oj='unit_test_oj', remote_id='unit_test_pid').save()

    def tearDown(self):
        Language.objects.filter(oj_name='unit_test_oj', oj_language='unit_test_language',
                                oj_language_name='unit_test_language_name').delete()
        Contest.objects.filter(title='unit_test_contest_title', user=self.user).delete()
        Problem.objects.filter(remote_oj='unit_test_oj', remote_id='unit_test_pid').delete()

    def test_submission_1(self):
        request_data = {
            "remote_oj": "unit_test_oj",
            "remote_id": "unit_test_pid",
            "contest_id": self.contest.id,
            "code": "#include <cstdio>"
                    "#include <cstring>"
                    "#include <algorithm>"
                    ""
                    "using namespace std;"
                    "int main(int argc, char **argv){"
                    ""
                    "   std::cout << \"Hello World\" << std::endl;"
                    "}",
            "language": "unit_test_language"
        }

        serializer = SubmissionSerializer(data=request_data)
        self.assertTrue(serializer.is_valid(), serializer.errors)

    def test_submission_2(self):
        request_data = {
            "remote_oj": "unit_test_oj",
            "remote_id": "unit_test_pid",
            # "contest_id": self.contest.id,
            "code": "#include <cstdio>"
                    "#include <cstring>"
                    "#include <algorithm>"
                    ""
                    "using namespace std;"
                    "int main(int argc, char **argv){"
                    ""
                    "   std::cout << \"Hello World\" << std::endl;"
                    "}",
            "language": "unit_test_language"
        }

        serializer = SubmissionSerializer(data=request_data)
        self.assertTrue(serializer.is_valid(), serializer.errors)

    def test_submission_3(self):
        request_data = {
            "remote_oj": "unit_test_oj",
            "remote_id": "unit_test_pid",
            # "contest_id": self.contest.id,
            "code": "",
            "language": "unit_test_language"
        }

        serializer = SubmissionSerializer(data=request_data)
        self.assertFalse(serializer.is_valid(), serializer.errors)

    def test_submission_4(self):
        request_data = {
            "remote_oj": "unit_test_oj",
            "remote_id": "unit_test_pid",
            # "contest_id": self.contest.id,
            "language": "unit_test_language"
        }

        serializer = SubmissionSerializer(data=request_data)
        self.assertFalse(serializer.is_valid(), serializer.errors)