示例#1
0
def problem_submit(problem_id, filename):
    with open(PROBLEM_MAPPING_PATH, "rt") as json_in:
        problem_to_config = json.load(json_in)
        if problem_id not in problem_to_config:
            print(
                cyan_wrapper("Invalid problem id!") +
                " Please confirm your input.")
            return
    try:
        with open(filename, "r") as fin:
            code = fin.read()
    except IOError:
        print('File "' + filename + '" does not exist!')
        return
    endpoint = "submission"
    code_type = ""
    if (filename.split(".")[-1] == "cpp"):
        code_type = "C++"
    elif (filename.split(".")[-1] == "c"):
        code_type = "C"
    elif (filename.split(".")[-1] == "go"):
        code_type = "Golang"
    elif (filename.split(".")[-1] == "java"):
        code_type = "Java"
    elif (filename.split(".")[-1] == "py"):
        type_ = input("Choose Python version (2/3): ")
        if (type_ == 2):
            code_type = "Python2"
        elif (type_ == 3):
            code_type = "Python3"
    else:
        print("Wrong file format.")
        return

    payload = {
        "problem_id": problem_to_config[problem_id]["_id"],
        "language": code_type,
        "code": code,
    }
    try:
        submission_response = json.loads(
            curl("POST",
                 payload=payload,
                 endpoint=endpoint,
                 use_x_csrf_token=True))
    except ValueError:
        print("No response is received! Please contact class TA!")
    if submission_response["error"] != None:
        print(submission_response["data"])
        return
    submission_id = submission_response["data"]["submission_id"]
    print(green_wrapper("Submit successfully!!"))
    print("Getting submission status...".format(submission_id))
    time.sleep(1.0)
    status(submission_id)
示例#2
0
文件: login.py 项目: josix/oj-cli
def login():
    username = raw_input("Username: "******"Password: "******"username": username,
        "password": passwd,
        "csrfmiddlewaretoken": get_csrf_token(),
    }
    result = curl("post", payload=payload, endpoint="login/", use_x_csrf_token=True)
    result = json.loads(result)
    print("%s!!" % result["data"])
    os.chmod(COOKIES_PATH, 0700)
    print("Cookies " + green_wrapper(COOKIES_PATH) + " was protected automatically. (700)")
示例#3
0
def update_contest_map():
	if not os.path.isdir(STATEMENT_PATH):
		os.mkdir(STATEMENT_PATH)
	os.chmod(STATEMENT_PATH, 0700)
	print("Target Contest: " + cyan_wrapper(CONTEST_NAME))
	endpoint = "contests?offset=0&limit=10&status=0"
	inputstr = '{'
	result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
	counter = 1
	result2 = ""
	for i in range(0,len(result['data']['results'])):
		if(result['data']['results'][i]['title'] != CONTEST_NAME):
			continue
		contestid = result['data']['results'][i]['id']
		payload = {
				"contest_id" : str(contestid)
				}
		endpoint = "contest/problem?contest_id=" + str(contestid)
		result2 = json.loads(curl("get", payload=payload, endpoint=endpoint, use_x_csrf_token=True))
		if result2["error"] == "error":
			print("Error : " + result2["data"])
			continue
		for problems in range(0,len(result2['data'])):
			c_id = result2['data'][problems]['_id']
			name = result2['data'][problems]['title']
			r_id =  result2['data'][problems]['id']
			try:
				print("Found HomeWork: " + cyan_wrapper(str(c_id) + " [" + name + "]"))
			except:
				print("Found HomeWork: " + cyan_wrapper(str(c_id) + " [" + str(c_id) + "]"))
			if counter != 1:
				inputstr += ','
			try:
				inputstr += '"' + str(c_id) + '":{"contest_name":"' + str(name) + '","contest_id":' + str(contestid) + ',"contest_problem_id":"' + str(c_id)+ '","problem_id":' + str(r_id) + '}'
			except:
				inputstr += '"' + str(c_id) + '":{"contest_name":"' + str(c_id) + '","contest_id":' + str(contestid) + ',"contest_problem_id":"' + str(c_id)+ '","problem_id":' + str(r_id) + '}'
			counter += 1
	inputstr += '}'
	if not os.path.isdir(STATEMENT_PATH):
		os.mkdir(STATEMENT_PATH)
	f = open(ASSIGNMENT_MAPPING_PATH,'w')
	f.write(inputstr.encode("utf-8"))
	f.close
	if result2["error"] == "error":
		print(red_wrapper("Fail updating assign!"))
	else:
		print(green_wrapper("Updated assign successfully!"))
