Exemplo n.º 1
0
def login(args: 'argparse.Namespace') -> None:
    # get service
    service = onlinejudge.dispatch.service_from_url(args.url)
    if service is None:
        sys.exit(1)

    # configure
    kwargs = {}
    if service.get_name() == 'yukicoder':
        if not args.method:
            args.method = 'github'
        if args.method not in ['github', 'twitter']:
            log.failure('login for yukicoder: invalid option: --method %s',
                        args.method)
            sys.exit(1)
        kwargs['method'] = args.method
    else:
        if args.method:
            log.failure('login for %s: invalid option: --method %s',
                        service.get_name(), args.method)
            sys.exit(1)

    with utils.with_cookiejar(utils.new_default_session(),
                              path=args.cookie) as sess:

        if args.check:
            if service.is_logged_in(session=sess):
                log.info('You have already signed in.')
            else:
                log.info('You are not signed in.')
                sys.exit(1)

        else:
            # login
            def get_credentials() -> Tuple[str, str]:
                if args.username is None:
                    args.username = input('Username: '******'If you don\'t want to give your password to this program, you can give only your session tokens.'
            )
            log.info(
                'see: https://github.com/kmyk/online-judge-tools/blob/master/LOGIN_WITH_COOKIES.md'
            )

            service.login(get_credentials, session=sess,
                          **kwargs)  # type: ignore
Exemplo n.º 2
0
 def add(self, s: str, name: str = '') -> None:
     if self.dangling is None:
         if re.search('output', name, re.IGNORECASE) or re.search(
                 '出力', name):
             log.warning('strange name for input string: %s', name)
         self.dangling = LabeledString(name, s)
     else:
         if re.search('input', name, re.IGNORECASE) or re.search(
                 '入力', name):
             if not (re.search('output', name, re.IGNORECASE)
                     or re.search('出力', name)
                     ):  # to ignore titles like "Output for Sample Input 1"
                 log.warning('strange name for output string: %s', name)
         self.data += [TestCase(self.dangling, LabeledString(name, s))]
         self.dangling = None
Exemplo n.º 3
0
    def get(self, directory: pathlib.Path = pathlib.Path.cwd()) -> List[str]:
        if not self.path.exists():
            return []

        log.status('read history from: %s', self.path)
        found = set()
        with open(str(self.path)) as fh:
            for line in fh:
                try:
                    data = json.loads(line)
                except json.decoder.JSONDecodeError as e:
                    log.warning('corrupted line found in: %s', self.path)
                    log.debug('%s', traceback.format_exc())
                    continue
                if pathlib.Path(data['directory']) == directory:
                    found.add(data['url'])
        log.status('found urls in history:\n%s', '\n'.join(found))
        return list(found)
Exemplo n.º 4
0
def download(args):
    problem = onlinejudge.dispatch.problem_from_url(args.url)
    if problem is None:
        sys.exit(1)
    kwargs = {}
    if problem.get_service().get_name() == 'yukicoder':
        for x in args.extra_option:
            if x == 'all':
                kwargs['is_all'] = True
    if args.format is None:
        if problem.get_service().get_name() == 'yukicoder' and kwargs.get(
                'is_all'):
            args.format = 'test/%b.%e'
        else:
            args.format = 'test/sample-%i.%e'
    with utils.session(cookiejar=args.cookie) as sess:
        samples = problem.download(session=sess, **kwargs)
    for i, sample in enumerate(samples):
        log.emit('')
        log.info('sample %d', i)
        for ext, (s, name) in zip(['in', 'out'], sample):
            table = {}
            table['i'] = str(i + 1)
            table['e'] = ext
            table['n'] = name
            table['b'] = os.path.basename(name)
            table['d'] = os.path.dirname(name)
            path = utils.parcentformat(args.format, table)
            log.status('%sput: %s', ext, name)
            log.emit(colorama.Style.BRIGHT + s.rstrip() +
                     colorama.Style.RESET_ALL)
            if args.dry_run:
                continue
            if os.path.exists(path):
                log.warning('file already exists: %s', path)
                if not args.overwrite:
                    log.warning('skipped')
                    continue
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(path, 'w') as fh:
                fh.write(s)
            log.success('saved to: %s', path)
