Esempio n. 1
0
def Tournament(form: TournamentForm) -> list:
    if form.validate_on_submit():
        probId = form.probId.data
        startTimeStr = form.start.data
        id = None
        try:
            id = int(probId)
            if storage.getProblem(id) == None:
                raise ValueError()
        except ValueError:
            return [0, ("No problem with this id!", "message red")]
        if (startTimeStr == ''):
            useCasesAPI.makeTournament(id)
            return [1, ("Tournament Successfully created.", "message green")]
        else:
            try:
                startTime = int(startTimeStr)
            except ValueError:
                return [0, ("Incorrect time", "message red")]
            if (startTime < unixTime()):
                return [0, ("Too early", "message red")]
            if (startTime > MaxStartTime):
                return [0, ("Too late", "message red")]
            useCasesAPI.createDelayedTournament(id, startTime)
            return [
                1, ("Looking forward for tournament start", "message green")
            ]
    return [0, ("Enter id of problem", "message blue")]
Esempio n. 2
0
def changeMainSubmission(userId, subId):
    newMainSubmission = storage.getSubmission(subId)
    if ((newMainSubmission is None) or newMainSubmission.userId != userId):
        return 0
    user = storage.getUser(userId)
    probId = newMainSubmission.probId
    problem = storage.getProblem(probId)
    if newMainSubmission.type == StrategyState.Main:
        newMainSubmission.type = StrategyState.NonMain
        problem.submissions.remove(subId)
        returnCode = 1
    else:
        for anotherSubmissionId in user.submissions[probId]:
            anotherSubmission = storage.getSubmission(anotherSubmissionId)
            if (anotherSubmission.type == StrategyState.Main):
                anotherSubmission.type = StrategyState.NonMain
                storage.saveSubmission(anotherSubmission)
                problem.submissions.remove(anotherSubmissionId)
        newMainSubmission.type = StrategyState.Main
        problem.submissions.add(subId)
        returnCode = 2

    storage.saveSubmission(newMainSubmission)
    storage.saveProblem(problem)
    return returnCode
Esempio n. 3
0
def update():
    time = unixTime()
    problemCnt = storage.getProblemsCount()
    for i in range(problemCnt):
        tourTime = storage.getCertainField('problems', i, 'nextTournament')
        if (tourTime != -1 and tourTime <= time):
            useCasesAPI.makeTournament(i)
            prob = storage.getProblem(i)
            prob.nextTournament = -1
            storage.saveProblem(prob)
Esempio n. 4
0
def addSubmission(userId, problemId, code):
    user = storage.getUser(userId)
    problem = storage.getProblem(problemId)
    newSubmission = Submission(-1, userId, problemId, code,
                               StrategyState.NonMain)
    idOfNewSubmission = storage.saveSubmission(newSubmission)
    if (problemId not in user.submissions):
        user.submissions[problemId] = []
    user.submissions[problemId].append(idOfNewSubmission)
    problem.allSubmissions.append(idOfNewSubmission)
    storage.saveUser(user)
    storage.saveProblem(problem)
    return idOfNewSubmission
Esempio n. 5
0
def testStrategies(id1, id2, saveLogs=False):
    sub1 = storage.getSubmission(id1)
    sub2 = storage.getSubmission(id2)

    if (sub1.probId != sub2.probId):
        raise Exception(
            'Trying to judge two strategies for different problems')

    problemId = sub1.probId
    problem = storage.getProblem(problemId)
    loadProblem(problem)

    loadSubmission(sub1, problem)
    loadSubmission(sub2, problem)

    invocationResult = judge.run(
        getGameModule(problem),
        [getStrategyModule(sub1),
         getStrategyModule(sub2)],
        saveLogs=saveLogs)
    return invocationResult
Esempio n. 6
0
def problemsetId(strId: str) -> list:
    try:
        probId = int(strId)
    except ValueError:
        return [0, [], None, None, None]
    problem = storage.getProblem(probId)
    if (problem is None):
        return [0, [], None, None, None]

    userId = info()['id']
    if userId == -1:
        subList = []
    else:
        subList = useCasesAPI.getSubmissionsUP(userId, probId)

    tester.loadProblemDownloads(problem)

    paths = [convertPathForApp(path[0]) for path in problem.rules.downloads]
    #paths - список путей до файлов, которые пользователь может скачать
    #print(paths)

    return [1, paths, problem, subList, useCasesAPI.getProbTournaments(probId)]
