コード例 #1
0
def stat_bar(cur):
    """ one-liner stat bar """
    # Block : All=X  Ours=Y Oth=Z   |  Allow : All=X Ours=Y Oth=Z
    data = []

    data.append("Blocks Enabled:  All=" +
                str(get(cur, "total_adlist_enabled")))
    data.append("│")
    data.append("Ours=" + str(get(cur, "our_adlist_enabled")))
    # data.append("│")
    # data.append("Other=" + str(get(cur, "other_adlist_enabled")))

    data.append("│")
    data.append("Allows Enabled:  All=" + str(get(cur, "total_allow_enabled")))
    data.append("│")
    data.append("Ours=" + str(get(cur, "our_allow_enabled")))
    # data.append("│")
    # data.append("Other=" + str(get(cur, "other_allow_enabled")))

    table = SingleTable([data])

    table.inner_heading_row_border = False
    table.outer_border = False
    table.inner_row_border = False
    table.inner_column_border = False
    table.padding_left = 2

    print()
    print(color(table.table, bg="#505050", fg="white"))
    print()
コード例 #2
0
def trace_table(exc, logger='default', note=True, column=5, mode='ascii', level='error', width=40):
    if isinstance(logger, str):
        logger = logging.getLogger(logger)
    tb = traceback.extract_tb(exc.__traceback__, limit=None)
    len_tb = len(tb)
    group_size = len_tb // column
    if len_tb % column != 0:
        group_size += 1
    if note:
        column -= 1
        if column <= 0:
            column = 1
    for index, tb_chunked in enumerate(grouper_it(tb, column)):
        if note:
            data = [
                ['file'], ['func'], ['desc']
            ]
        else:
            data = [[], [], []]

        for i, frame in enumerate(tb_chunked):
            current_filename = frame.filename
            if i == 0:
                last_filename = frame.filename
            else:
                if current_filename == last_filename:
                    current_filename = ''
                else:
                    last_filename = current_filename  # + ':' + frame.lineno
            if len(current_filename) == 0:
                data[0].append(str(frame.lineno))
            else:
                data[0].append('\n'.join(wrap(current_filename + ':' + str(frame.lineno), width)))
            data[1].append(frame.name)
            data[2].append('\n'.join(wrap(frame.line, width)))

        if mode == 'single':
            table = SingleTable(data, str(group_size) + '-' + str(index + 1))
        else:
            table = AsciiTable(data, str(group_size) + '-' + str(index + 1))

        table.outer_border = True
        table.inner_heading_row_border = True
        table.inner_column_border = True
        table.inner_row_border = True

        # max_width = table.column_max_width(1)
        # wrapped_string = '\n'.join(wrap(LONG_STRING, max_width))
        # table.table_data[0][1] = wrapped_string

        if level == 'critical':
            logger.critical('\n' + table.table)
        elif level == 'warning':
            logger.warning('\n' + table.table)
        elif level == 'info':
            logger.info('\n' + table.table)
        elif level == 'debug':
            logger.debug('\n' + table.table)
        else:
            logger.error('\n' + table.table)
コード例 #3
0
def terminaltables_(columns_,
                    data_,
                    header_='*',
                    align_right=[],
                    align_left=[],
                    footer_=False):
    # align_left is actually default, so it should not be needed for now
    if header_ is not None:
        header_ = "   ".join(header_)
        header_ = colored.stylize(header_, colored.fg('38'))
    data_ = (columns_, *data_)

    table_instance = SingleTable(data_, header_)
    # table_instance.inner_row_border = True
    # table_instance.outer_row_border = Falsaaae
    table_instance.outer_border = True
    # table_instance.inner_heading_row_border = False
    table_instance.inner_footing_row_border = footer_
    table_instance.inner_column_border = True
    # table_outer_borders = table_instance.table.splitlines()

    if align_right:
        for a in align_right:
            table_instance.justify_columns[a] = 'right'
    if align_left:
        for a in align_left:
            table_instance.justify_columns[a] = 'left'
    print(table_instance.table)