Exemplo n.º 5
0
 def add(self, s, name=""):
     if self.dangling is None:
         if re.search("output", name, re.IGNORECASE) or re.search(
                 "出力", name):
             log.warning("strange name for input string: %s", name)
         self.dangling = {"data": s, "name": name}
     else:
         if re.search("input", name, re.IGNORECASE) or re.search(
                 "入力", name):
             if not (re.search("output", name, re.IGNORECASE)
                     or re.search("出力", name)
                     ):  # to ignore titles like "Output for Sample Input 1"
                 log.warning("strange name for output string: %s", name)
         self.data += [{
             "input": self.dangling,
             "output": {
                 "data": s,
                 "name": name
             }
         }]
         self.dangling = None
Exemplo n.º 6
0
 def add(self, s, name=''):
     if self.dangling is None:
         if re.search('output', name, re.IGNORECASE) or re.search(
                 '出力', name):
             log.warning('strange name for input string: %s', name)
         self.dangling = {'data': s, 'name': name}
     else:
         if re.search('input', name, re.IGNORECASE) or re.search(
                 '入力', name):
             if not (re.search('output', name, re.IGNORECASE)
                     or re.search('出力', name)
                     ):  # to ignore titles like "Output for Sample Input 1"
                 log.warning('strange name for output string: %s', name)
         self.data += [{
             'input': self.dangling,
             'output': {
                 'data': s,
                 'name': name
             },
         }]
         self.dangling = None
def generate_scanner(args):
    if not args.silent:
        log.warning('This feature is ' + log.red('experimental') + '.')
    if args.silent:
        for handler in log.logger.handlers:
            log.removeHandler(handler)
    problem = onlinejudge.dispatch.problem_from_url(args.url)
    if problem is None:
        sys.exit(1)
    with utils.session(cookiejar=args.cookie) as sess:
        it = problem.get_input_format(session=sess)
    if not it:
        log.error('input format not found')
        sys.exit(1)
    try:
        it = tokenize(it)
        it = parse(it)
        it = export(it, use_scanf=args.scanf, repeat_macro=args.repeat_macro)
    except:
        log.error('somethin wrong')
        raise
    log.success('success:')
    print(log.bold(it.rstrip()))  # to stdout
Exemplo n.º 8
0
 def download_sample_cases(
     self,
     session: Optional[requests.Session] = None
 ) -> List[onlinejudge.type.TestCase]:
     session = session or utils.new_default_session()
     # get
     # 自分で書き換えた箇所(初期 AtCoder の問題 URl は末尾が数字になっているため)
     url = self.get_url()
     for _ in range(2):
         resp = _request('GET', url, session=session)
         msgs = AtCoderService._get_messages_from_cookie(resp.cookies)
         if AtCoderService._report_messages(msgs, unexpected=True):
             # example message: "message: You cannot see this page."
             log.warning('are you logged in?')
             return []
         # parse
         soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding),
                                  utils.html_parser)
         samples = utils.SampleZipper()
         if len(list(self._find_sample_tags(soup))) > 0:
             break
         else:
             url = url[:-1] + chr(ord(url[-1]) - ord('a') + ord('1'))
     lang = None
     for pre, h3 in self._find_sample_tags(soup):
         s = utils.textfile(utils.dos2unix(pre.string.lstrip()))
         name = h3.string
         l = self._get_tag_lang(pre)
         if lang is None:
             lang = l
         elif lang != l:
             log.info(
                 'skipped due to language: current one is %s, not %s: %s ',
                 lang, l, name)
             continue
         samples.add(s, name)
     return samples.get()
Exemplo n.º 9
0
 def submit_code(
     self,
     code: bytes,
     language: str,
     session: Optional[requests.Session] = None
 ) -> onlinejudge.type.Submission:  # or SubmissionError
     session = session or utils.new_default_session()
     # get
     url = self.get_url() + '/submit'
     resp = utils.request('GET', url, session=session)
     # parse
     soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding),
                              utils.html_parser)
     form = soup.find('form', id='submit_form')
     if not form:
         log.error('form not found')
         raise onlinejudge.type.SubmissionError
     # post
     form = utils.FormSender(form, url=resp.url)
     form.set('lang', language)
     form.set_file('file', 'code', code)
     form.unset('custom_test')
     resp = form.request(session=session)
     resp.raise_for_status()
     # result
     if 'submissions' in resp.url:
         # example: https://yukicoder.me/submissions/314087
         log.success('success: result: %s', resp.url)
         return onlinejudge.type.DummySubmission(resp.url)
     else:
         log.failure('failure')
         log.debug('redirected to %s', resp.url)
         soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding),
                                  utils.html_parser)
         for div in soup.findAll('div', attrs={'role': 'alert'}):
             log.warning('yukicoder says: "%s"', div.string)
         raise onlinejudge.type.SubmissionError
