예제 #1
0
def to_html_table(rows, caption="", classes=[]):
    """Convert the given rows into an HTML table.

    The first entry in `rows` will be used as the table headers.
    """
    headers = rows.pop(0)

    above = "<table{0}>".format(
        ' class="{0}"'.format(" ".join(classes) if classes else ""))
    if caption:
        above += "\n<caption>{0}</caption>\n".format(caption)

    return tabulate.tabulate(
        rows,
        headers,
        stralign=None,
        numalign=None,
        tablefmt=tabulate.TableFormat(
            lineabove=tabulate.Line(above, "", "", ""),
            linebelowheader="",
            linebetweenrows=None,
            linebelow=tabulate.Line("</tbody>\n</table>", "", "", ""),
            headerrow=partial(_html_row_with_attrs, "th"),
            datarow=partial(_html_row_with_attrs, "td"),
            padding=0,
            with_header_hide=None,
        ),
    )
예제 #2
0
    def get_table_formatter(self, table_type):
        """Get a `tabulate` table formatter.

        :param str table_type: Table type of either "detailed" (second
            level of output verbosity), or "summary" (first level of
            output verbosity).

        :return: A table formatter for printing desired output.
        :rtype: tabulate.TableFormat
        """
        assert table_type in (
            "detailed",
            "summary",
        ), "'{}' is not a supported table type".format(table_type)
        line_formatter = functools.partial(
            self._interrogate_line_formatter, table_type=table_type
        )
        return tabulate.TableFormat(
            lineabove=None,
            linebelowheader=None,
            linebetweenrows=None,
            linebelow=None,
            headerrow=line_formatter,
            datarow=line_formatter,
            padding=1,
            with_header_hide=None,
        )
예제 #3
0
def _addCustomTabulateTables():
    """Create a custom ARMI tables within tabulate."""
    tabulate._table_formats["armi"] = tabulate.TableFormat(
        lineabove=tabulate.Line("", "-", "  ", ""),
        linebelowheader=tabulate.Line("", "-", "  ", ""),
        linebetweenrows=None,
        linebelow=tabulate.Line("", "-", "  ", ""),
        headerrow=tabulate.DataRow("", "  ", ""),
        datarow=tabulate.DataRow("", "  ", ""),
        padding=0,
        with_header_hide=None,
    )
    tabulate.tabulate_formats = list(sorted(tabulate._table_formats.keys()))
    tabulate.multiline_formats["armi"] = "armi"
예제 #4
0
파일: debug.py 프로젝트: astroparam/pytype
def _setup_tabulate():
  """Customise tabulate."""
  tabulate.PRESERVE_WHITESPACE = True
  tabulate.MIN_PADDING = 0
  # Overwrite the 'presto' format to use the block-drawing vertical line.
  # pytype: disable=module-attr
  tabulate._table_formats["presto"] = tabulate.TableFormat(  # pylint: disable=protected-access
      lineabove=None,
      linebelowheader=tabulate.Line("", "-", "+", ""),
      linebetweenrows=None,
      linebelow=None,
      headerrow=tabulate.DataRow("", "│", ""),
      datarow=tabulate.DataRow("", "│", ""),
      padding=1, with_header_hide=None)
예제 #5
0
    def style_output(data,
                     headers,
                     style=None,
                     table_separator_token='Token.Output.TableSeparator',
                     **_):
        """Style the *table* a(e.g. bold, italic, and colors)

        .. NOTE::
            This requires the `Pygments <http://pygments.org/>`_ library to
            be installed. You can install it with CLI Helpers as an extra::
                $ pip install cli_helpers[styles]

        Example usage::

            from cli_helpers.tabular_output import tabulate_adapter
            from pygments.style import Style
            from pygments.token import Token

            class YourStyle(Style):
                default_style = ""
                styles = {
                    Token.Output.TableSeparator: '#ansigray'
                }

            headers = ('First Name', 'Last Name')
            data = [['Fred', 'Roberts'], ['George', 'Smith']]
            style_output_table = tabulate_adapter.style_output_table('psql')
            style_output_table(data, headers, style=CliStyle)

            data, headers = style_output(data, headers, style=YourStyle)
            output = tabulate_adapter.adapter(data, headers, style=YourStyle)

        :param iterable data: An :term:`iterable` (e.g. list) of rows.
        :param iterable headers: The column headers.
        :param str/pygments.style.Style style: A Pygments style. You can `create
        your own styles <https://pygments.org/docs/styles#creating-own-styles>`_.
        :param str table_separator_token: The token type to be used for the table separator.
        :return: data and headers.
        :rtype: tuple

        """
        if style and HAS_PYGMENTS and format_name in supported_table_formats:
            formatter = Terminal256Formatter(style=style)

            def style_field(token, field):
                """Get the styled text for a *field* using *token* type."""
                s = StringIO()
                formatter.format(((token, field), ), s)
                return s.getvalue()

            def addColorInElt(elt):
                if not elt:
                    return elt
                if elt.__class__ == tabulate.Line:
                    return tabulate.Line(
                        *(style_field(table_separator_token, val)
                          for val in elt))
                if elt.__class__ == tabulate.DataRow:
                    return tabulate.DataRow(
                        *(style_field(table_separator_token, val)
                          for val in elt))
                return elt

            srcfmt = tabulate._table_formats[format_name]
            newfmt = tabulate.TableFormat(*(addColorInElt(val)
                                            for val in srcfmt))
            tabulate._table_formats[format_name] = newfmt

        return iter(data), headers
