Пример #1
0
 def print_all(container):
     prefix = container.get_log_prefix()
     lines = container.logs(_iter=False,
                            follow=self.follow,
                            lines=self.lines).split('\n')
     text = '\n'.join(prefix + to_unicode(l) for l in lines)
     click.echo_via_pager(text.strip('\n'))
Пример #2
0
def problem_035(limit,verbose):
    """Circular primes.

    The number, 197, is called a circular prime because all rotations of the
    digits: 197, 971, and 719, are themselves prime.
    
    There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37,
    71, 73, 79, and 97.
    
    How many circular primes are there below one million?
    
    """

    cache = PrimeCache(limit + 1)
    cache.ensure_factors_for(limit)
    primes = set(cache.primes)
    
    with click.progressbar(primes) as bar:
        circular = [p for p in bar if is_circular_prime(primes, p)]
        
    if verbose > 0:
        circular.sort()
        lines = ("{}: {}".format(p, ', '.join(str(n) for n in rotate_number(p))) for p in circular)
        result = '\n'.join(lines)
        if len(circular) > 100:
            click.echo_via_pager(result)
        else:
            click.echo(result)
        
    click.echo(len(circular))
Пример #3
0
def timeline(ctx, pager, limit, twtfile, sorting, timeout, porcelain, source, cache):
    """Retrieve your personal timeline."""
    if source:
        source_obj = ctx.obj["conf"].get_source_by_nick(source)
        if not source_obj:
            logger.debug("Not following {0}, trying as URL".format(source))
            source_obj = Source(source, source)
        sources = [source_obj]
    else:
        sources = ctx.obj["conf"].following

    tweets = get_remote_tweets(sources, limit, timeout, cache)

    if twtfile and not source:
        source = Source(ctx.obj["conf"].nick, ctx.obj["conf"].twturl, file=twtfile)
        tweets.extend(get_local_tweets(source, limit))

    tweets = sort_and_truncate_tweets(tweets, sorting, limit)

    if not tweets:
        return

    if pager:
        click.echo_via_pager(style_timeline(tweets, porcelain))
    else:
        click.echo(style_timeline(tweets, porcelain))
Пример #4
0
    def view_url(self, url):
        """View the given url.

        :type index: int
        :param index: The index for the given item, used with the
            gh view [index] commend.

        :type url: str
        :param url: The url to view
        """
        contents = self.generate_url_contents(url)
        header = click.style('Viewing ' + url + '\n\n',
                             fg=self.config.clr_message)
        contents = header + contents
        contents += click.style(('\nView this article in a browser with'
                                 ' the -b/--browser flag.\n'),
                                fg=self.config.clr_message)
        contents += click.style(('\nPress q to quit viewing this '
                                 'article.\n'),
                                fg=self.config.clr_message)
        if contents == '{"error":"Not Found"}\n':
            click.secho('Invalid user/repo combination.')
            return
        color = None
        if platform.system() == 'Windows':
            color = True
        click.echo_via_pager(contents, color)
Пример #5
0
def main():
    """Summarize text."""
    # todo: use argparse or click or something like that
    input_dict = get_input()

    summarizer = Summarizer()
    result = summarizer.summarize(
        input_dict['text'],
        input_dict['title'],
        'Undefined',
        'Undefined',
    )
    result = summarizer.sortScore(result)
    result = summarizer.sortSentences(result[:30])

    # todo: paginate this output
    click.clear()
    summary = "Summary of '%s':\n\n" % input_dict['title']
    for r in result:
        summary += r['sentence'] + "\n\n"

    summary += "Press [q] to exit."

    click.echo_via_pager(summary)
    click.clear()
Пример #6
0
    def write(self, data):
        if isinstance(data, six.binary_type):
            data = data.decode('utf-8')

        # echo_via_pager() already appends a '\n' at the end of text,
        # so we use rstrip() to remove extra newlines (#89)
        click.echo_via_pager(data.rstrip())