Exemplo n.º 10
0
    def download_system_cases(
            self,
            session: Optional[requests.Session] = None) -> List[TestCase]:
        session = session or utils.new_default_session()

        # get header
        # reference: http://developers.u-aizu.ac.jp/api?key=judgedat%2Ftestcases%2F%7BproblemId%7D%2Fheader_GET
        url = 'https://judgedat.u-aizu.ac.jp/testcases/{}/header'.format(
            self.problem_id)
        resp = utils.request('GET', url, session=session)
        header = json.loads(resp.content.decode(resp.encoding))

        # get testcases via the official API
        testcases = []  # type: List[TestCase]
        for header in header['headers']:
            # reference: http://developers.u-aizu.ac.jp/api?key=judgedat%2Ftestcases%2F%7BproblemId%7D%2F%7Bserial%7D_GET
            url = 'https://judgedat.u-aizu.ac.jp/testcases/{}/{}'.format(
                self.problem_id, header['serial'])
            resp = utils.request('GET', url, session=session)
            testcase = json.loads(resp.content.decode(resp.encoding))
            skipped = False
            for type in ('in', 'out'):
                if testcase[type].endswith(
                        '..... (terminated because of the limitation)\n'):
                    log.error(
                        'AOJ API says: terminated because of the limitation')
                    skipped = True
            if skipped:
                log.warning("skipped due to the limitation of AOJ API")
                continue
            testcases += [
                TestCase(
                    LabeledString(header['name'], testcase['in']),
                    LabeledString(header['name'], testcase['out']),
                )
            ]
        return testcases
Exemplo n.º 11
0
 def download(self, session: Optional[requests.Session] = None) -> List[onlinejudge.problem.TestCase]:
     session = session or utils.new_default_session()
     # get
     resp = utils.request('GET', self.get_url(), session=session)
     msgs = AtCoderService._get_messages_from_cookie(resp.cookies)
     if AtCoderService._report_messages(msgs, unexpected=True):
         # example message: "message: You cannot see this page."
         log.warning('are you logged in?')
         return []
     # parse
     soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding), utils.html_parser)
     samples = utils.SampleZipper()
     lang = None
     for pre, h3 in self._find_sample_tags(soup):
         s = utils.textfile(utils.dos2unix(pre.string.lstrip()))
         name = h3.string
         l = self._get_tag_lang(pre)
         if lang is None:
             lang = l
         elif lang != l:
             log.info('skipped due to language: current one is %s, not %s: %s ', lang, l, name)
             continue
         samples.add(s, name)
     return samples.get()