예제 #6
0
from cli_helpers.utils import filter_dict_by_key
from cli_helpers.compat import (Terminal256Formatter, StringIO)
from .preprocessors import (convert_to_string, truncate_string,
                            override_missing_value, style_output, HAS_PYGMENTS,
                            escape_newlines)

import tabulate

tabulate.MIN_PADDING = 0

tabulate._table_formats['psql_unicode'] = tabulate.TableFormat(
    lineabove=tabulate.Line("┌", "─", "┬", "┐"),
    linebelowheader=tabulate.Line("├", "─", "┼", "┤"),
    linebetweenrows=None,
    linebelow=tabulate.Line("└", "─", "┴", "┘"),
    headerrow=tabulate.DataRow("│", "│", "│"),
    datarow=tabulate.DataRow("│", "│", "│"),
    padding=1,
    with_header_hide=None,
)

tabulate._table_formats['double'] = tabulate.TableFormat(
    lineabove=tabulate.Line("╔", "═", "╦", "╗"),
    linebelowheader=tabulate.Line("╠", "═", "╬", "╣"),
    linebetweenrows=None,
    linebelow=tabulate.Line("╚", "═", "╩", "╝"),
    headerrow=tabulate.DataRow("║", "║", "║"),
    datarow=tabulate.DataRow("║", "║", "║"),
    padding=1,
    with_header_hide=None,
)
            e['head'].lower(), e['span'].lower(),
            ','.join([x['span'].lower() for x in e['modifiers']])
        ] for e in graph['entities']]
        _print(
            tabulate.tabulate(entities_data,
                              headers=['Head', 'Span', 'Modifiers'],
                              tablefmt=_tabulate_format))

    if show_relations:
        _print('Relations:')

        entities = graph['entities']
        relations_data = [[
            entities[rel['subject']]['head'].lower(), rel['relation'].lower(),
            entities[rel['object']]['head'].lower()
        ] for rel in graph['relations']]
        _print(
            tabulate.tabulate(relations_data,
                              headers=['Subject', 'Relation', 'Object'],
                              tablefmt=_tabulate_format))


_tabulate_format = tabulate.TableFormat(
    lineabove=tabulate.Line("+", "-", "+", "+"),
    linebelowheader=tabulate.Line("|", "-", "+", "|"),
    linebetweenrows=None,
    linebelow=tabulate.Line("+", "-", "+", "+"),
    headerrow=tabulate.DataRow("|", "|", "|"),
    datarow=tabulate.DataRow("|", "|", "|"),
    padding=1,
    with_header_hide=None)
예제 #8
0
import fileinput
import tabulate as TAB

from argparse import ArgumentParser, Action
from functools import partial

#########################
# Customize LaTeX table #
#########################

# Disable LaTeX character escaping
TAB._table_formats["latex_booktabs_raw"] = TAB.TableFormat(
    lineabove=partial(TAB._latex_line_begin_tabular, booktabs=True),
    linebelowheader=TAB.Line("\\midrule", "", "", ""),
    linebetweenrows=None,
    linebelow=TAB.Line("\\bottomrule\n\\end{tabular}", "", "", ""),
    headerrow=partial(TAB._latex_row, escrules={}),
    datarow=partial(TAB._latex_row, escrules={}),
    padding=1,
    with_header_hide=None,
)

################################
# Command line argument parser #
################################


class ColAlignmentAct(Action):
    def __call__(self, parser, namespace, value, option_string=None):
        if ',' not in value:
            setattr(namespace, self.dest, [value])
        else:
예제 #9
0
import re
import time

import tabulate
from six.moves.configparser import ConfigParser

from biggraphite.cli import command

