Ejemplo n.º 1
0
def print_table(elements, title=None, filename=None):
    # type: (list, str, str) -> None
    if len(elements) > 0:
        if 'version' in elements[0].keys():
            table_data = [['Name', 'Version']]
            table = AsciiTable(table_data)
            table.padding_left = 1
            table.padding_right = 1
            max_width = 80
            if title is not None:
                table.title = title
            for element in elements:
                table_data.append([
                    element['name'],
                    '\n'.join(wrap(element['version'], max_width))
                ])
            print(table.table)
            if isinstance(filename, list):
                filename = filename[0]
            if filename is not None:
                try:
                    with open(filename, 'w') as fp:
                        fp.write(table.table)
                except IOError as e:
                    print_line(
                        "Exception {0} occured while write file {1}.".format(
                            e, filename))
        elif 'description' in elements[0].keys():
            table_data = [['Name', 'Description']]
            table = AsciiTable(table_data)
            table.padding_left = 1
            table.padding_right = 1
            max_width = 80  # table.column_max_width(1)
            if title is not None:
                table.title = title
            for element in elements:
                table_data.append([
                    element['name'],
                    '\n'.join(wrap(element['description'], max_width))
                ])
            print(table.table)
            if isinstance(filename, list):
                filename = filename[0]
            if filename is not None:
                try:
                    with open(filename, 'w') as fp:
                        fp.write(table.table)
                except IOError as e:
                    print_line(
                        "Exception occured while write file {0}.".format(
                            filename))
Ejemplo n.º 2
0
def test_attributes():
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
    ]
    table = AsciiTable(table_data)

    assert 31 == max(len(r) for r in table.table.splitlines())
    assert 31 == table.table_width

    table.outer_border = False
    assert 29 == max(len(r) for r in table.table.splitlines())
    assert 29 == table.table_width

    table.inner_column_border = False
    assert 27 == max(len(r) for r in table.table.splitlines())
    assert 27 == table.table_width

    table.padding_left = 0
    assert 24 == max(len(r) for r in table.table.splitlines())
    assert 24 == table.table_width

    table.padding_right = 0
    assert 21 == max(len(r) for r in table.table.splitlines())
    assert 21 == table.table_width