Exemplo n.º 12
0
def submit(args: 'argparse.Namespace') -> None:
    # guess url
    history = onlinejudge.implementation.download_history.DownloadHistory()
    if args.file.parent.resolve() == pathlib.Path.cwd():
        guessed_urls = history.get()
    else:
        log.warning(
            'cannot guess URL since the given file is not in the current directory'
        )
        guessed_urls = []
    if args.url is None:
        if len(guessed_urls) == 1:
            args.url = guessed_urls[0]
            log.info('guessed problem: %s', args.url)
        else:
            log.error('failed to guess the URL to submit')
            log.info('please manually specify URL as: $ oj submit URL FILE')
            sys.exit(1)

    # parse url
    problem = onlinejudge.dispatch.problem_from_url(args.url)
    if problem is None:
        sys.exit(1)

    # read code
    with args.file.open('rb') as fh:
        code = fh.read()  # type: bytes
    format_config = {
        'dos2unix': args.format_dos2unix or args.golf,
        'rstrip': args.format_dos2unix or args.golf,
    }
    code = format_code(code, **format_config)

    # report code
    try:
        s = code.decode()
    except UnicodeDecodeError as e:
        log.failure('%s: %s', e.__class__.__name__, str(e))
        s = repr(code)[1:]
    log.info('code (%d byte):', len(code))
    lines = s.splitlines(keepends=True)
    if len(lines) < 30:
        log.emit(log.bold(s))
    else:
        log.emit(log.bold(''.join(lines[:10])))
        log.emit('... (%s lines) ...', len(lines[10:-10]))
        log.emit(log.bold(''.join(lines[-10:])))

    with utils.with_cookiejar(utils.new_default_session(),
                              path=args.cookie) as sess:
        # guess or select language ids
        langs = problem.get_language_dict(session=sess)
        matched_lang_ids = None  # type: Optional[List[str]]
        if args.language in langs:
            matched_lang_ids = [args.language]
        else:
            if args.guess:
                kwargs = {
                    'language_dict': langs,
                    'cxx_latest': args.guess_cxx_latest,
                    'cxx_compiler': args.guess_cxx_compiler,
                    'python_version': args.guess_python_version,
                    'python_interpreter': args.guess_python_interpreter,
                }
                matched_lang_ids = guess_lang_ids_of_file(
                    args.file, code, **kwargs)
                if not matched_lang_ids:
                    log.info('failed to guess languages from the file name')
                    matched_lang_ids = list(langs.keys())
                if args.language is not None:
                    log.info(
                        'you can use `--no-guess` option if you want to do an unusual submission'
                    )
                    matched_lang_ids = select_ids_of_matched_languages(
                        args.language.split(),
                        matched_lang_ids,
                        language_dict=langs)
            else:
                if args.language is None:
                    matched_lang_ids = None
                else:
                    matched_lang_ids = select_ids_of_matched_languages(
                        args.language.split(),
                        list(langs.keys()),
                        language_dict=langs)

        # report selected language ids
        if matched_lang_ids is not None and len(matched_lang_ids) == 1:
            args.language = matched_lang_ids[0]
            log.info('chosen language: %s (%s)', args.language,
                     langs[args.language]['description'])
        else:
            if matched_lang_ids is None:
                log.error('language is unknown')
                log.info('supported languages are:')
            elif len(matched_lang_ids) == 0:
                log.error('no languages are matched')
                log.info('supported languages are:')
            else:
                log.error('Matched languages were not narrowed down to one.')
                log.info('You have to choose:')
            for lang_id in sorted(matched_lang_ids or langs.keys()):
                log.emit('%s (%s)', lang_id, langs[lang_id]['description'])
            sys.exit(1)

        # confirm
        guessed_unmatch = ([problem.get_url()] != guessed_urls)
        if guessed_unmatch:
            samples_text = ('samples of "{}'.format('", "'.join(guessed_urls))
                            if guessed_urls else 'no samples')
            log.warning(
                'the problem "%s" is specified to submit, but %s were downloaded in this directory. this may be mis-operation',
                problem.get_url(), samples_text)
        if args.wait:
            log.status('sleep(%.2f)', args.wait)
            time.sleep(args.wait)
        if not args.yes:
            if guessed_unmatch:
                problem_id = problem.get_url().rstrip('/').split(
                    '/')[-1].split('?')[-1]  # this is too ad-hoc
                key = problem_id[:3] + (problem_id[-1]
                                        if len(problem_id) >= 4 else '')
                sys.stdout.write('Are you sure? Please type "{}" '.format(key))
                sys.stdout.flush()
                c = sys.stdin.readline().rstrip()
                if c != key:
                    log.info('terminated.')
                    return
            else:
                sys.stdout.write('Are you sure? [y/N] ')
                sys.stdout.flush()
                c = sys.stdin.read(1)
                if c.lower() != 'y':
                    log.info('terminated.')
                    return

        # submit
        kwargs = {}
        if problem.get_service().get_name() == 'topcoder':
            if args.full_submission:
                kwargs['kind'] = 'full'
            else:
                kwargs['kind'] = 'example'
        try:
            submission = problem.submit_code(code,
                                             language=args.language,
                                             session=sess,
                                             **kwargs)  # type: ignore
        except onlinejudge.type.SubmissionError:
            log.failure('submission failed')
            sys.exit(1)

        # show result
        if args.open:
            if args.open_browser:
                browser = args.open_browser
            else:
                for browser in default_url_opener:
                    if shutil.which(browser):
                        break
                else:
                    browser = None
                    log.failure(
                        'couldn\'t find browsers to open the url. please specify a browser'
                    )
            if browser:
                log.status('open the submission page with: %s', browser)
                subprocess.check_call([browser, submission.get_url()],
                                      stdin=sys.stdin,
                                      stdout=sys.stdout,
                                      stderr=sys.stderr)