コード例 #4
0
def print_table(data: List[List[str]] = None,
                title: str = '',
                colored_header: bool = True,
                no_borders: bool = False):
    if data is None:
        return

    # Make header blue
    if colored_header:
        for x in range(len(data[0])):
            data[0][x] = print_utils.color(data[0][x], 'blue')

    table = SingleTable(data)
    table.title = title
    table.inner_row_border = True

    if no_borders:
        table.inner_row_border = False
        table.inner_column_border = False
        table.outer_border = False
        table.inner_footing_row_border = False
        table.inner_heading_row_border = False

    print('')
    print(table.table)
    print('')
    def get_description(self):
        root, _, scripts = self.walking_in_directory()
        scripts.sort()

        full_description = {}
        for s in scripts:
            with open(root + s) as text:
                head = [next(text) for l in range(2)]
                technique_name = head[0].replace('#TechniqueName: ', '').strip('\n')
                atomic_name = head[1].replace('#AtomicTestName:', '').strip('\n')

                if technique_name not in full_description:
                    full_description[technique_name] = [(atomic_name, s)]
                else:
                    full_description[technique_name].append((atomic_name, s))
        
        description_display = ''
        table_data = []
        for key, values in full_description.items():
            table_data.append([f'\n#{key}', ''])
            
            for ttp_variant in values:
                table_data.append([f'  {ttp_variant[0]}', ttp_variant[1]])
                self.ttp_list.append(ttp_variant[1])

        table = SingleTable(table_data, title='Atomics')
        table.inner_column_border = False
        table.inner_heading_row_border = False
        table.inner_row_border = False
        table.outer_border = False

        description_display += table.table

        return description_display 
コード例 #6
0
ファイル: command.py プロジェクト: tarunlalwani/a10ctl
def gettable(headers, data):
    from terminaltables import SingleTable

    table = SingleTable([headers] + data)
    table.inner_heading_row_border = False
    table.inner_column_border = False
    table.outer_border = False

    return table
コード例 #7
0
def print_table(title: str, header: List[str], rows: List[List[str]],
                overhead_col: int) -> None:
    table = SingleTable([header] + rows)
    for row in table.table_data:
        row[overhead_col] = fill(row[overhead_col],
                                 width=table.column_max_width(overhead_col))
    table.outer_border = False
    table.title = title
    print(table.table)
コード例 #8
0
ファイル: metrics.py プロジェクト: flixpar/larynx-semseg
def mean_metric_table(m, metrics):
    table = []
    for metric_name in metrics:
        table.append([metric_name, str(m[metric_name])])
    table = SingleTable(table, title="Metrics")
    table.inner_heading_row_border = False
    table.inner_column_border = True
    table.inner_row_border = False
    table.outer_border = True
    return table.table
コード例 #9
0
ファイル: metrics.py プロジェクト: flixpar/larynx-semseg
def cfm_table(m, normalized=True):
    if normalized: cfm = m["normalized_cfm"]
    else: cfm = m["cfm"]
    table = list(cfm)
    table = SingleTable(table, title="CFM")
    table.inner_heading_row_border = False
    table.inner_column_border = False
    table.inner_row_border = False
    table.outer_border = True
    return table.table
コード例 #10
0
def print_table(rows):
    table = SingleTable(rows)
    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
    table.padding_left = 0
    table.padding_right = 3

    print(table.table)
コード例 #11
0
ファイル: strings.py プロジェクト: whatever4711/Kathara
def formatted_strings():
    commands = []
    for item in strings.items():
        commands.append(list(item))

    commands_table = SingleTable(commands)
    commands_table.inner_heading_row_border = False
    commands_table.outer_border = False
    commands_table.inner_column_border = False

    return commands_table.table
コード例 #12
0
ファイル: metrics.py プロジェクト: flixpar/larynx-semseg
def perclass_metric_table(m, metrics, classes):
    table = []
    table.append(["metric"] + classes)
    for metric_name in metrics:
        table.append([metric_name] + [str(s) for s in m[metric_name]])
    table = SingleTable(table, title="Metrics")
    table.inner_heading_row_border = True
    table.inner_column_border = True
    table.inner_row_border = False
    table.outer_border = True
    return table.table