Ejemplo n.º 3
0
def test_attributes():
    """Test with different attributes."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
    ]
    table = AsciiTable(table_data)

    assert 31 == max(len(r) for r in table.table.splitlines())
    assert 31 == table.table_width

    table.outer_border = False
    assert 29 == max(len(r) for r in table.table.splitlines())
    assert 29 == table.table_width

    table.inner_column_border = False
    assert 27 == max(len(r) for r in table.table.splitlines())
    assert 27 == table.table_width

    table.padding_left = 0
    assert 24 == max(len(r) for r in table.table.splitlines())
    assert 24 == table.table_width

    table.padding_right = 0
    assert 21 == max(len(r) for r in table.table.splitlines())
    assert 21 == table.table_width
Ejemplo n.º 4
0
def render_basic(data, title=None):
    table = AsciiTable(data, title=title)
    table.inner_row_border = True
    table.inner_footing_row_border = True
    table.padding_left = 5
    table.padding_right = 5
    print(table.table)
    print("\n")
Ejemplo n.º 5
0
def print_table(data):
    table = AsciiTable(data)
    table.outer_border = False
    table.inner_column_border = False
    table.padding_left = 0
    table.padding_right = 2

    output = table.table
    print
    print
    print output
    print output.split('\n')[1]
Ejemplo n.º 6
0
 def search(self,
            criteria: str = '',
            limit: int = 10,
            format: str = 'table'):
     total_in_db = self.session.query(BooksTable.uid).count()
     r = self.session.query(BooksTable.title, BooksTable.date_published, BooksTable.pages, BooksTable.url, BooksTable.isbn13)\
             .filter(BooksTable.title.like(criteria))\
             .order_by(desc(BooksTable.date_published))\
             .limit(limit)
     data = []
     # print(self.__default__orm)
     header = [
         colored('Date', "cyan", attrs=['bold']),
         colored('Pages', "cyan", attrs=['bold']),
         colored('ISBN13', "cyan", attrs=['bold']),
         colored('Title', "cyan", attrs=['bold']),
         colored('Url', "cyan", attrs=['bold'])
     ]
     for book in r:
         data.append([
             str(book.date_published), book.pages, book.isbn13,
             textwrap.fill(book.title, 90),
             textwrap.fill(book.url, 100)
         ])
     if format == 'table':
         if len(data) == 0:
             tt.print([[f"No results for: {criteria}"]],
                      style=tt.styles.ascii_thin)
         else:
             h = [header]
             h.extend(data)
             title = "---| " + colored("Results for:", "yellow") + colored(f" {criteria} ", "green") + \
                     ", Total DB: " + colored(number_format(total_in_db), "green") + \
                     ", ORM: " + \
                 colored(self.__default__orm, "green") + " |"
             t = AsciiTable(h, title=title)
             t.inner_row_border = True
             t.CHAR_OUTER_TOP_LEFT = "╭"
             t.CHAR_OUTER_BOTTOM_LEFT = "╰"
             t.CHAR_OUTER_BOTTOM_RIGHT = "╯"
             t.CHAR_OUTER_TOP_RIGHT = "╮"
             t.padding_left = 2
             t.justify_columns = {0: 'left', 1: 'left', 2: 'left'}
             print("\n")
             print(t.table)
             #tt.print(data, header=header, padding=(0, 1), style=tt.styles.ascii_thin, alignment='lll')
     elif format == 'json':
         print(json.dumps(data))
     return data
Ejemplo n.º 7
0
Archivo: table.py Proyecto: pcn/cogctl
def render(table_data):
    """
    Render the given data as an ASCII table. Table data
    is provided as a list-of-lists. Column names are provided as a
    list of strings.

    Returns the string.
    """

    table = AsciiTable(table_data)
    table.inner_column_border = False
    table.outer_border = False
    table.inner_heading_row_border = False
    table.padding_left = 0
    table.padding_right = 2
    output = table.table
    return "\n".join([line.strip() for line in output.split("\n")])
Ejemplo n.º 8
0
    def get_grid(self, astype='table'):
        r"""
        """
        from pandas import DataFrame as df

        geoms = self.geometries().keys()
        phases = [
            p.name for p in self.phases().values()
            if not hasattr(p, 'mixture')
        ]
        grid = df(index=geoms, columns=phases)
        for r in grid.index:
            for c in grid.columns:
                phys = self.find_physics(phase=self[c], geometry=self[r])
                if phys is not None:
                    grid.loc[r][c] = phys.name
                else:
                    grid.loc[r][c] = '---'
        if astype == 'pandas':
            pass
        elif astype == 'dict':
            grid = grid.to_dict()
        elif astype == 'table':
            from terminaltables import AsciiTable
            headings = [self.network.name] + list(grid.keys())
            g = [headings]
            for row in list(grid.index):
                g.append([row] + list(grid.loc[row]))
            grid = AsciiTable(g)
            grid.title = 'Project: ' + self.name
            grid.padding_left = 3
            grid.padding_right = 3
            grid.justify_columns = {
                col: 'center'
                for col in range(len(headings))
            }
        elif astype == 'grid':
            grid = ProjectGrid()
        return grid
Ejemplo n.º 9
0
def print_table(elements, title=None, filename=None):
    # type: (list, str, str) -> None
    """
    Print information as ASCII Table.
    :param elements: list of printing elements
                     {'name': element_name, 'version': element_version}
                     or
                     {'name': element_name, 'description': element_description}
    :param title: title of Table
    :param filename: path to text file export
    :return: None
    """

    # If list of printing elements is not empty

    if len(elements) > 0:
        # For elements with 'version' field
        if 'version' in elements[0].keys():
            table_data = [['Name', 'Version']]

            table = AsciiTable(table_data)
            table.padding_left = 1
            table.padding_right = 1

            max_width = 80

            if title is not None:
                table.title = title

            for element in elements:
                table_data.append([
                    element['name'],
                    '\n'.join(wrap(element['version'], max_width))
                ])

            print(table.table)

            if isinstance(filename, list):
                filename = filename[0]

            if filename is not None:
                try:
                    with open(filename, 'w') as fp:
                        fp.write(table.table)

                except IOError as ioerror_exception:
                    print_line(
                        "Exception {0} occured while write file {1}.".format(
                            ioerror_exception, filename))

        # For elements with 'description' field
        elif 'description' in elements[0].keys():
            table_data = [['Name', 'Description']]

            table = AsciiTable(table_data)
            table.padding_left = 1
            table.padding_right = 1

            max_width = 80

            if title is not None:
                table.title = title

            for element in elements:
                table_data.append([
                    element['name'],
                    '\n'.join(wrap(element['description'], max_width))
                ])

            print(table.table)

            if isinstance(filename, list):
                filename = filename[0]

            if filename is not None:
                try:
                    with open(filename, 'w') as fp:
                        fp.write(table.table)

                except IOError as ioerror_exception:
                    print_line(
                        "Exception {0} occured while write file {1}.".format(
                            ioerror_exception, filename))
Ejemplo n.º 10
0
        secrets = client.service.SearchSecrets(token=token,
                                               searchTerm="aws",
                                               includeDeleted=False,
                                               includeRestricted=False)

        EPS_USER_SECRET_DATA = [["Secret", "ID", "Secret Type Name"]]

        for secret in secrets.SecretSummaries.SecretSummary:

            EPS_USER_SECRET_DATA.append([
                colored(secret.SecretName, "green"), secret.SecretId,
                secret.SecretTypeName
            ])

        EPS_FORMATTED_USER_SECRET = AsciiTable(table_data=EPS_USER_SECRET_DATA)
        EPS_FORMATTED_USER_SECRET.padding_left = 4
        EPS_FORMATTED_USER_SECRET.padding_right = 4
        EPS_FORMATTED_USER_SECRET.inner_row_border = True

        print(colored("\n[SECRETS]\n", "yellow"))
        print("\n".join([
            "User: %s" % identity.DisplayName,
            "Domain: %s" % identity.DomainName
        ]))
        print("\n" + EPS_FORMATTED_USER_SECRET.table + "\n")
        print(colored("[DETAILS]\n", "yellow"))

        while True:

            try:
                user_secret_id = input(
Ejemplo n.º 11
0
def print_summary(row_data):
    table = AsciiTable([row_data])
    table.outer_border = False
    table.padding_left = 10
    table.padding_right = 2
    print(table.table)
Ejemplo n.º 12
0
def format_key_values(key_values: KeyValuesType,
                      title: Optional[str] = None,
                      formatter: Callable[[Any], str] = str,
                      delimiter_char: str = '=') -> str:
    """
    Format key value sequence into str.

    The basic usage, to format a :class:`Config`, a dict or a list of tuples:

    >>> print(format_key_values(Config(a=123, b=Config(value=456))))
    a         123
    b.value   456
    >>> print(format_key_values({'a': 123, 'b': {'value': 456}}))
    a   123
    b   {'value': 456}
    >>> print(format_key_values([('a', 123), ('b', {'value': 456})]))
    a   123
    b   {'value': 456}

    To add a title and a delimiter:

    >>> print(format_key_values(Config(a=123, b=Config(value=456)),
    ...                         title='short title'))
    short title
    =============
    a         123
    b.value   456
    >>> print(format_key_values({'a': 123, 'b': {'value': 456}},
    ...                         title='long long long title'))
    long long long title
    ====================
    a   123
    b   {'value': 456}

    Args:
        key_values: The sequence of key values, may be a :class:`Config`,
            a dict, or a list of (key, value) pairs.
            If it is a :class:`Config`, it will be flatten via
            :meth:`Config.to_flatten_dict()`.
        title: If specified, will prepend a title and a horizontal delimiter
            to the front of returned string.
        formatter: The function to format values.
        delimiter_char: The character to use for the delimiter between title
            and config key values.

    Returns:
        The formatted str.
    """
    if len(delimiter_char) != 1:
        raise ValueError(f'`delimiter_char` must be one character: '
                         f'got {delimiter_char!r}')

    if isinstance(key_values, Config):
        key_values = config_to_dict(key_values, flatten=True)

    if hasattr(key_values, 'items'):
        data = [(key, formatter(value)) for key, value in key_values.items()]
    else:
        data = [(key, formatter(value)) for key, value in key_values]

    # use the terminaltables.AsciiTable to format our key values
    table = AsciiTable(data)
    table.padding_left = 0
    table.padding_right = 3
    table.inner_column_border = False
    table.inner_footing_row_border = False
    table.inner_heading_row_border = False
    table.inner_row_border = False
    table.outer_border = False
    lines = [line.rstrip() for line in table.table.split('\n')]

    # prepend a title
    if title is not None:
        max_length = max(max(map(len, lines)), len(title))
        delim = delimiter_char * max_length
        lines = [title, delim] + lines

    return '\n'.join(lines)
Ejemplo n.º 13
0
import json
from terminaltables import AsciiTable

with open('movements.json') as json_file:
    movements = json.load(json_file)

    print(
        "--------------------------------------------------------------------------------"
    )
    for i in range(0, len(movements)):
        movement = movements[i]
        movement["numbers"].insert(0, [0, 1, 2, 3])
        print("key: ", movement["key"])
        print("random location: ", movement["random_location"])
        print("random number: ", movement["random_number"])
        table = AsciiTable(movement["numbers"])
        table.padding_left = 4
        table.padding_right = 4
        print(table.table)
        print(
            "--------------------------------------------------------------------------------"
        )