Exemplo n.º 13
0
    def submit(self, code, language, kind='example', session=None):
        assert kind in ['example', 'full']
        driver = session  # rename
        assert isinstance(driver,
                          selenium.webdriver.remote.webdriver.WebDriver)

        # get params and enter the module=Submit page
        url_match_detail = 'https://community.topcoder.com/tc?module=MatchDetails&rd=%d' % self.rd
        log.info('GET: %s', url_match_detail)
        driver.get(url_match_detail)
        link = driver.find_element_by_xpath('//a[text() = "Register/Submit"]')
        log.info('GET: %s', link.get_attribute('href'))
        link.click()
        try:
            link = driver.find_element_by_xpath(
                '//a[text() = "Submit" and contains(@href, "rd=%d")]' %
                self.rd)
        except selenium.common.exceptions.NoSuchElementException:
            log.error(
                'link to submit not found:  Are you registered?  Is the contest running?'
            )
            return None
        log.info('GET: %s', link.get_attribute('href'))
        link.click()

        # select the language
        log.status('click: %s', language)
        language_id = [None, 'Java', None, 'C++', 'C#', 'VB',
                       'Python'].index(language)
        driver.find_element_by_xpath(
            '//form[@name = "codingForm"]//input[@type = "radio" and @name = "lid" and @value = "%d"]'
            % language_id).click()

        # type the code
        log.warning('TODO: make faster')
        driver.find_element_by_xpath(
            '//form[@name = "codingForm"]//div[@class = "CodeMirror-code"]//pre'
        ).click()
        time.sleep(0.1)
        driver.switch_to.active_element.send_keys(
            selenium.webdriver.common.keys.Keys.CONTROL, 'a')
        driver.switch_to.active_element.send_keys(
            selenium.webdriver.common.keys.Keys.BACKSPACE)
        for line in code.splitlines():
            log.status('type: %s', line.decode())
            driver.switch_to.active_element.send_keys(line.decode())
            driver.switch_to.active_element.send_keys(
                selenium.webdriver.common.keys.Keys.RETURN)
            driver.switch_to.active_element.send_keys(
                selenium.webdriver.common.keys.Keys.HOME)
            driver.switch_to.active_element.send_keys(
                selenium.webdriver.common.keys.Keys.CONTROL,
                selenium.webdriver.common.keys.Keys.DELETE)

        # submit
        alt_text = {'example': 'Test', 'full': 'Submit'}[kind]
        log.status('click: %s', alt_text)
        driver.find_element_by_xpath(
            '//form[@name = "codingForm"]//img[@alt = "%s"]' %
            alt_text).click()

        # check
        for _ in range(8):
            if 'module=SubmitSuccess' in driver.current_url:
                break
            time.sleep(1)
        else:
            message = driver.find_element_by_xpath(
                '//textarea[@name = "messages"]').text
            log.failure('%s', message)
            return None

        log.success('success: result: %s', driver.current_url)
        return onlinejudge.submission.CompatibilitySubmission(
            driver.current_url)
Exemplo n.º 14
0
 def download_sample_cases(self, session: Optional[requests.Session] = None) -> List[TestCase]:
     log.warning('use --system option')
     raise NotImplementedError
