Esempio n. 1
0
def fetchProblem(problemName, overrideLanguage = None):
    problemUrl = getConfigUrl("problemsurl", "problems") + "/" + problemName
    checkProblemExistence(problemName)
    print("­ЪД░  Initializing problem " + problemName)
    os.makedirs(problemName)
    downloadSampleFiles(problemName, problemUrl)
    createBoilerplate(problemName, overrideLanguage)
Esempio n. 2
0
def fetchNewSubmissionStatus(id, session):
    response = session.get(getConfigUrl("submissionsurl", "submissions") +
                           "/" + id,
                           headers=HEADERS)

    body = response.content.decode("utf-8")
    soup = BeautifulSoup(body, "html.parser")
    data = soup.select("#judge_table tbody tr")
    info = data[0]
    testcases = data[1] if len(data) > 1 else None

    status = info.select_one("td.status").text
    runtime = info.select("td.runtime")
    runtime = runtime[0].text if len(runtime) >= 1 else None

    if status == "Compile Error":
        print(_ERROR_MESSAGES["Compile Error"])
        raise Exception(_ERROR_MESSAGES["Compile Error"])

    if not testcases:
        return Response.Success, {"status": status, "runtime": runtime}

    successCount = 0
    testTotal = 0

    for testcase in testcases.select(".testcases > span"):
        testResult = testcase.get("title")
        match = re.search(r"Test case (\d+)\/(\d+): (.+)", testResult)
        if match is None:
            print(
                "⚠️ Error while parsing test cases. Please report this on our github so we can fix it in future versions."
            )
            raise Exception(
                "⚠️ Error while parsing test cases. Please report this on our github so we can fix it in future versions."
            )
        testNumber = match.group(1)
        testTotal = match.group(2)
        testStatus = match.group(3).strip()

        if testStatus == "Accepted":
            successCount += 1
        elif testStatus == "not checked":
            break
        elif testStatus in _ERROR_MESSAGES:
            msg = (_ERROR_MESSAGES[testStatus].replace(
                "@test", testNumber).replace("@total", testTotal))
            print("\U0000274C\n" + msg)
            return Response.Failure
        else:
            print(
                "⚠️\n😕 Unknown error  '" + testStatus +
                "' for test case. Please report this on our github so we can fix it in future versions"
            )
            raise Exception("Unknown Error")

    return Response.Success, {
        "testCount": successCount,
        "testTotal": int(testTotal),
        "runtime": runtime
    }
Esempio n. 3
0
def collectProblems(data):
    session = requests.Session()
    url = getConfigUrl("problemsurl", "problems")
    parameters = buildParameters(data)
    login(session)
    problems = fetchProblems(url, parameters, data, session)
    return problems
Esempio n. 4
0
def read(problemName, data):
    session = requests.Session()
    problemUrl = getConfigUrl("problemsurl", "problems") + "/" + problemName

    checkProblemExistence(problemName)

    if "console" in data and data['console']:
        problemText = fetchProblemText(problemUrl, session)

        for line in problemText:
            print(line)
    else:
        webCommand(problemName)
Esempio n. 5
0
def login(session):
    config = getConfig()
    username = config.get("user", "username")
    token = config.get("user", "token")
    login_url = getConfigUrl("loginurl", "login")

    session.post(
        login_url,
        data={
            "user": username,
            "token": token,
            "script": "true"
        },
        headers=_HEADERS,
    )
Esempio n. 6
0
def postSubmission(session, problemName, programFile):
    login(session)

    url = getConfigUrl("submissionurl", "submit")
    language = guessLanguage(programFile)

    if language == -1:
        print("Could not guess language for " + programFile)
        raise Exception("Could not guess language for " + programFile)

    language = formatLanguage(language)
    data = {
        "submit": "true",
        "submit_ctr": 2,
        "language": language,
        "problem": problemName,
        "script": "true",
    }

    if requiresClass(programFile):
        data["mainclass"] = detectClassName(programFile)

    sub_files = []
    undoBOM(programFile["relativePath"])
    with open(programFile["relativePath"]) as sub_file:
        sub_files.append((
            "sub_file[]",
            (programFile["name"], sub_file.read(), "application/octet-stream"),
        ))

    response = session.post(url, data=data, files=sub_files, headers=HEADERS)

    body = response.content.decode("utf-8").replace("<br />", "\n")
    match = re.search(r"Submission ID: ([0-9]+)", body)

    if match is None:
        print(
            "Submission was received, but could not read ID from response.",
            "Visit the submission manually in the browser.",
        )
        print("Response was: " + body)
        return -1

    return match.group(1).strip()
Esempio n. 7
0
def submitCommand(data):
    problemName = data["problem"]

    if not os.path.exists(problemName):
        promptToFetch(problemName)
        return Response.Error

    # if programFile is not given, we will attempt to guess it
    programFile = (formatProgramFile(data.get("file"))
                   if data.get("file") else selectProgramFile(problemName))

    if programFile == -1:
        raise Exception("Could not guess programFile")

    if "force" not in data or not data.get('force'):
        response = confirm(problemName, programFile)
        if not response: return Response.Aborted

    session = requests.Session()

    print("📨 Submitting " + problemName + "...")

    id = postSubmission(session, problemName, programFile)

    print("📬 Submission Successful (url " +
          getConfigUrl("submissionsurl", "submissions") + "/" + id + ")")

    if id == -1:
        return False

    response = Response.Failure
    try:
        response = printUntilDone(id, problemName, session)
    except:
        pass
    if data.get('sound'):
        if response == Response.Success:
            winsound()
        elif response == Response.Failure:
            losesound()
    if response == Response.Success:
        if data.get('archive'):
            archive(problemName, ".solved/")
    return response
Esempio n. 8
0
def openSubmission(submissionId):
    url = getConfigUrl("submissionsurl", "submissions") + "/" + submissionId
    webbrowser.open(url)
Esempio n. 9
0
def webCommand(problemName):
    url = getConfigUrl("problemsurl", "problems") + "/" + problemName
    webbrowser.open(url)
Esempio n. 10
0
def checkProblemExistence(problemName):
    problemUrl = getConfigUrl("problemsurl", "problems") + "/" + problemName
    existenceTest = requests.get(problemUrl)
    if existenceTest.status_code != 200:
        raise InvalidProblemException("Рџа№ИЈ Problem '" + problemName + "' does not exist!")
Esempio n. 11
0
def definedContest(contest_id):
    if re.search('https://.+/(contests|sessions)/\w+', contest_id):
        return contest_id
    id = contest_id.split('/')[-1]
    contestsUrl = getConfigUrl("contestsurl", "contests")
    return f'{contestsUrl}/{id}'