コード例 #13
0
ファイル: example2.py プロジェクト: Robpol86/terminaltables
def table_abcd():
    """Return table string to be printed. Two tables on one line."""
    table_instance = SingleTable([['A', 'B'], ['C', 'D']])

    # Get first table lines.
    table_instance.outer_border = False
    table_inner_borders = table_instance.table.splitlines()

    # Get second table lines.
    table_instance.outer_border = True
    table_instance.inner_heading_row_border = False
    table_instance.inner_column_border = False
    table_outer_borders = table_instance.table.splitlines()

    # Combine.
    smallest, largest = sorted([table_inner_borders, table_outer_borders], key=len)
    smallest += [''] * (len(largest) - len(smallest))  # Make both same size.
    combined = list()
    for i, row in enumerate(largest):
        combined.append(row.ljust(10) + '          ' + smallest[i])
    return '\n'.join(combined)
コード例 #14
0
ファイル: obj.py プロジェクト: tjhop/linode-cli
def _borderless_table(data):
    """
    Returns a terminaltables.SingleTable object with no borders and correct padding
    """
    tab = SingleTable(data)
    tab.inner_heading_row_border = False
    tab.inner_column_border = False
    tab.outer_border = False
    tab.padding_left = 0
    tab.padding_right = 2

    return tab
コード例 #15
0
def table_abcd():
    """Return table string to be printed. Two tables on one line."""
    table_instance = SingleTable([['A', 'B'], ['C', 'D']])

    # Get first table lines.
    table_instance.outer_border = False
    table_inner_borders = table_instance.table.splitlines()

    # Get second table lines.
    table_instance.outer_border = True
    table_instance.inner_heading_row_border = False
    table_instance.inner_column_border = False
    table_outer_borders = table_instance.table.splitlines()

    # Combine.
    smallest, largest = sorted([table_inner_borders, table_outer_borders],
                               key=len)
    smallest += [''] * (len(largest) - len(smallest))  # Make both same size.
    combined = list()
    for i, row in enumerate(largest):
        combined.append(row.ljust(10) + '          ' + smallest[i])
    return '\n'.join(combined)
コード例 #16
0
ファイル: metrics.py プロジェクト: flixpar/larynx-semseg
def mean_square_metric_table(m, metrics):
    if len(metrics) != 4:
        raise Exception("Invalid number of metrics for table.")
    s1 = "\033[1m" + metrics[0] + "\033[0m\n" + str(m[metrics[0]])
    s2 = "\033[1m" + metrics[1] + "\033[0m\n" + str(m[metrics[1]])
    s3 = "\033[1m" + metrics[2] + "\033[0m\n" + str(m[metrics[2]])
    s4 = "\033[1m" + metrics[3] + "\033[0m\n" + str(m[metrics[3]])
    table = [[s1, s2], [s3, s4]]
    table = SingleTable(table)
    table.inner_heading_row_border = False
    table.inner_column_border = True
    table.inner_row_border = True
    table.outer_border = True
    return table.table
コード例 #17
0
ファイル: table.py プロジェクト: pingf/logcc
def trace_table(exc, logger='default', column=4, mode='ascii', level='error'):
    if isinstance(logger, str):
        logger = logging.getLogger(logger)
    tb = traceback.extract_tb(exc.__traceback__, limit=None)
    len_tb = len(tb)
    group_size = len_tb // column
    if len_tb % column != 0:
        group_size += 1
    for index, tb_chunked in enumerate(grouper_it(tb, column)):
        data = [
            ['file'], ['func'], ['desc']
        ]

        for i, frame in enumerate(tb_chunked):
            current_filename = frame.filename
            if i == 0:
                last_filename = frame.filename
            else:
                if current_filename == last_filename:
                    current_filename = ''
                else:
                    last_filename = current_filename  # + ':' + frame.lineno
            if len(current_filename) == 0:
                data[0].append(str(frame.lineno))
            else:
                data[0].append(current_filename + ':' + str(frame.lineno))
            data[1].append(frame.name)
            data[2].append(frame.line)

        if mode == 'single':
            table = SingleTable(data, str(group_size) + '-' + str(index + 1))
        else:
            table = AsciiTable(data, str(group_size) + '-' + str(index + 1))

        table.outer_border = True
        table.inner_heading_row_border = True
        table.inner_column_border = True
        table.inner_row_border = True

        if level == 'critical':
            logger.critical('\n' + table.table)
        elif level == 'warning':
            logger.warning('\n' + table.table)
        elif level == 'info':
            logger.info('\n' + table.table)
        elif level == 'debug':
            logger.debug('\n' + table.table)
        else:
            logger.error('\n' + table.table)