示例#4
0
文件: status.py 项目: josix/oj-cli
def status(submission_id):
    endpoint = "submission?id={}".format(submission_id)
    result = json.loads(curl("GET", endpoint=endpoint, use_x_csrf_token=True))
    response_data = result["data"]
    if response_data == "Submission doesn't exist":
        print("Submission doesn't exist")
        return
    print("Your code has been graded! Here's your results:\n")
    status_to_response = {
        -1:
        lambda idx: red_wrapper("Testcase {}: WA(Wrong Answer)".format(idx)
                                ),  # WA
        -2:
        lambda idx: cyan_wrapper("Testcase {}: CE(Compilation Error)".format(
            idx)),  # CE
        0:
        lambda idx: green_wrapper("Testcase {}: AC(Accept)".format(idx)),  # AC
        2:
        lambda idx: "Testcase {}: TLE(Time Limit Exceeded)".format(idx),  # TLE
        3:
        lambda idx: "Testcase {}: MLE(Memory Limit Exceeded)".format(idx
                                                                     ),  # MLE
        4:
        lambda idx: purple_wrapper("Testcase {}: RE(Runtime Error)".format(idx)
                                   ),  # RE
    }
    if "data" not in response_data["info"]:
        print(cyan_wrapper("CE(Compilation Error) before running testing"))
        return
    for idx, ans in enumerate(response_data["info"]["data"]):
        test_case_no = idx + 1
        answers_status = ans["result"]
        if answers_status not in status_to_response:
            print("Testcase {}: SE(System Error)".format(test_case_no))
            continue
        print(status_to_response[answers_status](test_case_no))
    print("For graphical results,\nplease visit: " + HOST + "status/" +
          submission_id)
示例#5
0
def update_problem_map():
    if not os.path.isdir(STATEMENT_PATH):
        os.mkdir(STATEMENT_PATH)
    os.chmod(STATEMENT_PATH, 0700)
    endpoint = "problem?offset=0&limit=200"
    inputstr = '{'
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    counter_1 = 1
    for i in range(0, len(result['data']['results'])):
        real_id = result['data']['results'][i]['id']
        display_id = result['data']['results'][i]['_id'].replace(" ", "")
        if counter_1 != 1:
            inputstr += ','
        inputstr += '"' + str(display_id) + '":{"_id":"' + str(
            real_id
        ) + '","query_id":"' + result['data']['results'][i]['_id'].replace(
            " ", "+") + '"}'
        counter_1 += 1
    inputstr += '}'
    f = open(PROBLEM_MAPPING_PATH, 'w')
    f.write(inputstr.encode("utf-8"))
    f.close
    print(green_wrapper("Updated problems successfully!"))