Пример #7
0
def ledger(globs: ROAttrDict, task: str, duration: str, rate: str):
    """Generate ledger compatible data file.

    \f
    Args:
        globs: Global options object
        task: Task name to operate on
        duration: Time window to filter on
        rate: Rate to assign hours in report

    """
    if task == 'default':
        # Lazy way to remove duplicate argument definitions
        task = None
    events = filter_events(globs, task, duration)

    def gen_output():
        if events.running():
            yield ';; Running event not included in output!\n'
        for event in events:
            if not event.delta:
                continue
            end = event.start + event.delta
            hours = event.delta.total_seconds() / 3600
            yield f'{event.start:%F * %H:%M}-{end:%H:%M}'
            yield '    (task:{})  {:.2f}h{}{}\n'.format(
                event.task, hours, ' @ {}'.format(rate) if rate else '',
                '  ; {}'.format(event.message) if event.message else ''
            )
        if events.running():
            yield ';; Running event not included in output!\n'

    click.echo_via_pager(gen_output())
Пример #8
0
def timeclock(globs: ROAttrDict, task: str, duration: str):
    """Generate ledger compatible timeclock file.

    \f
    Args:
        globs: Global options object
        task: Task name to operate on
        duration: Time window to filter on
    """
    if task == 'default':
        # Lazy way to remove duplicate argument definitions
        task = None
    events = filter_events(globs, task, duration)

    def gen_output():
        if events.running():
            yield ';; Running event not included in output!\n'
        for event in events:
            if not event.delta:
                continue
            yield f'i {event.start:%F %T} {event.task}\n'
            yield f'o {event.start + event.delta:%F %T}' \
                f'{"  ; " + event.message if event.message else ""}\n'
        if events.running():
            yield ';; Running event not included in output!\n'

    click.echo_via_pager(gen_output())
Пример #9
0
def selectFolder(M, moreMessages = ""):
    resp, data = M.list('""', '*')
    #print(data)
    listAllFolders = listFolderNames(data, moreMessages)
    if not listAllFolders: listAllFolders = listFolderNames(data, "")
    listFolders = listAllFolders
    while listFolders:
        if (listFolders.count('\n') == 0):
            nF = nameFolder(listFolders)
            nF = nF.strip('\n')
            print("nameFolder", nF)
            return(nF)
        rows, columns = os.popen('stty size', 'r').read().split()
        if listFolders.count('\n') > int(rows) - 2:
            click.echo_via_pager(listFolders)
        else:
            print(listFolders)
        print(len(listFolders))
        inNameFolder = input("Folder number [-cf] Create Folder // A string to select a smaller set of folders ")
        
        if (len(inNameFolder) > 0) and (inNameFolder == '-cf'):
           nfn = input("New folder name? ")
           iFolder = createFolder(M, nfn, moreMessages)
           return(iFolder)
           #listFolders = iFolder
        listFolders = listFolderNames(listFolders.split('\n'), inNameFolder)
        if (not inNameFolder):
            print("Entra")
            listAllFolders = listFolderNames(data, "")
            listFolders = ""
        if (not listFolders):
            listFolders = listAllFolders
Пример #10
0
def print_formated(fmatches, format):
    if format == 'json':
        from json import dumps
        click.echo(dumps(fmatches,
                         sort_keys=True,
                         indent=2,
                         separators=(',', ': ')))
    elif format == 'yaml':
        from yaml import dump
        click.echo(dump(fmatches,
                        default_flow_style=False,
                        width=80,
                        indent=4))
    else:
        to_print = []
        for filename, comments in sorted(fmatches.items()):
            to_print.append(click.style(filename, fg='red', bold=True))
            for type, lines in sorted(comments.items()):
                to_print.append(click.style(type, fg='blue', bold=True))
                for number, content in sorted(lines.items()):
                    to_print.append(' '.join([
                        click.style('  line %d -' % number,
                                    fg='white'), click.style(content,
                                                             bold=True)
                    ]))
            to_print.append('\n')

        if format == 'plain':
            click.echo('\n'.join(to_print))
        else:
            click.echo_via_pager('\n'.join(to_print))