コード例 #18
0
def main():
    td = [[' ', 'A', 'B', 'C'], ['1', 'X', ' ', 'O'], ['2', 'O', 'X', ' '],
          ['3', 'O', ' ', 'X']]

    t = SingleTable(td, 'GameBoard')
    t.outer_border = False
    t.inner_row_border = True
    t.inner_column_border = True

    print(t.table)

    b = Border(5, 5)
    b.draw()
    b.set('a1', 'x')
    b.set('d4', 'o')
    b.draw()
コード例 #19
0
def view(server: GroupsServer, group_id: Union[str, int]):
    group = server.view(group_id)

    data = [['Id', group['id']], ['Name', group['name']]]

    if 'environment' in group and len(group['environment']) > 0:
        e = SingleTable([[key, value]
                         for key, value in group['environment'].items()])
        e.inner_heading_row_border = False
        e.outer_border = False
        e.inner_column_border = False
        data.append(['Environment', e.table])

    table = SingleTable(data)
    table.inner_heading_row_border = False
    click.echo(table.table)
コード例 #20
0
def block_header(cur):
    """ block portion of header """

    block_data = [
        [
            "Total     :",
            get(cur, "total_adlist_enabled") + "/" + get(cur, "total_adlist"),
        ],
        [
            "Our Lists :",
            get(cur, "our_adlist_enabled") + "/" + get(cur, "our_adlist")
        ],
        [
            "Others    :",
            get(cur, "other_adlist_enabled") + "/" + get(cur, "other_adlist"),
        ],
    ]
    block_table = AsciiTable(block_data)

    block_table.inner_heading_row_border = False
    block_table.outer_border = False
    block_table.inner_row_border = False
    block_table.inner_column_border = False

    rows = adlist_top3_by_comment(cur)
    t3_block_data = []
    for row in rows:
        t3_block_data.append([row[0], row[1]])

    t3_block_table = AsciiTable(t3_block_data)

    t3_block_table.inner_heading_row_border = False
    t3_block_table.outer_border = False
    t3_block_table.inner_row_border = False
    t3_block_table.inner_column_border = False

    table_data = [
        ["Ad/Blocklist Stats", "Top 3 by Comment"],
        [block_table.table, t3_block_table.table],
        [],
    ]

    table = SingleTable(table_data)
    table.padding_left = 2
    table.outer_border = False

    utils.info(table.table)
コード例 #21
0
ファイル: utils.py プロジェクト: 2dotstwice/dlcli
def print_run_table(table_data):
    table = SingleTable(table_data)
    table.justify_columns = {0: 'left', 1: 'center', 2: 'left'}
    table.inner_heading_row_border = False
    table.inner_column_border = False
    table.outer_border = False
    max_width = table.column_max_width(2)
    for index, row in enumerate(table_data):
        table.table_data[index][2] = str(row[2][0:max_width].splitlines()[0])
        if row[1] == 0:
            table.table_data[index][1] = colored(str(row[1]), 'green')
        elif row[1] == 1:
            table.table_data[index][2] = colored(str(row[1]), 'yellow')
        elif row[1] == 3:
            table.table_data[index][2] = colored(str(row[1]), 'grey')
        else:
            table.table_data[index][2] = colored(str(row[1]), 'red')
    print table.table
コード例 #22
0
ファイル: metrics.py プロジェクト: flixpar/larynx-semseg
def perclass_square_metric_table(m, metrics, classes):
    if len(metrics) != 4:
        raise Exception("Invalid number of metrics for table.")
    s = ""
    for c, class_name in enumerate(classes):
        s1 = "\033[1m" + metrics[0] + "\033[0m\n" + str(m[metrics[0]][c])
        s2 = "\033[1m" + metrics[1] + "\033[0m\n" + str(m[metrics[1]][c])
        s3 = "\033[1m" + metrics[2] + "\033[0m\n" + str(m[metrics[2]][c])
        s4 = "\033[1m" + metrics[3] + "\033[0m\n" + str(m[metrics[3]][c])
        table = [[s1, s2], [s3, s4]]
        table = SingleTable(table, title=class_name)
        table.inner_heading_row_border = False
        table.inner_column_border = True
        table.inner_row_border = True
        table.outer_border = True
        s += table.table
        if c != len(classes) - 1: s += "\n"
    return s