示例#6
0
def status(submission_id):
    endpoint = "submission?id={}".format(submission_id)
    result = json.loads(curl("GET", endpoint=endpoint, use_x_csrf_token=True))
    this_result = result["data"]["result"]
    error_counter = 0
    while (str(this_result) == "7" and error_counter < 10):
        time.sleep(1.0)
        result = json.loads(
            curl("GET", endpoint=endpoint, use_x_csrf_token=True))
        this_result = result["data"]["result"]
        error_counter += 1
    response_data = result["data"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(TimeLimitExceeded)"),  # TLE
        3: purple_wrapper("MLE(MemoryLimitExceeded)"),  # MLE
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    if "info" in response_data:
        if response_data == "Submission doesn't exist":
            print("Submission doesn't exist")
            return
        print("========================================================")
        try:
            print("Result: {:40}  Score:{:4}".format(
                status_to_response[this_result],
                response_data["statistic_info"]["score"]))
            if "data" not in response_data["info"]:
                print(gray_wrapper(
                    response_data["statistic_info"]["err_info"]))
                print(
                    "========================================================")
                return
            print("|ID |Status                       |   Time|  Mem| Score|")
            for ans in result["data"]["info"]["data"]:
                print("|#{:2}|{:40}|{:5}ms|{:3}MB| {:5}|".format(
                    ans["test_case"], status_to_response[ans["result"]],
                    ans["real_time"], (ans["memory"] / 1048576) + 1,
                    ans["score"]))
            print("========================================================")
        except:
            print(result)
            print(
                "Bad response! Please check your internet connection and ask TAs!"
            )
    else:
        if response_data == "Submission doesn't exist":
            print("Submission doesn't exist")
            return
        print("==============================================")
        try:
            print("Result: {:40}".format(status_to_response[this_result]))
            if "err_info" in response_data["statistic_info"]:
                print(gray_wrapper(
                    response_data["statistic_info"]["err_info"]))
                print("==============================================")
                return
            print("|Status                       |   Time|  Mem|")
            print("|{:40}|{:5}ms|{:3}MB|".format(
                status_to_response[this_result],
                response_data["statistic_info"]["time_cost"],
                (response_data["statistic_info"]["memory_cost"] / 1048576) +
                1))
            print("==============================================")
        except:
            print(result)
            print(
                "Bad response! Please check your internet connection and ask TAs!"
            )
示例#7
0
def my_contests_status(assign_name):
    with open(ASSIGNMENT_MAPPING_PATH, "rt") as json_in:
        assign_to_config = json.load(json_in)
    try:
        with open(MY_STATUS_PATH, "rt") as json_in:
            status_config = json.load(json_in)
            if assign_name in status_config:
                status(status_config[assign_name]["id"])
                return
    except:
        pass
    if assign_name not in assign_to_config:
        print("Invalid Assign Number!")
        print("Available names are:")
        for hwmap in assign_to_config:
            print("- " +
                  cyan_wrapper(hwmap + " [" +
                               assign_to_config[hwmap]['contest_name'] + "]"))
        print(
            "If you want to update latest homework assignment, type: [oj update] to update."
        )
        return
    contest_id, problem_id = (
        assign_to_config[assign_name]["contest_id"],
        assign_to_config[assign_name]["contest_problem_id"],
    )
    endpoint = "contest_submissions?myself=1&contest_id={}&limit=20&problem_id={}".format(
        contest_id, assign_name)
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result["error"] == "error":
        print("Error : " + result["data"])
        return
    result = result["data"]["results"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        2: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        3: purple_wrapper("MLE(Memory Limit Exceeded)"),  # ML 
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    print(
        "============================================================================"
    )
    print('|  Problem Name: {:58}|'.format(
        assign_to_config[assign_name]["contest_problem_id"] + " [" +
        assign_to_config[assign_name]["contest_name"] + "]"))
    print(
        "============================================================================"
    )
    print('|{:12}|{:27}|   {:4}|  {:3}|               When|'.format(
        "ID  ", "Status", "Time", "Mem"))
    inputstr = '{'
    idx = 0
    for i in result:
        if i["problem"] != assign_to_config[assign_name]["contest_problem_id"]:
            continue
        timestr = i["create_time"].split("T")[0]
        timestr += " " + i["create_time"].split("T")[1].split(".")[0]
        mydatetmp = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
        hours_added = timedelta(hours=8)
        timestr = mydatetmp + hours_added
        timestr.strftime("%m/%d/%Y, %H:%M:%S")
        if i["result"] != -2:
            print('|ID{:10}|{:38}|{:5}ms|{:3}MB|{}|'.format(
                idx, status_to_response[i["result"]],
                i["statistic_info"]["time_cost"],
                (i["statistic_info"]["memory_cost"] / 1048576) + 1, timestr))
        else:
            print('|ID{:10}|{:38}|{:5}--|{:3}--|{}|'.format(
                idx, status_to_response[i["result"]], "-----", "---", timestr))
        if idx != 0:
            inputstr += ','
        inputstr += '"ID' + str(idx) + '":{"id":"' + i["id"] + '"}'
        idx += 1
    print(
        "============================================================================"
    )
    inputstr += '}'
    if not os.path.isdir(STATEMENT_PATH):
        os.mkdir(STATEMENT_PATH)
    f1 = open(MY_STATUS_PATH, 'w')
    f1.write(inputstr.encode('utf-8'))
    f1.close
示例#8
0
def contests_result(assign_name):
    with open(ASSIGNMENT_MAPPING_PATH, "rt") as json_in:
        assign_to_config = json.load(json_in)
    if assign_name not in assign_to_config:
        print("Invalid Assign Number!")
        print("Available names are:")
        for hwmap in assign_to_config:
            print("- " +
                  cyan_wrapper(hwmap + " [" +
                               assign_to_config[hwmap]['contest_name'] + "]"))
        print(
            "If you want to update latest homework assignment, type: [oj update] to update."
        )
        return
    contest_id, problem_id = (
        assign_to_config[assign_name]["contest_id"],
        assign_to_config[assign_name]["contest_problem_id"],
    )
    endpoint = "contest_rank?myself=0&contest_id={}&limit=100".format(
        contest_id)
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result["error"] == "error":
        print("Error : " + result["data"])
        return
    endpoint = "contest/problem?contest_id={}&problem_id={}".format(
        contest_id, assign_name)
    result2 = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result2["error"] == "error":
        print("Error : " + result2["data"])
        return
    result = result["data"]["results"]
    result2 = result2["data"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        2: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        3: purple_wrapper("MLE(Memory Limit Exceeded)"),  # ML 
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    if result2["my_status"] == None:
        print("Your status of " +
              assign_to_config[assign_name]["contest_problem_id"] +
              " : No record")
    else:
        print("Your status of " +
              assign_to_config[assign_name]['contest_problem_id'] + " : " +
              status_to_response[result2["my_status"]])
    print("================================================")
    blockstatus = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for usr in result:
        try:
            problem_index = str(assign_to_config[assign_name]["problem_id"])
            blocks = usr["submission_info"][problem_index] / 10
            blocks -= 1
            if blocks <= 0:
                blocks = 0
            blockstatus[blocks] += 1
        except:
            continue
    ic = 0
    for i in blockstatus:
        stastr = ''
        if ic == 0:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[0],
                    result2["statistic_info"]["0"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[0], 0))
        elif ic == 10:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[4],
                    result2["statistic_info"]["4"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[4], 0))
        elif ic == 20:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[8],
                    result2["statistic_info"]["8"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[8], 0))
        elif ic == 30:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-1],
                    result2["statistic_info"]["-1"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-1], 0))
        elif ic == 40:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-2],
                    result2["statistic_info"]["-2"]))
            except:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[-2], 0))
        elif ic == 50:
            try:
                print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                    ic + 1, ic + 10, i, status_to_response[1],
                    result2["statistic_info"]["1"] +
                    result2["statistic_info"]["2"]))
            except:
                try:
                    print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                        ic + 1, ic + 10, i, status_to_response[1],
                        result2["statistic_info"]["2"]))
                except:
                    try:
                        print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                            ic + 1, ic + 10, i, status_to_response[1],
                            result2["statistic_info"]["1"]))
                    except:
                        print(' {:3}~{:3} :{:3}  |  {:35} : {}'.format(
                            ic + 1, ic + 10, i, status_to_response[1], 0))
        elif ic == 60:
            print(' {:3}~{:3} :{:3}  |--------------------------------'.format(
                ic + 1, ic + 10, i))
        elif ic == 70:
            print(' {:3}~{:3} :{:3}  |  {:24} : {}'.format(
                ic + 1, ic + 10, i, "Total submissions",
                result2["submission_number"]))
        else:
            print(' {:3}~{:3} :{:3}  |'.format(ic + 1, ic + 10, i))
        ic += 10
    print(
        "================================================\nFor real time score ranking, please go to the website."
    )