Exemplo n.º 15
0
 def get_language_dict(self, session=None):
     session = session or utils.new_default_session()
     info = self._get_model(session=session)
     # lang_display_mapping from https://hrcdn.net/hackerrank/assets/codeshell/dist/codeshell-449bb296b091277fedc42b23f7c9c447.js, Sun Feb 19 02:25:36 JST 2017
     lang_display_mapping = {
         "c": "C",
         "cpp": "C++",
         "java": "Java 7",
         "csharp": "C#",
         "haskell": "Haskell",
         "php": "PHP",
         "python": "Python 2",
         "pypy": "Pypy 2",
         "pypy3": "Pypy 3",
         "ruby": "Ruby",
         "perl": "Perl",
         "bash": "BASH",
         "oracle": "Oracle",
         "mysql": "MySQL",
         "sql": "SQL",
         "clojure": "Clojure",
         "scala": "Scala",
         "code": "Generic",
         "text": "Plain Text",
         "brainfuck": "Brainfuck",
         "javascript": "Javascript",
         "typescript": "Typescript",
         "lua": "Lua",
         "sbcl": "Common Lisp (SBCL)",
         "erlang": "Erlang",
         "go": "Go",
         "d": "D",
         "ocaml": "OCaml",
         "pascal": "Pascal",
         "python3": "Python 3",
         "groovy": "Groovy",
         "objectivec": "Objective-C",
         "text_pseudo": "Plain Text",
         "fsharp": "F#",
         "visualbasic": "VB. NET",
         "cobol": "COBOL",
         "tsql": "MS SQL Server",
         "lolcode": "LOLCODE",
         "smalltalk": "Smalltalk",
         "tcl": "Tcl",
         "whitespace": "Whitespace",
         "css": "CSS",
         "html": "HTML",
         "java8": "Java 8",
         "db2": "DB2",
         "octave": "Octave",
         "r": "R",
         "xquery": "XQuery",
         "racket": "Racket",
         "xml": "XML",
         "rust": "Rust",
         "swift": "Swift",
         "elixir": "Elixir",
         "fortran": "Fortran",
         "ada": "Ada",
         "nim": "Nim",
         "julia": "Julia",
         "cpp14": "C++14",
         "coffeescript": "Coffeescript",
     }
     result = {}
     for lang in info["languages"]:
         descr = lang_display_mapping.get(lang)
         if descr is None:
             log.warning("display mapping for language `%s' not found",
                         lang)
             descr = lang
         result[lang] = {"description": descr}
     return result
Exemplo n.º 16
0
 def get_language_dict(
     self,
     session: Optional[requests.Session] = None
 ) -> Dict[str, Dict[str, str]]:
     session = session or utils.new_default_session()
     info = self._get_model(session=session)
     # lang_display_mapping from https://hrcdn.net/hackerrank/assets/codeshell/dist/codeshell-449bb296b091277fedc42b23f7c9c447.js, Sun Feb 19 02:25:36 JST 2017
     lang_display_mapping = {
         'c': 'C',
         'cpp': 'C++',
         'java': 'Java 7',
         'csharp': 'C#',
         'haskell': 'Haskell',
         'php': 'PHP',
         'python': 'Python 2',
         'pypy': 'Pypy 2',
         'pypy3': 'Pypy 3',
         'ruby': 'Ruby',
         'perl': 'Perl',
         'bash': 'BASH',
         'oracle': 'Oracle',
         'mysql': 'MySQL',
         'sql': 'SQL',
         'clojure': 'Clojure',
         'scala': 'Scala',
         'code': 'Generic',
         'text': 'Plain Text',
         'brainfuck': 'Brainfuck',
         'javascript': 'Javascript',
         'typescript': 'Typescript',
         'lua': 'Lua',
         'sbcl': 'Common Lisp (SBCL)',
         'erlang': 'Erlang',
         'go': 'Go',
         'd': 'D',
         'ocaml': 'OCaml',
         'pascal': 'Pascal',
         'python3': 'Python 3',
         'groovy': 'Groovy',
         'objectivec': 'Objective-C',
         'text_pseudo': 'Plain Text',
         'fsharp': 'F#',
         'visualbasic': 'VB. NET',
         'cobol': 'COBOL',
         'tsql': 'MS SQL Server',
         'lolcode': 'LOLCODE',
         'smalltalk': 'Smalltalk',
         'tcl': 'Tcl',
         'whitespace': 'Whitespace',
         'css': 'CSS',
         'html': 'HTML',
         'java8': 'Java 8',
         'db2': 'DB2',
         'octave': 'Octave',
         'r': 'R',
         'xquery': 'XQuery',
         'racket': 'Racket',
         'xml': 'XML',
         'rust': 'Rust',
         'swift': 'Swift',
         'elixir': 'Elixir',
         'fortran': 'Fortran',
         'ada': 'Ada',
         'nim': 'Nim',
         'julia': 'Julia',
         'cpp14': 'C++14',
         'coffeescript': 'Coffeescript'
     }
     result = {}
     for lang in info['languages']:
         descr = lang_display_mapping.get(lang)
         if descr is None:
             log.warning('display mapping for language `%s\' not found',
                         lang)
             descr = lang
         result[lang] = {'description': descr}
     return result