コード例 #23
0
def print_run_table(table_data):
    table = SingleTable(table_data)
    table.justify_columns = {0: 'left', 1: 'center', 2: 'left'}
    table.inner_heading_row_border = False
    table.inner_column_border = False
    table.outer_border = False
    max_width = table.column_max_width(2)
    for index, row in enumerate(table_data):
        table.table_data[index][2] = str(row[2][0:max_width].splitlines()[0])
        if row[1] == 0:
            table.table_data[index][1] = colored(str(row[1]), 'green')
        elif row[1] == 1:
            table.table_data[index][2] = colored(str(row[1]), 'yellow')
        elif row[1] == 3:
            table.table_data[index][2] = colored(str(row[1]), 'grey')
        else:
            table.table_data[index][2] = colored(str(row[1]), 'red')
    print table.table
コード例 #24
0
def view(server: JobServer, job_id: Union[int, str]):
    current_job = server.view(job_id)

    data = [['Id', current_job['id']],
            ['Name/Description', current_job['name']],
            [
                'Alias',
                util.format_none(current_job['alias'] if 'alias' in
                                 current_job else '')
            ], ['Image:tag', f'{current_job["image"]}:{current_job["tag"]}'],
            ['Schedule', current_job['scheduleText']],
            ['Time Zone', current_job['timeZone']],
            ['Paused', current_job['paused']],
            ['Cron entry', current_job['schedule']],
            ['Cron Type', current_job['cronType']],
            ['EntryPoint',
             util.format_none(current_job['entryPoint'])],
            ['Groups', ','.join(current_job['groups'])],
            ['Created on', f"{current_job['createdOn']} (UTC)"],
            ['Last status',
             util.format_status(current_job['lastStatus'])],
            ['Updated on', f"{current_job['statusUpdateOn']} (UTC)"],
            [
                'Last run on',
                f"{current_job['lastRun']} ({current_job['timeZone']})"
            ],
            [
                'Next run on',
                f"{current_job['nextRun']} ({current_job['timeZone']})"
            ]]

    if 'environment' in current_job and len(current_job['environment']) > 0:
        e = SingleTable(
            [[key, value[:9] + ' ...' if len(value) > 14 else value]
             for key, value in current_job['environment'].items()])
        e.inner_heading_row_border = False
        e.outer_border = False
        e.inner_column_border = False
        data.append(['Environment', e.table])

    table = SingleTable(data)
    table.inner_heading_row_border = False
    click.echo(table.table)
コード例 #25
0
def list_deployments():
    def process_versions(versions: List[dict]) -> (str, str):
        active_version = "None"
        versions_string = ""

        for v in sorted(versions, key=lambda version: version["created_on"]):
            if v["active"]:
                active_version = v["version"]

            if versions_string:
                versions_string += ", "
            versions_string += v["version"]

        return (active_version, versions_string)

    deployments = STATE.api_call("deployments/")
    table_headers = ["Name", "URL", "Creation Date", "Active Version", "All Versions", "Categories"]
    table_data = map(
        lambda datum: [
            datum["name"],
            "{}://{}.{}/".format(
                STATE.conf["hosting_protocol"], datum["subdomain"], STATE.conf["hosting_base_url"]
            ),
            dateutil.parser.parse(datum["created_on"]).strftime("%Y-%m-%d"),
            *process_versions(datum["versions"]),
            ", ".join(
                filter(None, map(lambda category: category["category"], datum["categories"]))
            ),
        ],
        deployments,
    )

    table = SingleTable([table_headers, *table_data])
    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
    table.padding_left = 0
    table.padding_right = 3

    print(table.table)
コード例 #26
0
    def build_grid(self, rover_row, rover_col, rover_dir):
        grid = []
        for i in range(self.cols, 0, -1):
            row = [str(i)]
            for j in range(self.rows):
                row.append(self.arrows[rover_dir] if (
                    rover_row == j + 1 and rover_col == i) else "")
            grid.append(row)
        headings = [str(x + 1) for x in range(self.rows)]
        headings.insert(0, "")
        grid.append(headings)

        grid = SingleTable(grid)
        grid.padding_left = 2
        grid.padding_right = 2
        grid.inner_heading_row_border = True
        grid.inner_column_border = True
        grid.outer_border = False
        grid.inner_row_border = True
        return grid.table