# Hack to add some more formats.
# TODO: Add Graphite support.
# TODO: Remove padding.
tabulate._table_formats["csv"] = tabulate.TableFormat(
    lineabove=None,
    linebelowheader=None,
    linebetweenrows=None,
    linebelow=None,
    headerrow=tabulate.DataRow("", ";", ""),
    datarow=tabulate.DataRow("", ";", ""),
    padding=0,
    with_header_hide=None,
)

tabulate.tabulate_formats = list(sorted(tabulate._table_formats.keys()))


class Namespaces(object):
    r"""Helper for namespaces.

    The config file would look like:
    ```
    [carbon-relay]
    pattern = carbon\.relay\.*
예제 #10
0
파일: utils.py 프로젝트: iloleg/interrogate
    final_row_width += len(padded_cells) * padding_per_cell
    remaining_padding = max(0, TERMINAL_WIDTH - final_row_width)
    cell_to_put_extra_padding_into = 0

    to_join = []
    for index, (cell, alignment) in enumerate(zip(padded_cells, colaligns)):
        cell_padding = padding_per_cell
        if index == cell_to_put_extra_padding_into:
            cell_padding += remaining_padding
        if alignment == "right":
            to_append = (padder * cell_padding) + cell
        else:  # default to left
            to_append = cell + (padder * cell_padding)

        to_join.append(to_append)

    ret = sep + sep.join(to_join) + sep
    return ret.rstrip()


InterrogateTableFormat = tabulate.TableFormat(
    lineabove=None,
    linebelowheader=None,
    linebetweenrows=None,
    linebelow=None,
    headerrow=interrogate_line_formatter,
    datarow=interrogate_line_formatter,
    padding=1,
    with_header_hide=None,
)
예제 #11
0
파일: cli.py 프로젝트: thorkellhelga/voting
"""
import click
import tabulate

import voting
import simulate as sim
import util
import web

### Monkey patching CSV output mode into tabulate:
tabulate.tabulate_formats.append("csv")
tabulate._table_formats["csv"] = tabulate.TableFormat(
    lineabove=None,
    linebelowheader=None,
    linebetweenrows=None,
    linebelow=None,
    headerrow=tabulate.DataRow(begin=u'', sep=u',', end=u''),
    datarow=tabulate.DataRow(begin=u'', sep=u',', end=u''),
    padding=0,
    with_header_hide=None)


@click.group()
@click.option('--debug/--no-debug', default=False)
def cli(debug):
    """Basic CLI."""
    if debug:
        click.echo('Debug mode is on')


@cli.command()
     table_attributes=
     "id=\"info-table\" class=\"table table-condensed table-bordered table-hover\""
 )
 metadata_table = json2html.convert(
     json=vars(args),
     table_attributes=
     "id=\"info-table\" class=\"table table-condensed table-bordered table-hover\""
 )
 MyHTMLFormat = tabulate.TableFormat(lineabove=tabulate.Line(
     "<table class=\"table table-condensed table-bordered table-hover\">",
     "", "", ""),
                                     linebelowheader=None,
                                     linebetweenrows=None,
                                     linebelow=tabulate.Line(
                                         "</table>", "", "", ""),
                                     headerrow=partial(
                                         gophercannon_lib.
                                         my_html_row_with_attrs, "th"),
                                     datarow=partial(
                                         gophercannon_lib.
                                         my_html_row_with_attrs, "td"),
                                     padding=0,
                                     with_header_hide=None)
 transient_table = tabulate.tabulate(message_table, [
     "Parameter", "TX Count", "Min Delay (us)", "Max Delay(us)",
     "Avg. Delay(us)"
 ],
                                     tablefmt=MyHTMLFormat)
 image_file = "{0}_transient_graph.png".format(pretty_name)
 filename = 'report_TEMPLATE.html.jinja2'
 with open(os.path.join('templates', filename)) as file_:
예제 #13
0
import enum
import json
from typing import Any, Dict, Union

import click
import kfp_server_api
import tabulate

KFP_TABLE_FORMAT = 'custom-simple'

tabulate._table_formats.update({  # type: ignore
    KFP_TABLE_FORMAT:
    tabulate.TableFormat(lineabove=None,
                         linebelowheader=None,
                         linebetweenrows=None,
                         linebelow=None,
                         headerrow=tabulate.DataRow('', '  ', ''),
                         datarow=tabulate.DataRow('', '  ', ''),
                         padding=0,
                         with_header_hide=['lineabove', 'linebelow'])
})


@enum.unique
class OutputFormat(enum.Enum):
    """Enumerated class with the allowed output format constants."""
    table = 'table'
    json = 'json'


RUN_STORAGE_STATE_MAP = {
    kfp_server_api.ApiRunStorageState.AVAILABLE: 'Available',