Exemplo n.º 17
0
def download(args: 'argparse.Namespace') -> None:
    # prepare values
    problem = onlinejudge.dispatch.problem_from_url(args.url)
    if problem is None:
        sys.exit(1)
    kwargs = {}
    if args.system:
        supported_service_names = ['aoj', 'yukicoder']
        if problem.get_service().get_name() not in supported_service_names:
            log.error('--system for %s is not supported',
                      problem.get_service().get_name())
            sys.exit(1)
        kwargs['is_system'] = True
    if args.format is None:
        if kwargs.get('is_system'):
            if problem.get_service().get_name() == 'yukicoder':
                args.format = '%b.%e'
            else:
                args.format = '%i.%e'
        else:
            args.format = 'sample-%i.%e'

    # get samples from the server
    with utils.with_cookiejar(utils.new_default_session(),
                              path=args.cookie) as sess:
        samples = problem.download(session=sess, **kwargs)  # type: ignore

    # write samples to files
    for i, sample in enumerate(samples):
        log.emit('')
        log.info('sample %d', i)
        for kind in ['input', 'output']:
            ext = kind[:-3]
            data = getattr(sample, kind).data
            name = getattr(sample, kind).name
            table = {}
            table['i'] = str(i + 1)
            table['e'] = ext
            table['n'] = name
            table['b'] = os.path.basename(name)
            table['d'] = os.path.dirname(name)
            path = os.path.join(args.directory,
                                utils.parcentformat(args.format, table))
            log.status('%sput: %s', ext, name)
            log.emit(colorama.Style.BRIGHT + data.rstrip() +
                     colorama.Style.RESET_ALL)
            if args.dry_run:
                continue
            if os.path.exists(path):
                log.warning('file already exists: %s', path)
                if not args.overwrite:
                    log.warning('skipped')
                    continue
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(path, 'w') as fh:
                fh.write(data)
            log.success('saved to: %s', path)

    # print json
    if args.json:
        print(json.dumps(list(map(convert_sample_to_dict, samples))))
Exemplo n.º 18
0
def download(args: 'argparse.Namespace') -> None:
    # prepare values
    problem = onlinejudge.dispatch.problem_from_url(args.url)
    if problem is None:
        sys.exit(1)
    is_default_format = args.format is None and args.directory is None  # must be here since args.directory and args.format are overwritten
    if args.directory is None:
        args.directory = pathlib.Path('test')
    if args.format is None:
        if args.system:
            if problem.get_service().get_name() == 'yukicoder':
                args.format = '%b.%e'
            else:
                args.format = '%i.%e'
        else:
            args.format = 'sample-%i.%e'

    # get samples from the server
    with utils.with_cookiejar(utils.new_default_session(),
                              path=args.cookie) as sess:
        if args.system:
            samples = problem.download_system_cases(
                session=sess)  # type: ignore
        else:
            samples = problem.download_sample_cases(
                session=sess)  # type: ignore

    # append the history for submit command
    if not args.dry_run and is_default_format:
        history = onlinejudge.implementation.download_history.DownloadHistory()
        history.add(problem)

    # write samples to files
    for i, sample in enumerate(samples):
        log.emit('')
        log.info('sample %d', i)
        for kind in ['input', 'output']:
            ext = kind[:-3]
            data = getattr(sample, kind).data
            name = getattr(sample, kind).name
            table = {}
            table['i'] = str(i + 1)
            table['e'] = ext
            table['n'] = name
            table['b'] = os.path.basename(name)
            table['d'] = os.path.dirname(name)
            path = args.directory / utils.percentformat(
                args.format, table)  # type: pathlib.Path
            log.status('%sput: %s', ext, name)
            if not args.silent:
                log.emit(colorama.Style.BRIGHT + data.rstrip() +
                         colorama.Style.RESET_ALL)
            if args.dry_run:
                continue
            if path.exists():
                log.warning('file already exists: %s', path)
                if not args.overwrite:
                    log.warning('skipped')
                    continue
            path.parent.mkdir(parents=True, exist_ok=True)
            with path.open('w') as fh:
                fh.write(data)
            log.success('saved to: %s', path)

    # print json
    if args.json:
        print(json.dumps(list(map(convert_sample_to_dict, samples))))