示例#9
0
def contests_status(assign_name):
    with open(ASSIGNMENT_MAPPING_PATH, "rt") as json_in:
        assign_to_config = json.load(json_in)
    if assign_name not in assign_to_config:
        print("Invalid Assign Number!")
        print("Available names are:")
        for hwmap in assign_to_config:
            print("- " +
                  cyan_wrapper(hwmap + " [" +
                               assign_to_config[hwmap]['contest_name'] + "]"))
        print(
            "If you want to update latest homework assignment, type: [oj update] to update."
        )
        return
    contest_id, problem_id = (
        assign_to_config[assign_name]["contest_id"],
        assign_to_config[assign_name]["contest_problem_id"],
    )
    endpoint = "contest_submissions?myself=0&contest_id={}&limit=20&problem_id={}".format(
        contest_id, assign_name)
    result = json.loads(curl("get", endpoint=endpoint, use_x_csrf_token=True))
    if result["error"] == "error":
        print("Error : " + result["data"])
        return
    result = result["data"]["results"]
    status_to_response = {
        -1: red_wrapper("WA(Wrong Answer)"),  # WA
        -2: cyan_wrapper("CE(Compilation Error)"),  # CE
        0: green_wrapper("AC(Accept)"),  # AC
        1: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        2: purple_wrapper("TLE(Time Limit Exceeded)"),  # TLE
        3: purple_wrapper("MLE(Memory Limit Exceeded)"),  # ML 
        4: purple_wrapper("RE(Runtime Error)"),  # RE
        8: cyan_wrapper("PAC(Partial Accepted)")
    }
    print(
        "============================================================================"
    )
    print('|  Problem Name: {:58}|'.format(
        assign_to_config[assign_name]["contest_problem_id"] + " [" +
        assign_to_config[assign_name]["contest_name"] + "]"))
    print(
        "============================================================================"
    )
    print('|{:12}|{:27}|   Time|  Mem|               When|'.format(
        "User", "Status"))
    for i in result:
        if i["problem"] != assign_to_config[assign_name]["contest_problem_id"]:
            continue
        timestr = i["create_time"].split("T")[0]
        timestr += " " + i["create_time"].split("T")[1].split(".")[0]
        mydatetmp = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
        hours_added = timedelta(hours=8)
        timestr = mydatetmp + hours_added
        timestr.strftime("%m/%d/%Y, %H:%M:%S")
        if i["result"] != -2:
            try:
                usrname = i["username"].encode('ascii').decode()
            except UnicodeEncodeError:
                usrname = "UCuser"
            print('|{:12}|{:38}|{:5}ms|{:3}MB|{}|'.format(
                usrname, status_to_response[i["result"]],
                i["statistic_info"]["time_cost"],
                (i["statistic_info"]["memory_cost"] / 1048576) + 1, timestr))
        else:
            try:
                usrname = i["username"].encode('ascii').decode()
            except UnicodeEncodeError:
                usrname = "UCuser"
            print('|{:12}|{:38}|{:5}--|{:3}--|{}|'.format(
                usrname, status_to_response[i["result"]], "-----", "---",
                timestr))
    print(
        "============================================================================"
    )