Esempio n. 7
0
def tournament(problemId):
    problem = storage.getProblem(problemId)
    problem.type = ProblemState.Testing
    storage.saveProblem(problem)
    loadProblem(problem)

    subCnt = len(problem.submissions)
    subs = [storage.getSubmission(subId) for subId in problem.submissions]
    scores = [[0, subs[i].id] for i in range(subCnt)]

    for i in range(subCnt):
        loadSubmission(subs[i], problem)

    problemPath = os.path.join('problems', str(problemId))

    for i in range(subCnt):
        for j in range(subCnt):
            if (i != j):
                print("judging ", i, j)
                invocationResult = judge.run(
                    getGameModule(problem),
                    getClassesModule(problem),
                    [getStrategyModule(subs[i]),
                     getStrategyModule(subs[j])],
                    saveLogs=False)
                print(invocationResult.results[0].goodStr())
                print(invocationResult.results[1].goodStr())
                scores[i][0] += invocationResult.results[0].score
                scores[j][0] += invocationResult.results[1].score

    scores.sort(reverse=True)
    newTournament = Tournament(-1, problemId, problem.revisionId, unixTime(),
                               scores)
    newTournamentId = storage.saveTournament(newTournament)
    problem.tournaments.append(newTournamentId)
    storage.saveProblem(problem)
    return newTournamentId
Esempio n. 8
0
def createDelayedTournament(probId, time):
    prob = storage.getProblem(probId)
    prob.nextTournament = time
    storage.saveProblem(prob)
Esempio n. 9
0
def parseArchive(archivePath, probId=-1):
    if (not os.path.isfile(archivePath)):
        return {'ok': 0, 'error': 'No such archive (internal error)'}
    if (os.path.isdir(SaveFolder)):
        shutil.rmtree(SaveFolder)
    try:
        zip = ZipFile(archivePath)
    except BadZipFile:
        return {'ok': 0, 'error': 'Bad zip file'}
    zip.extractall(path=SaveFolder)
    problemPath = SaveFolder

    while (True):
        typeDict = getFolderType(problemPath)
        if (typeDict['type'] == FolderType.Correct):
            break
        elif (typeDict['type'] == FolderType.Bad):
            return {'ok': 0, 'error': "Archive isn't correct"}
        else:
            problemPath = os.path.join(problemPath, typeDict['go'])

    statement = readFile(os.path.join(problemPath, 'statement'))
    rawConfig = readFile(os.path.join(problemPath, 'config.json'))
    config = json.loads(rawConfig)

    if ('name' not in config):
        return {'ok': 0, 'error': 'No name parameter in config'}

    if (probId == -1):
        probId = storage.getProblemsCount()
        problem = Problem(probId, Rules("", [], [], ""), {}, [], [], -1, 0)
    else:
        problem = storage.getProblem(probId)
        problem.revisionId += 1

    name = config['name']

    try:
        downloads = readFiles(
            os.path.join(problemPath, 'downloads'),
            os.path.join('app', 'downloads', problemFolder(probId)))
        sources1 = readFiles(os.path.join(problemPath, 'sources'),
                             os.path.join('problems', problemFolder(probId)))
        sources2 = readFiles(
            os.path.join(problemPath, 'templates'),
            os.path.join('app', 'templates', 'problems',
                         problemFolder(probId)))
    except SourceSizeException:
        return {'ok': 0, 'error': 'Source file is too large'}
    except UnicodeDecodeError:
        return {'ok': 0, 'error': "Can't decode files"}

    copyFiles(os.path.join(problemPath, 'static'),
              os.path.join('app', 'static', 'problems', problemFolder(probId)))

    sources = sources1 + sources2

    if (name == "" or (name != problem.rules.name
                       and storage.getProblemByName(name) != None)):
        return {"ok": 0, "error": "You can't add problem with same name"}

    newRules = Rules(name, sources, downloads, statement)
    problem.rules = newRules

    storage.saveProblem(problem)
    return {'ok': 1}
Esempio n. 10
0
        break

    params = line.split()
    command = params[0]

    if (command == 'look'):
        if (len(params) < 3 or (not isInt(params[2]))):
            continue

        if (params[1][0] == 'u'):
            id = int(params[2])
            resp = storage.getUser(id)

        if (params[1][0] == 'p'):
            id = int(params[2])
            resp = storage.getProblem(id)

        if (params[1][0] == 's'):
            id = int(params[2])
            resp = storage.getSubmission(id)

        if (params[1][0] == 't'):
            id = int(params[2])
            resp = storage.getTournament(id)

        if (resp is not None):
            resp.print()

    if (command == 'add'):
        if (len(params) < 2):
            continue