コード例 #27
0
ファイル: example2.py プロジェクト: alex8866/linux_terminal
    [
        Color('Low Load'),
        Color('Nominal Load'),
        Color('{autored}High Load{/autored}')
    ],
    [
        Color('{autocyan}Low Free RAM{/autocyan}'),
        Color('Nominal Free RAM'),
        Color('High Free RAM')
    ],
]
print()
print(table.table)

table.title = None
table.outer_border = False
table.table_data = [['A', 'B'], ['C', 'D']]
print()
print(table.table)

table.outer_border = True
table.inner_row_border = False
table.inner_column_border = False
print()
print(table.table)

table = SingleTable([['Obey Obey Obey Obey']], 'Instructions')
print()
print(table.table)

print()
コード例 #28
0
def _chat_history_table(evts):
    # type: (List[Dict[Text, Any]]) -> Text
    """Create a table containing bot and user messages.

    Also includes additional information, like any events and
    prediction probabilities."""
    def wrap(txt, max_width):
        return "\n".join(
            textwrap.wrap(txt, max_width, replace_whitespace=False))

    def colored(txt, color):
        return "{" + color + "}" + txt + "{/" + color + "}"

    def format_user_msg(user_evt, max_width):
        _parsed = user_evt.get('parse_data', {})
        _intent = _parsed.get('intent', {}).get("name")
        _confidence = _parsed.get('intent', {}).get("confidence", 1.0)
        _md = _as_md_message(_parsed)

        _lines = [
            colored(wrap(_md, max_width), "hired"),
            "intent: {} {:03.2f}".format(_intent, _confidence)
        ]
        return "\n".join(_lines)

    def bot_width(_table):
        # type: (AsciiTable) -> int
        return _table.column_max_width(1)

    def user_width(_table):
        # type: (AsciiTable) -> int
        return _table.column_max_width(3)

    def add_bot_cell(data, cell):
        data.append([len(data), Color(cell), "", ""])

    def add_user_cell(data, cell):
        data.append([len(data), "", "", Color(cell)])

    # prints the historical interactions between the bot and the user,
    # to help with correctly identifying the action
    table_data = [
        [
            "#  ",
            Color(colored('Bot      ', 'autoblue')), "  ",
            Color(colored('You       ', 'hired'))
        ],
    ]

    table = SingleTable(table_data, 'Chat History')

    bot_column = []
    for idx, evt in enumerate(evts):
        if evt.get("event") == "action":
            bot_column.append(colored(evt['name'], 'autocyan'))
            if evt['confidence'] is not None:
                bot_column[-1] += (colored(
                    " {:03.2f}".format(evt['confidence']), 'autowhite'))

        elif evt.get("event") == 'user':
            if bot_column:
                text = "\n".join(bot_column)
                add_bot_cell(table_data, text)
                bot_column = []

            msg = format_user_msg(evt, user_width(table))
            add_user_cell(table_data, msg)

        elif evt.get("event") == "bot":
            wrapped = wrap(format_bot_output(evt), bot_width(table))
            bot_column.append(colored(wrapped, 'autoblue'))

        elif evt.get("event") != "bot":
            e = Event.from_parameters(evt)
            bot_column.append(wrap(e.as_story_string(), bot_width(table)))

    if bot_column:
        text = "\n".join(bot_column)
        add_bot_cell(table_data, text)

    table.inner_heading_row_border = False
    table.inner_row_border = True
    table.inner_column_border = False
    table.outer_border = False
    table.justify_columns = {0: 'left', 1: 'left', 2: 'center', 3: 'right'}

    return table.table
コード例 #29
0
print()
print(table.table)

table.title = '192.168.0.105'
table.justify_columns = {0: 'center', 1: 'center', 2: 'center'}
table.inner_row_border = True
table.table_data = [
    [Color('Low Space'), Color('{autocyan}Nominal Space{/autocyan}'), Color('Excessive Space')],
    [Color('Low Load'), Color('Nominal Load'), Color('{autored}High Load{/autored}')],
    [Color('{autocyan}Low Free RAM{/autocyan}'), Color('Nominal Free RAM'), Color('High Free RAM')],
]
print()
print(table.table)

table.title = None
table.outer_border = False
table.table_data = [['A', 'B'], ['C', 'D']]
print()
print(table.table)

table.outer_border = True
table.inner_row_border = False
table.inner_column_border = False
print()
print(table.table)

table = SingleTable([['Obey Obey Obey Obey']], 'Instructions')
print()
print(table.table)

print()
コード例 #30
0
    def printboard(self):
        table_instance = SingleTable(
            [[self.name, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
             [
                 '1', self.board[0, 0], self.board[0, 1], self.board[0, 2],
                 self.board[0, 3], self.board[0, 4], self.board[0, 5],
                 self.board[0, 6], self.board[0, 7], self.board[0, 8],
                 self.board[0, 9]
             ],
             [
                 '2', self.board[1, 0], self.board[1, 1], self.board[1, 2],
                 self.board[1, 3], self.board[1, 4], self.board[1, 5],
                 self.board[1, 6], self.board[1, 7], self.board[1, 8],
                 self.board[1, 9]
             ],
             [
                 '3', self.board[2, 0], self.board[2, 1], self.board[2, 2],
                 self.board[2, 3], self.board[2, 4], self.board[2, 5],
                 self.board[2, 6], self.board[2, 7], self.board[2, 8],
                 self.board[2, 9]
             ],
             [
                 '4', self.board[3, 0], self.board[3, 1], self.board[3, 2],
                 self.board[3, 3], self.board[3, 4], self.board[3, 5],
                 self.board[3, 6], self.board[3, 7], self.board[3, 8],
                 self.board[3, 9]
             ],
             [
                 '5', self.board[4, 0], self.board[4, 1], self.board[4, 2],
                 self.board[4, 3], self.board[4, 4], self.board[4, 5],
                 self.board[4, 6], self.board[4, 7], self.board[4, 8],
                 self.board[4, 9]
             ],
             [
                 '6', self.board[5, 0], self.board[5, 1], self.board[5, 2],
                 self.board[5, 3], self.board[5, 4], self.board[5, 5],
                 self.board[5, 6], self.board[5, 7], self.board[5, 8],
                 self.board[5, 9]
             ],
             [
                 '7', self.board[6, 0], self.board[6, 1], self.board[6, 2],
                 self.board[6, 3], self.board[6, 4], self.board[6, 5],
                 self.board[6, 6], self.board[6, 7], self.board[6, 8],
                 self.board[6, 9]
             ],
             [
                 '8', self.board[7, 0], self.board[7, 1], self.board[7, 2],
                 self.board[7, 3], self.board[7, 4], self.board[7, 5],
                 self.board[7, 6], self.board[7, 7], self.board[7, 8],
                 self.board[7, 9]
             ],
             [
                 '9', self.board[8, 0], self.board[8, 1], self.board[8, 2],
                 self.board[8, 3], self.board[8, 4], self.board[8, 5],
                 self.board[8, 6], self.board[8, 7], self.board[8, 8],
                 self.board[8, 9]
             ],
             [
                 '10', self.board[9, 0], self.board[9, 1], self.board[9, 2],
                 self.board[9, 3], self.board[9, 4], self.board[9, 5],
                 self.board[9, 6], self.board[9, 7], self.board[9, 8],
                 self.board[9, 9]
             ]])

        # Get second table lines.
        table_instance.outer_border = True
        table_instance.inner_column_border = True
        table_instance.inner_row_border = True
        table = table_instance.table.splitlines()

        return table
コード例 #31
0
def standard_insight(number):

    # Clear the terminal
    click.clear()

    client = nexmo.Client(
        key=os.environ['NEXMO_API_KEY'],
        secret=os.environ['NEXMO_API_SECRET']
    )

    response = client.get_standard_number_insight({'number': number})

    if response['status'] == 0:

        # Number format table
        number_data = [
            [
                click.style('International format', bold=True),
                click.style(response['international_format_number'], fg='green')
            ],
            [
                click.style('National format', bold=True),
                click.style(response['national_format_number'], fg='green')
            ]
        ]

        number_table = SingleTable(number_data)
        number_table.inner_heading_row_border = False
        number_table.outer_border = False

        # Country code information table
        country_data = [[
            click.style('Key', bold=True, fg='green'),
            click.style('Value from Nexmo', bold=True, fg='green')
        ]]

        for k in ['country_name', 'country_prefix', 'country_code', 'country_code_iso3']:
            country_data.append([
                k.replace('_', ' '),
                response[k]
            ])

        country_table = SingleTable(country_data)
        country_table.title = 'COUNTRY INFORMATION'

        # Carrier table
        carrier_data = [[
            click.style('Key', bold=True, fg='green'),
            click.style('Value from Nexmo', bold=True, fg='green')
        ]]

        for key, value in response['current_carrier'].items():
            carrier_data.append([
                key.replace('_', ' '),
                value
            ])

        carrier_table = SingleTable(carrier_data)
        carrier_table.title = 'CURRENT CARRIER'

        click.echo(" ")
        click.echo(number_table.table)
        click.echo(" ")
        click.echo(country_table.table)
        click.echo(" ")
        click.echo(carrier_table.table)

    else:
        # There's been some sort of error, print the message from Nexmo
        click.secho(
            response['status_message'],
            bold=True,
            bg='red',
            fg='white'
        )
コード例 #32
0
def main():
    res = arguments()
    api_key = res.KEY
    file_to_scan = res.FILE
    params = {"apikey": api_key}
    files = {"file": (res.FILE, open(res.FILE, 'rb'))}
    resp = requests.post('https://www.virustotal.com/vtapi/v2/file/scan',
                         files=files,
                         params=params)
    check_response_code(resp)
    print("[*] Sent file to VT api")
    resource_hash = resp.json()['resource']
    params['resource'] = resource_hash
    headers = {
        "Accept-Encoding":
        "gzip, deflate",
        "User-Agent":
        "Mozilla/5.0 (X11; Linux x86_64; rv:2.0b4) Gecko/20100818 Firefox/4.0b4"
    }
    resp = requests.get("https://www.virustotal.com/vtapi/v2/file/report",
                        params=params,
                        headers=headers)
    check_response_code(resp)
    if res.OUT:
        with open(res.OUT, "w+") as outfile:
            outfile.write(resp.text)
            outfile.close()
    print("[*] Received response\n")
    positives = int(resp.json()['positives'])
    total = int(resp.json()['total'])
    if res.CLEAR:
        subprocess.call("clear", shell=True)
    detection_rate = round((positives / total) * 100, 2)
    attrs = []
    if int(detection_rate) in range(0, 20):
        color = 'blue'
    elif int(detection_rate) in range(20, 40):
        color = 'green'
    elif int(detection_rate) in range(40, 60):
        color = 'yellow'
    elif int(detection_rate) in range(60, 80):
        color = 'red'
    elif int(detection_rate) in range(60, 100):
        color = 'red'
        attrs = ['blink']
    print(
        f"{green('[+]')} Results for {bold(res.FILE)} ({resp.json()['scan_date']})"
    )
    print(f"Permalink: {resp.json()['permalink']}")
    print(
        f"\n{bold('Detection rate:')} {colored(detection_rate, color, attrs=attrs)} ({green(positives)} positive / {red(total-positives)} negative)"
    )
    print(f"MD5: {resp.json()['md5']}")
    print(f"SHA256: {resp.json()['sha256']}")
    print(f"SHA1: {resp.json()['sha1']}")
    scans = resp.json()['scans']
    table_data = [['--VENDOR--', '--STATUS--', '--RESULT--', '--UPDATE--']]
    for scan in scans:
        detected = colored("not detected", "red", attrs=["bold"])
        scan_result = "N/A"
        if scans[scan]['detected']:
            detected = colored("detected", "green", attrs=["bold"])
        if scans[scan]['result'] != None:
            scan_result = scans[scan]["result"]
        date = str(scans[scan]['update'])
        date = "{}-{}-{}".format(date[0:4], date[4:6], date[6:8])
        if (res.POSITIVE and scans[scan]["detected"]):
            table_data.append([scan, detected, scan_result, date])
        elif not res.POSITIVE:
            table_data.append([scan, detected, scan_result, date])
    table = SingleTable(table_data)
    table.inner_column_border = False
    table.outer_border = False
    table.justify_columns[1] = "center"
    if (not res.QUIET and len(table_data) != 1):
        print("\nVendors analysis results:\n")
        print(table.table)
コード例 #33
0
 def draw(self):
     t = SingleTable(self.m, self.title)
     t.outer_border = True
     t.inner_row_border = True
     t.inner_column_border = True
     print(t.table)