Пример #11
0
    def visit_immutation(self, node, children):
        context = self._final_context()
        child_type = children[0].expr_name

        if child_type == 'preview':
            if self.tool == 'httpie':
                command = ['http'] + context.httpie_args(self.method,
                                                         quote=True)
            else:
                assert self.tool == 'curl'
                command = ['curl'] + context.curl_args(self.method, quote=True)
            click.echo(' '.join(command))
        elif child_type == 'action':
            output = BytesIO()
            try:
                env = Environment(stdout=output, is_windows=False)
                httpie_main(context.httpie_args(self.method), env=env)
                content = output.getvalue()
            finally:
                output.close()

            # XXX: Work around a bug of click.echo_via_pager(). When you pass
            # a bytestring to echo_via_pager(), it converts the bytestring with
            # str(b'abc'), which makes it "b'abc'".
            if six.PY2:
                content = unicode(content, 'utf-8')  # noqa
            else:
                content = str(content, 'utf-8')
            click.echo_via_pager(content)

        return node
Пример #12
0
def check_result(returncode, output='', success_message='DONE',
                 error_message='ERROR', raise_exception=True,
                 ask_for_details=True, show_details=True,
                 ):
    if returncode == 0:
        click.secho(success_message, fg='green')
    else:
        click.secho(error_message, fg='red')

    if returncode != 0:
        if ask_for_details:
            show_details = click.confirm(
                '    Show details?',
                default=False,
                abort=False,
                prompt_suffix=' ',
                show_default=True,
                err=False,
            )
            if show_details:
                click.echo_via_pager(output)
        elif show_details and output:
                click.echo(output)

        if raise_exception:
            raise click.ClickException(
                'Something went wrong, please look at the logs.')
Пример #13
0
 def paged_display(source, sep='\n'):
     """Display paginated text so that the user can scroll through it;
     works with any iterable"""
     if not source:
         return
     text = sep.join(str(x) for x in source)
     click.echo_via_pager(text)
Пример #14
0
def delete(config, a, se):
    """
    Deletes all the directory content (files, dirs)
    """
    if a and click.confirm("Delete all contents of " + config.dir_to_use + " ?"):
        click.echo("Attempting to delete: " + str(analyzer.get_entries_count()) + " entries...\n")

        cleaner.delete_dir_content(config.dir_to_use)
        filemanager.write_cleanup_report(cleaner.cleanup_data, config.app_dir)
        filemanager.pickle_data("last-cleanup", cleaner.cleanup_data, config.app_dir)  # Make clean up data persistent

        click.echo("\nDeletion complete!")
        click.echo("* Deletions: " + str(cleaner.cleanup_data["deletions"]))
        click.echo("* Deletion size: " + converter.human_readable_size(cleaner.cleanup_data["size"]))
        click.echo("* Errors: " + str(cleaner.cleanup_data["error_count"]))

    if se:
        try:
            last_cleanup = filemanager.unpickle_data("last-cleanup")

            click.echo("Errors encountered during the last deletion [" + last_cleanup["datetime"] + "]:")
            click.echo("Total: " + str(last_cleanup["error_count"]) + "\n")
            click.echo_via_pager("\n\n".join("* %s" % error
                                             for error in last_cleanup["errors"]))
        except FileNotFoundError:
            click.echo("No error data was found.")
