Exemplo n.º 1
0
Arquivo: spoj.py Projeto: Osmose/spoj
def test(problem_name):
    """
    Run the test input for a problem and compare it to the expected
    output.
    """
    t = Terminal()

    program = '{0}/program.py'.format(problem_name)
    test_input_filename = '{0}/input.txt'.format(problem_name)
    with open(test_input_filename, 'rU') as f:
        test_input = f.read()
    with open('{0}/output.txt'.format(problem_name), 'rU') as f:
        expected_output = f.read()

    result = subprocess.check_output(program,
                                     stdin=open(test_input_filename, 'rU'))

    if result.strip() != expected_output.strip():
        print t.bright_red('Test run failed!')
        print t.cyan('<== Input ==>')
        print test_input
        print t.cyan('<== Expected output ==>')
        print expected_output
        print t.cyan('<== Actual output ==>')
        print result
    else:
        print t.bright_green('Test run passed!')
        print t.cyan('<== Input ==>')
        print test_input
        print t.cyan('<== Output ==>')
        print expected_output
Exemplo n.º 2
0
    def _print_stream_item(self, item, pattern=None):
        print("")

        term = Terminal()
        time_label = " on %s at %s" % (term.yellow(item.time.strftime("%a, %d %b %Y")),
                                       term.yellow(item.time.strftime("%H:%M"))) \
                     if item.time is not None else ""
        print("%s%s:" % (term.cyan(item.source), time_label))

        if item.title is not None:
            print("   %s" % self._highlight_pattern(item.title, pattern,
                                                    term.bold_black_on_bright_yellow, term.bold))

        if item.text is not None:
            excerpter = TextExcerpter()
            excerpt, clipped_left, clipped_right = excerpter.get_excerpt(item.text, 220, pattern)

            # Hashtag or mention
            excerpt = re.sub("(?<!\w)([#@])(\w+)",
                             term.green("\\g<1>") + term.bright_green("\\g<2>"), excerpt)
            # URL in one of the forms commonly encountered on the web
            excerpt = re.sub("(\w+://)?[\w.-]+\.[a-zA-Z]{2,4}(?(1)|/)[\w#?&=%/:.-]*",
                             term.bright_magenta_underline("\\g<0>"), excerpt)

            # TODO: This can break previously applied highlighting (e.g. URLs)
            excerpt = self._highlight_pattern(excerpt, pattern, term.black_on_bright_yellow)

            print("   %s%s%s" % ("... " if clipped_left else "", excerpt,
                                 " ..." if clipped_right else ""))

        if item.link is not None:
            print("   %s" % self._highlight_pattern(item.link, pattern,
                                                    term.black_on_bright_yellow_underline,
                                                    term.bright_blue_underline))
Exemplo n.º 3
0
def validate_contribute_json():
    t = Terminal()
    schema = get_schema()

    passed, failed, skipped = [], [], []
    for project in Bar('Validating').iter(list(get_projects())):
        if not project.repos:
            reason = 'No repos found'
            skipped.append((project, reason))
            continue

        # TODO: Handle non-github projects
        for repo in project.repos:
            if repo.startswith('https://github.com'):
                parsed = urlparse(repo)
                user, repo_name = parsed.path.strip('/').split('/')
                url = CONTRIBUTE_JSON_URL.format(user=user, repo=repo_name)

                response = requests.get(url)
                if response.status_code != requests.codes.ok:
                    reason = 'No contribute.json: {0}'.format(
                        response.status_code)
                    failed.append((project, reason))
                    continue

                contribute_json = json.loads(response.text)
                try:
                    jsonschema.validate(contribute_json, schema)
                    passed.append(project)
                except jsonschema.ValidationError as e:
                    reason = 'Invalid contribute.json: {0}'.format(e.message)
                    failed.append((project, reason))

    print t.bright_green('== Passed ==')
    for project in passed:
        print '  ' + t.underline(project.name)

    print t.bright_red('== Failed ==')
    for project, reason in failed:
        print '  {0}\n    {1}'.format(t.underline(project.name), reason)

    print t.bright_yellow('== Skipped ==')
    for project, reason in skipped:
        print '  {0}\n    {1}'.format(t.underline(project.name), reason)
