async def display_problem(self, user, problem_code): if Problem(None, problem_code) in self.contest.problems: info = { 'bot': self.bot, 'channel': self.channel, 'user': user, 'content': [problem_code], 'description': "Details on problem `{0}` in the `{1}` contest".format( problem_code, self.contest.name), } await handlers.Problem().view(info, in_contest=True) else: em = Embed(title="Problems List", description="Problems in the `{}` contest.".format( self.contest.name), color=BOT_COLOUR) em.add_field(name="Problem Number", value="\n".join( map(str, range(1, len(self.contest.problems) + 1)))) em.add_field(name="Problem Code", value="\n".join(x.code for x in self.contest.problems)) em.add_field(name="Problem Name", value="\n".join(x.name for x in self.contest.problems)) await self.bot.send_message(self.channel, embed=em)
def remote_judge_add_remote_problem(data: dict): """ 客户端发送添加题目请求 """ import datetime from flask import request oj, remoteProblemID = data["oj"], data["remoteProblemID"] if oj not in config.REMOTE_JUDGE_OJS: return make_response(-1, message="不合法的OJ") if not permission_manager.has_permission(session.get("uid"), "problem.create"): emit("server_response", { "message": "你没有权限这样做", "ok": False }, room=request.sid) return problem = Problem(create_time=datetime.datetime.now()) problem.uploader_id = int(session.get("uid")) db.session.add(problem) db.session.commit() print("Fetching: ", [oj, remoteProblemID, str(problem.id), request.sid]) remote_judge_queue.send_task( "judgers.remote.fetch_problem", [oj, remoteProblemID, str(problem.id), request.sid]) emit("message", {"message": "正在爬取"}, room=request.sid)
def parse(filename): with open(filename) as f: r = lambda: f.readline().strip() rows, cols, drones, deadline, max_payload = map(int, r().split()) n_products = int(r()) Products = map(int, r().split()) assert n_products == len(Products) n_warehouses = int(r()) warehouses = [] for w in range(n_warehouses): row, col = map(int, r().split()) products = map(int, r().split()) warehouses.append(Warehouse(w, row, col, products)) n_orders = int(r()) orders = [] for i in range(n_orders): row, col = map(int, r().split()) _ = int(r()) products = map(int, r().split()) orders.append(Order(i, row, col, products)) return Problem(Products, warehouses, orders, rows, cols, drones, deadline, max_payload)
def admin_addproblem(): form = ProblemForm() error = None if request.method == 'POST' and form.validate(): inputfile = request.files['inputfile'] outputfile = request.files['outputfile'] problem = Problem(form.title.data, form.description.data, form.pinput.data, form.poutput.data, form.sinput.data, form.soutput.data, form.hint.data, form.time_limit.data, form.memory_limit.data) problem.save() inputfile.save( os.path.join(app.config['UPLOAD_FOLDER'], '.'.join([str(problem.pid), 'in']))) outputfile.save( os.path.join(app.config['UPLOAD_FOLDER'], '.'.join([str(problem.pid), 'out']))) print 'upload successfully!' return redirect(url_for('admin_problemset')) error = get_error(form) if error: flash(error) return render_template('admin_addproblem.html', form=form)
def crawl(self, key: str) -> Problem: logger.info("[*] start crawl problem SDUT-{}".format(key)) r = requests.get( f"https://acm.sdut.edu.cn/onlinejudge2/index.php/API_ng/problems/{key}" ) problem = Problem(SDUTCrawler.NAMESPACE, key) meta_nodes = r.json().get('data') if meta_nodes is None or len(meta_nodes) is 0: raise CrawlerException(f"SDUT problem-{key} is not found") problem.title = meta_nodes.get('title') problem.description = meta_nodes.get('description') problem.description = replace_image_src(IMAGE_TAG_REGULAR, problem.description, self.ORIGIN) problem.input = meta_nodes.get('input') problem.output = meta_nodes.get('output') problem.hint = meta_nodes.get('hint') problem.source = meta_nodes.get('source') problem.sample_input = meta_nodes.get('sampleInput') problem.sample_output = meta_nodes.get('sampleOutput') problem.memory_limit = meta_nodes.get('memoryLimit') problem.time_limit = meta_nodes.get('timeLimit') problem.language = ['C++', "JAVA", "C"] return problem
async def load(bot): global loading loading = True global problem_list global discord_users_list global users global judgeserver global judges global locks global db db = pymysql.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_DATABASE) locks["problem"] = defaultdict(lambda: asyncio.Lock()) locks["submissions"] = defaultdict(lambda: asyncio.Lock()) locks["judge"] = defaultdict(lambda: asyncio.Lock()) locks["user"] = defaultdict(lambda: asyncio.Lock()) locks["contest"] = defaultdict(lambda: asyncio.Lock()) locks["db"] = defaultdict(lambda: threading.RLock()) from bridge import JudgeHandler, JudgeServer from models import Problem, Player judgeserver = JudgeServer(BRIDGED_IP_ADDRESS, JudgeHandler) threading.Thread(target=judgeserver.serve_forever).start() for x in db_select("dmob_problem"): problem_list[x[2]] = Problem(*x) for x in db_select("dmob_user"): discord_users_list[x[0]] = await bot.get_user_info(x[0]) users[x[0]] = Player(*x) loading = False
def create_problem(id_=None): if id_: pass form = ProblemForm() if request.method == 'POST': title = request.form['title'] level = request.form.get('level', '') category_id = request.form.get('category', None) if not category_id: category = Category(title='Unknown category') category_id = category.id text = request.form['text'] knowledge = request.form.get('knowledge', None) answer = request.form.get('answer', None) # NotBug: i specialy do not use here try except so user can find problem. we got here prototype any way problem_ = Problem(title=title, level=level, category_id=category_id, text=text, knowledge=knowledge, answer=answer) db.session.add(problem_) db.session.commit() return redirect(url_for('problem', id_=problem_.id)) context = { 'form': form } context.update(get_common_data()) return render_template('create_problem.html', context=context)
def create_profile(sender, **kw): user = kw["instance"] base = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if kw["created"]: os.mkdir(os.path.join(base + '/documents/', user.username)) os.mkdir(os.path.join(base + '/documents/' + user.username, 'models')) os.mkdir(os.path.join(base + '/documents/' + user.username, 'logs')) os.mkdir(os.path.join(base + '/documents/' + user.username, 'data')) profile = UserProfile(user=user) profile.save() problem = Problem(title='Problema_' + user.username, status=Problem.EXPECTING_TRAINING_FILE) problem.save() profile.problem = problem profile.save()
def crawl(self, key: str) -> Problem: logger.info("[*] start crawl problem POJ-{}".format(key)) r = requests.get(f"http://poj.org/problem?id={key}") bs = BeautifulSoup(r.content, "html.parser") problem = Problem(POJCrawler.NAMESPACE, key) problem.title = bs.select(".ptt")[0].get_text() meta_nodes = bs.select(".plm")[0].select("td") time_limit_raw = meta_nodes[0].get_text() matches = re.findall(r"Time Limit: (\d+)MS", time_limit_raw) if len(matches) != 1: raise CrawlerException( f"no time limit found, raw: '{time_limit_raw}'") problem.time_limit = int(matches[0]) memory_limit_raw = meta_nodes[2].get_text() matches = re.findall(r"Memory Limit: (\d+)K", memory_limit_raw) if len(matches) != 1: raise CrawlerException( f"no memory limit found, raw: '{memory_limit_raw}'") problem.memory_limit = int(matches[0]) desc_nodes = bs.select(".ptx") try: problem.description = desc_nodes[0].prettify() problem.input = desc_nodes[1].prettify() problem.output = desc_nodes[2].prettify() problem.hint = desc_nodes[3].prettify() problem.source = desc_nodes[4].get_text() except IndexError: pass problem.description = replace_image_src(IMAGE_TAG_REGULAR, problem.description, self.OJ_ORIGIN) sample_nodes = bs.select(".sio") try: problem.sample_input = sample_nodes[0].get_text() problem.sample_output = sample_nodes[1].get_text() except IndexError: pass problem.language = ['C++', "JAVA", "C"] return problem
def add_problem(request, patient_id): role = UserProfile.objects.get(user=request.user).role authenticated = True if (role == 'physician' or role == 'admin') else False if 'problem_name' in request.POST: problem = Problem(patient=User.objects.get(id=patient_id), problem_name=request.POST['problem_name'], concept_id=request.POST['concept_id'], authenticated=authenticated) problem.save() elif 'goal' in request.POST: goal = Goal(patient=User.objects.get(id=patient_id), goal=request.POST['goal']) goal.save() elif 'todo' in request.POST: # print 'todo' # print request.POST todo = ToDo(patient=User.objects.get(id=patient_id), todo=request.POST['todo']) todo.save() return HttpResponse('added')
def new_problem(): # current_user = Account.query.first() #debug if current_user.permLevel > 1: return redirect(url_for('index')) form = EditProblemForm() if form.validate_on_submit(): # tag appen_tag = [] tags = form.tags.data.split(';') for t in tags: db_tag = Tag.query.filter_by(tag_name=t).first() if db_tag: appen_tag.append(db_tag) # info info = { 'description': '', 'input_format': '', 'output_format': '', 'sample_input': '', 'sample_output': '', 'hint': '', 'source': '', 'td_description': '', 'td_num': 2 } info['description'] = form.description.data info['input_format'] = form.input_format.data info['output_format'] = form.output_format.data info['sample_input'] = form.sample_input.data info['sample_output'] = form.sample_output.data new_prob = Problem(problemName=form.problem_name.data, uid=current_user.uid, info=json.dumps(info)) new_prob.problem_tag = appen_tag db.session.add(new_prob) db.session.commit() flash('新增成功', 'success') return render_template('problem_edit.html', form=form, form_action=url_for('.new_problem'))
def claim(self): r = self.api_call(self.base_url + "/jobs") print("text:", repr(r.text)) if not r.text: return None required_fields = [ "id", "language", "source", "pid", "test_cases", "time_limit", "memory_limit", "generator_code", "grader_code", "source_verifier_code" ] # create job object obj = r.json() if not all(field in obj for field in required_fields): return None problem = Problem(obj["pid"], obj["test_cases"], obj["time_limit"], obj["memory_limit"], obj["generator_code"], Python3, obj["grader_code"], Python3, obj["source_verifier_code"], Python3) language = languages.get(obj["language"]) if not language: return None # TODO: should definitely not do this return Job(obj["id"], problem, obj["source"], language)
def crawl(self, key: str) -> Problem: logger.info("[*] start crawl problem HDU-{}".format(key)) r = requests.get(f"http://acm.hdu.edu.cn/showproblem.php?pid={key}") bs = BeautifulSoup(r.content, "html.parser") problem = Problem(HDUCrawler.NAMESPACE, key) problem.title = bs.find('h1').get_text() meta_nodes = bs.find('span').get_text() time_limit_raw = re.findall( r"Time Limit: \d+/(\d+) MS \(Java/Others\)", meta_nodes) if len(time_limit_raw) != 1: raise CrawlerException( f"no time limit found, HDU problem: '{key}'") problem.time_limit = time_limit_raw[0] memory_limit_raw = re.findall( r"Memory Limit: \d+/(\d+) K \(Java/Others\)", meta_nodes) if len(memory_limit_raw) != 1: raise CrawlerException( f"no memory limit found, raw: '{memory_limit_raw}'") problem.memory_limit = memory_limit_raw[0] desc_nodes = bs.select(".panel_content") try: problem.description = desc_nodes[0].prettify() problem.input = desc_nodes[1].prettify() problem.output = desc_nodes[2].prettify() problem.sample_input = desc_nodes[3].get_text() problem.sample_output = desc_nodes[4].get_text() problem.source = desc_nodes[5].get_text() problem.hint = desc_nodes[6].get_text() except IndexError: pass problem.description = replace_image_src(IMAGE_TAG_REGULAR, problem.description, self.ORIGIN) problem.language = ['C++', "JAVA", "C"] return problem
def parse_problem_page(page_soup): for row in page_soup.table.tbody.find_all('tr'): cols = row.find_all('td') if len(cols) != 11: raise ValueError('Unexpected number of columns') problem_id, problem_name = parse_title_cell(cols[0]) total_submissions = int(cols[1].string) accepted_submissions = int(cols[2].string) submissions_ratio = (int(cols[3].string.replace('%', '')) / 100) if '--' not in cols[3].string else None fastest_submission = float( cols[4].string) if '--' not in cols[4].string else None total_users = int(cols[5].string) accepted_users = int(cols[6].string) users_ratio = (int(cols[7].string.replace('%', '')) / 100) if '--' not in cols[3].string else None min_difficulty, max_difficulty = parse_difficulty_cell(cols[8]) yield Problem(problem_id, problem_name, total_submissions, accepted_submissions, submissions_ratio, fastest_submission, total_users, accepted_users, users_ratio, min_difficulty, max_difficulty)
def admin_add_problem(): '''后台添加题目页面''' form = ProblemForm() if request.method == 'GET': return render_template('admin_addproblem.html', form=form) else: inputfile = request.files['inputfile'] outputfile = request.files['outputfile'] problem_count = Problem.query.count() inputfile.save( os.path.join(app.config['DATA_FOLDER'], '.'.join([str(problem_count + 1001), 'in']))) outputfile.save( os.path.join(app.config['DATA_FOLDER'], '.'.join([str(problem_count + 1001), 'out']))) problem = Problem(title = form.title.data, desc = form.desc.data, pinput = form.pinput.data, \ poutput = form.poutput.data, sinput = form.sinput.data, soutput = form.soutput.data, \ hint = form.hint.data, time_limit = int(form.time_limit.data), memory_limit = int(form.memory_limit.data)) db.session.add(problem) db.session.commit() flash(UPLOAD_SUCCESS) return redirect('/admin/problemset')
import re from models import Assignment, Problem file = open("management/commands/sample.tex", "r") data = file.read() m = re.search(r"assignment{(.*)}", data) name = m.group(1) m = re.search(r"duedate{(.*)}", data) due_date = m.group(1) asgt = Assignment(name=name, due_date=due_date) asgt.save() problems = [] problem_locs = [m.end() for m in re.finditer("begin{problem}", data)] for loc in problem_locs: p = Problem() m = re.search(r"\[(.*)\]", data[loc:]) p.name = m.group(1) n = re.search(r"\[(.*)\]", data[loc + m.end():]) p.points = n.group(1) o = re.search(r"([^]]*)\\end{problem}", data[loc + m.end() + n.end():]) p.solution = o.group(1) p.save() asgt.problems.add(p)
def storeProb(myProb, myAns): myProb2 = Problem(myProb, myAns) myProb2.put() return myProb2
def parse(): logger = logging.getLogger('parser_logger') logger.info('Starting Parsing') try: # List of problems to store parsed Problems problems = list() with open('robots.mat') as input_text: for line in input_text: # Remove whitespaces line = line.replace(' ','').replace('\n', '') try: question_number = int(line[:line.index(':')]) problem = Problem(question_number=question_number) # logger.info('Parsing question : %i' % problem.question_number) except ValueError as e: logger.critical('ValueError %s' % (str(e))) sys.exit(1) # Remove the question number part line = line[line.index(':')+1:] try: i = line.index('#') except ValueError: i = -1 if i > 0: # If it has obstacles, parse the robots and obstacles robots = line[:i].split('),') # Obstacles (still in string) obstacles = line[i + 1:].split(';') problem_obstacles = list() # Parse the tuples for obstacle in obstacles: coordinates = obstacle.split('),') # Parse the string list coordinates[:] = [coordinate.strip('()') for coordinate in coordinates] coordinates[:] = [coordinate.split(',') for coordinate in coordinates] vertices = list() for coordinate in coordinates: try: x = float(coordinate[0]) y = float(coordinate[1]) vert = (x, y) vertices.append(vert) except ValueError as e: logger.critical('ValueError %s' % str(e)) sys.exit(1) problem_obstacles.append(Obstacle(vertices=vertices, problem=problem)) problem.obstacles = problem_obstacles # logger.info('There are %i obstacles' % len(problem.obstacles)) else: # There is no obstacle robots = line.split('),') robots[:] = [rob.strip('()') for rob in robots] robots[:] = [rob.split(',') for rob in robots] problem_robots = list() for rob in robots: try: x = float(rob[0]) y = float(rob[1]) vertex = (x, y) rb = Robot(vertex=vertex, problem=problem) except ValueError as e: logger.critical('ValueError %s' % str(e)) sys.exit(1) problem_robots.append(rb) problem.robots = problem_robots # logger.info('There are %i robots' % len(problem.robots)) logger.info('Successfully parsed Question number : %i' % problem.question_number) problems.append(problem) logger.info('Parse Successful') return problems except IOError as e: logger.critical('IOError %i: %s' % (e.errno, e.strerror)) sys.exit(1)
def storeProb(myProb, myAns, url=""): if myProb == None: myProb = "" if myAns == None: myAns = "" myProb2 = Problem(problem=myProb, solution=myAns, url=url) myProb2.put() return myProb2
def problem_from_data ( data ) : return Problem(data["contestId"], data["index"], data["name"], str(data["tags"]), data.get("points", 0))
def post(self): """ Creates a problem """ data = request.json ############# # Update DB # ############# # Create problem problem_name = data.get('name') description_english = data.get('description_english') description_spanish = data.get('description_spanish') memory_limit = data.get('memory_limit') time_limit = data.get('time_limit') language = data.get('language') author_id = data.get('author_id') difficulty = data.get('difficulty') code = data.get('code') template = data.get('template') signature = data.get('signature') test_cases = data['test_cases'] topic_id = data['topic_id'] # Added for subproblems functionality is_subproblem = data.get('is_subproblem') belongs_to = data.get('belongs_to') new_problem = Problem(name=problem_name, author_id=author_id, difficulty=difficulty, active=True, language=language, code=code, template=template, signature=signature, description_english=description_english, description_spanish=description_spanish, time_limit=time_limit, memory_limit=memory_limit, is_subproblem=is_subproblem, belongs_to=belongs_to) db.session.add(new_problem) db.session.commit() problem_id = new_problem.id new_stat = Statistic(total_submissions = 0, total_accepted_submissions = 0, problem_id = new_problem.id) db.session.add(new_stat) db.session.commit() # Create problem-topic entry if (not(is_subproblem)): new_problemtopic = ProblemTopic(problem_id=problem_id, topic_id=topic_id) db.session.add(new_problemtopic) db.session.commit() # Create test cases for i in range(len(test_cases)): new_case = Case(is_sample=test_cases[i]['is_sample'], input=test_cases[i]['input'], feedback=test_cases[i]['feedback'], output=test_cases[i]['output'], problem_id=problem_id) db.session.add(new_case) db.session.commit() # Add input and output files to filesystem json = {} json['test_cases'] = data['test_cases'] json['problem_id'] = problem_id result = services.upload_problem(json) return result