Пример #15
0
    def execute_command(self, text, query):
        logger = self.logger

        try:
            output, query = self._evaluate_command(text)
        except KeyboardInterrupt:
            # Restart connection to the database
            self.pgexecute.connect()
            logger.debug("cancelled query, sql: %r", text)
            click.secho("cancelled query", err=True, fg='red')
        except NotImplementedError:
            click.secho('Not Yet Implemented.', fg="yellow")
        except OperationalError as e:
            logger.error("sql: %r, error: %r", text, e)
            logger.error("traceback: %r", traceback.format_exc())
            self._handle_server_closed_connection()
        except Exception as e:
            logger.error("sql: %r, error: %r", text, e)
            logger.error("traceback: %r", traceback.format_exc())
            click.secho(str(e), err=True, fg='red')
        else:
            try:
                if self.output_file and not text.startswith(('\\o ', '\\? ')):
                    try:
                        with open(self.output_file, 'a', encoding='utf-8') as f:
                            click.echo(text, file=f)
                            click.echo('\n'.join(output), file=f)
                            click.echo('', file=f)  # extra newline
                    except IOError as e:
                        click.secho(str(e), err=True, fg='red')
                else:
                    click.echo_via_pager('\n'.join(output))
            except KeyboardInterrupt:
                pass

            if self.pgspecial.timing_enabled:
                # Only add humanized time display if > 1 second
                if query.total_time > 1:
                    print('Time: %0.03fs (%s)' % (query.total_time,
                          humanize.time.naturaldelta(query.total_time)))
                else:
                    print('Time: %0.03fs' % query.total_time)

            # Check if we need to update completions, in order of most
            # to least drastic changes
            if query.db_changed:
                with self._completer_lock:
                    self.completer.reset_completions()
                self.refresh_completions(persist_priorities='keywords')
            elif query.meta_changed:
                self.refresh_completions(persist_priorities='all')
            elif query.path_changed:
                logger.debug('Refreshing search path')
                with self._completer_lock:
                    self.completer.set_search_path(
                        self.pgexecute.search_path())
                logger.debug('Search path: %r',
                             self.completer.search_path)
        return query
Пример #16
0
def project_list(obj, grouped):
    """List all your projects"""
    api_response = obj.get_projects()
    header = ('Slug', 'Name', 'Organisation')

    # get all users + organisations
    groups = {
        'users': {
            account['id']: {'name': 'Personal', 'projects': []}
            for account in api_response['accounts']
            if account['type'] == 'user'
        },
        'organisations': {
            account['id']: {'name': account['name'], 'projects': []}
            for account in api_response['accounts']
            if account['type'] == 'organisation'
        }
    }

    # sort websites into groups
    for website in api_response['websites']:
        organisation_id = website['organisation_id']
        if organisation_id:
            owner = groups['organisations'][website['organisation_id']]
        else:
            owner = groups['users'][website['owner_id']]
        owner['projects'].append((website['domain'], website['name']))

    accounts = itertools.chain(
        groups['users'].items(),
        groups['organisations'].items()
    )

    def sort_projects(items):
        return sorted(items, key=lambda x: x[0].lower())

    # print via pager
    if grouped:
        output_items = []
        for group, data in accounts:
            projects = data['projects']
            if projects:
                output_items.append(
                    u'{title}\n{line}\n\n{table}\n\n'.format(
                        title=data['name'],
                        line='=' * len(data['name']),
                        table=table(sort_projects(projects), header[:2])
                    )
                )
        output = os.linesep.join(output_items).rstrip(os.linesep)
    else:
        # add account name to all projects
        projects = [
            each + (data['name'],) for group, data in accounts
            for each in data['projects']
        ]
        output = table(sort_projects(projects), header)

    click.echo_via_pager(output)
Пример #17
0
def main(number):
    url = RFC_URL.format(number)
    response = fetch_url(url)

    try:
        click.echo_via_pager(response)
    except BrokenPipeError:
        pass
Пример #18
0
def cli(mcf, schema, schema_local, output):
    if mcf is None or (schema is None and schema_local is None):
        raise click.UsageError("Missing arguments")
    else:
        content = render_template(mcf, schema=schema, schema_local=schema_local)
        if output is None:
            click.echo_via_pager(content)
        else:
            output.write(content)
Пример #19
0
def cli(sort):
    """ Lists all available problems. """

    problems = sorted(data.problems, key=lambda problem: problem[sort.lower()])
    problem_list = ((problem['id'], problem['name'],
                     '%d%%' % problem['difficulty']) for problem in problems)

    table = tabulate(problem_list, TABLE_HEADERS, tablefmt='fancy_grid')
    click.echo_via_pager(table)
Пример #20
0
def stats(pod_path, full):
    """Displays statistics about the pod."""
    root = os.path.abspath(os.path.join(os.getcwd(), pod_path))
    pod = pods.Pod(root, storage=storage.FileStorage)
    try:
        stats = stats_lib.Stats(pod, full=full)
        click.echo_via_pager("\n\n".join(stats.to_tables()))
    except pods.Error as e:
        raise click.ClickException(str(e))
Пример #21
0
def cli_list():
    """List all the tags."""

    resp = []

    for tag in tag_list():
        resp.append('{name} ({count})'.format(**tag))

    click.echo_via_pager('\n'.join(resp))
Пример #22
0
def run_command(command, pager=False):
    if pager is True:
        click.echo(click.style("Command: ", fg='cyan') + click.style(command, fg='green'))
        p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
        click.echo_via_pager(p.stdout.read())
    else:
        click.echo(click.style("Command: ", fg='cyan') + click.style(command, fg='green'))
        p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
        click.echo(p.stdout.read())
Пример #23
0
def dump_container(container):
    """Dump container info."""
    container.ship = None
    container.shipment = None
    for volume in container.volumes.values():
        if hasattr(volume, 'files'):
            for file in volume.files.values():
                if hasattr(file, 'context'):
                    file.context = 'skipped'
    click.echo_via_pager(yaml.dump(container))
Пример #24
0
def migrate(mcf, output):
    if mcf is None:
        raise click.UsageError('Missing arguments')
    else:
        content = configparser2yaml(mcf).decode('utf-8')

        if output is None:
            click.echo_via_pager(content)
        else:
            output.write(content)
Пример #25
0
def show(repository):
    if not repository:
        repos = Repository.list_repos()
        str_repos = '\n'.join(sorted(repos))
        click.echo(str_repos)
    else:
        repo = Repository(repository)
        content = yaml.safe_dump(dict(repo.get_contents()),
                                 default_flow_style=False)
        click.echo_via_pager(content)
Пример #26
0
def list_containers(ctx):
    """List all Cloud Files containers for your specified region. If not in
    interactive mode, these are printed to stdout; interactive mode will
    paginate the output for you. """
    conn = auth.conn(ctx)
    if ctx.interactive:
        click.echo_via_pager("\n".join("Container: %s" % c.name for c in conn.object_store.containers()))
    else:
        for container in conn.object_store.containers():
            click.echo(container.name)
Пример #27
0
def list_objects(ctx, containername):
    """List all Cloud Files objects in the specified container. If not in
    interactive mode, these are printed to stdout; interactive mode will
    paginate the output for you. """
    conn = auth.conn(ctx)
    if ctx.interactive:
        click.echo_via_pager("\n".join("Container: %s" % c.name for c in conn.object_store.objects(containername)))
    else:
        for object in conn.object_store.objects(containername):
            click.echo(object.name)
Пример #28
0
def print_home_timeline(tweets,pager):
  """Print the home timeline of the user."""
  s=""
  for i,tweet in enumerate(tweets):  
    s += ((click.style('[%d] ' %(i+1), bold=True, fg="blue") + 
           click.style('@%s - ' %tweet.author.screen_name, bold=True, fg="cyan") + 
           click.style('%s' %tweet.text)).encode('utf_8')+'\n\n')
  if pager:
    click.echo_via_pager(s)
  else:
    click.echo(s)
Пример #29
0
def inspect_stats(pod_path, full):
    """Displays statistics about the pod."""
    root = os.path.abspath(os.path.join(os.getcwd(), pod_path))
    pod = pods.Pod(root, storage=storage.FileStorage)
    try:
        with pod.profile.timer('grow_inspect_stats'):
            pod_stats = stats_lib.Stats(pod, full=full)
            click.echo_via_pager('\n\n'.join(pod_stats.to_tables()))
    except pods.Error as err:
        raise click.ClickException(str(err))
    return pod
Пример #30
0
def pager(__text: str, pager: Optional[bool] = False):
    """Pass output through pager.

    Args:
        __text: Text to page
        pager: Pager to use
    """
    if pager:
        click.echo_via_pager(__text)
    else:
        click.echo(__text)