Exemplo n.º 4
0
Arquivo: spoj.py Projeto: Osmose/spoj
def create(problem_name):
    t = Terminal()
    problem_name = problem_name.lower()

    if os.path.isdir(problem_name):
        print t.bright_red(
            'Directory for problem `{0}` already exists!'.format(problem_name))
        return

    url = 'http://www.spoj.com/problems/{0}/'.format(problem_name.upper())
    response = requests.get(url)
    response.raise_for_status()

    # TODO: Handle bad input.
    soup = BeautifulSoup(response.text)
    title = soup.find_all('h1')[1].text.strip()
    test_input, test_output = _find_sample_io(soup)

    # Create problem directory.
    os.makedirs(problem_name)

    # Write program template and chmod +x
    program = '{0}/program.py'.format(problem_name)
    with open(program, 'w') as f:
        f.write(problem_template.format(title=title, url=url))
    st = os.stat(program)
    os.chmod(program, st.st_mode | stat.S_IEXEC)

    with open('{0}/input.txt'.format(problem_name), 'w') as f:
        f.write(test_input)

    with open('{0}/output.txt'.format(problem_name), 'w') as f:
        f.write(test_output)

    print t.bright_green(
        'Directory created for problem `{0}`.'.format(problem_name))
Exemplo n.º 5
0
    def _print_stream_item(self, item, pattern=None):
        print("")

        term = Terminal()
        time_label = " on %s at %s" % (term.yellow(item.time.strftime("%a, %d %b %Y")),
                                       term.yellow(item.time.strftime("%H:%M"))) \
                     if item.time is not None else ""
        print("%s%s:" % (term.cyan(item.source), time_label))

        if item.title is not None:
            print("   %s" % self._highlight_pattern(
                item.title, pattern, term.bold_black_on_bright_yellow,
                term.bold))

        if item.text is not None:
            excerpter = TextExcerpter()
            excerpt, clipped_left, clipped_right = excerpter.get_excerpt(
                item.text, 220, pattern)

            # Hashtag or mention
            excerpt = re.sub(
                "(?<!\w)([#@])(\w+)",
                term.green("\\g<1>") + term.bright_green("\\g<2>"), excerpt)
            # URL in one of the forms commonly encountered on the web
            excerpt = re.sub(
                "(\w+://)?[\w.-]+\.[a-zA-Z]{2,4}(?(1)|/)[\w#?&=%/:.-]*",
                term.bright_magenta_underline("\\g<0>"), excerpt)

            # TODO: This can break previously applied highlighting (e.g. URLs)
            excerpt = self._highlight_pattern(excerpt, pattern,
                                              term.black_on_bright_yellow)

            print("   %s%s%s" % ("... " if clipped_left else "", excerpt,
                                 " ..." if clipped_right else ""))

        if item.link is not None:
            print("   %s" % self._highlight_pattern(
                item.link, pattern, term.black_on_bright_yellow_underline,
                term.bright_blue_underline))
Exemplo n.º 6
0
     if not username == "backup" and passwd == "backup":
         run = False
     logged = True
     print("Successfully logged in.")
     print("Connecting...")
     time.sleep(1)
     print("Connected with options '--public_key %s' " %
           hashlib.sha256("Hello gaming!".encode()).hexdigest())
     print("[INFO] $" + wrap.bold("su") +
           " - use this for get super user permissions.")
     print("[INFO] $" + wrap.bold("sudo") +
           " - use this for execute command with root permissions.")
     print("[INFO] $" + wrap.bold("exit") + " - use this for quit program.")
 if logged:
     if not root:
         cmd = input(wrap.blue("MMCnet:/ ") + wrap.bright_green("$ "))
     else:
         cmd = input("MMCnet:/ # ")
     if cmd.split(" ")[0] == "su":
         tries = 3
         while tries > 0 and not root:
             supass = input(cmd.split(" ")[0] + ": ")
             if supass == "backup":
                 root = True
             else:
                 tries -= 1
                 print("You enter wrong password.")
     elif cmd.split(" ")[0] == "sudo":
         if not root:
             tries = 3
             while tries > 0 and not root: