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 
Beispiel #2
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)
Beispiel #3
0
def make_bar_chart(val,
                   max_val,
                   title=None,
                   left='',
                   right='',
                   color='green',
                   length=80):
    full_block = '█'
    empty_block = '░'
    half_block = '▒'

    # building the bar
    bar = ''
    num_full = length * val / float(max_val)
    bar += full_block * int(num_full)
    if not (num_full).is_integer():
        bar += half_block
    bar += empty_block * (length - len(bar))

    # colorize
    bar = colorize(bar, color)

    # adding left/right text if needed
    row = []
    if left:
        row.append(left)
    row.append(bar)
    if right:
        row.append(right)

    st = SingleTable([row], title)
    st.inner_column_border = False
    return st.table
Beispiel #4
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)
Beispiel #5
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()
Beispiel #6
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('')
Beispiel #7
0
 def table_metrics(self):
     # Returns a printable table of metrics
     data = [[m, self.metrics[m][-1]] for m in self.metrics.keys()]
     table = SingleTable(data, self.experiment.name)
     table.inner_heading_row_border = True
     table.inner_row_border = True
     table.inner_column_border = True
     return table.table
Beispiel #8
0
def list_files(folder_path):
    ipa_files = [f for f in os.listdir(folder_path) if str(f).endswith(".ipa")]
    table_data = [[' * ', Color('{autoblue}%-40s{/autoblue}' % f)] for f in ipa_files]
    table = SingleTable(table_data)
    table.title = "All ipa files:"
    table.inner_column_border = False
    table.inner_heading_row_border = False
    print(table.table)
Beispiel #9
0
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
Beispiel #10
0
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
Beispiel #11
0
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
Beispiel #12
0
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
Beispiel #13
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)
Beispiel #14
0
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
Beispiel #15
0
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
def hinton_diagram(arr, max_arr=None):
    max_arr = arr if max_arr is None else max_arr
    max_val = max(abs(np.max(max_arr)), abs(np.min(max_arr)))
    diagram = [list([hinton_diagram_value(x, max_val) for x in _arr]) for _arr in arr]

    table = SingleTable(diagram)
    table.inner_heading_row_border = False
    table.inner_footing_row_border = False
    table.inner_column_border = False
    table.inner_row_border = False
    table.column_max_width = 1

    return table.table
Beispiel #17
0
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
Beispiel #18
0
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)
Beispiel #19
0
    def report(self):
        print(colored("FAILED!", "red"), "Got wrong output...")

        table_data = [[self.test_case.input.rstrip("\n\r")]]
        table_instance = SingleTable(table_data, 'Input')
        table_instance.inner_heading_row_border = False
        table_instance.inner_row_border = False
        table_instance.inner_column_border = False

        print(table_instance.table)

        diff = ndiff(self.test_case.output.splitlines(1),
                     self.got_output.splitlines(1))

        table_data = []
        for line in diff:
            line = line.rstrip("\n\r")
            if line.startswith("+"):
                table_data.append(
                    [colored("GOT", "red"),
                     colored(line, "red")])
            elif line.startswith("-"):
                table_data.append(
                    [colored("EXPECTED", "green"),
                     colored(line, "green")])
            elif line.startswith("?"):
                table_data.append(["", colored(line, "yellow")])
            else:
                table_data.append(["", line])

        table_instance = SingleTable(table_data, 'Output Diff')
        table_instance.inner_heading_row_border = False
        table_instance.inner_row_border = False
        table_instance.inner_column_border = False

        print(table_instance.table)
Beispiel #20
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()
Beispiel #21
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)
Beispiel #22
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
Beispiel #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
Beispiel #24
0
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
Beispiel #25
0
def fill_tabel(app):
    table_data = [
        ['{0: <20}'.format('Title'),Color('{autoblue}%-50s{/autoblue}' % app.title)],
        ['{0: <20}'.format('URL'), Color('{autocyan}%s{/autocyan}' % app.url)],
        ['{0: <20}'.format('Price'), Color('{autogreen}%s{/autogreen}' % app.price)],
        ['{0: <20}'.format('Category'),Color('{autogreen}%s{/autogreen}' % app.category)],
        ['{0: <20}'.format('Release'),Color('{autogreen}%s{/autogreen}' % app.release)],
        ['{0: <20}'.format('Version') ,Color('{autogreen}%s{/autogreen}' % app.version)],
        ['{0: <20}'.format('Size'),Color('{autogreen}%s{/autogreen}' % app.size)],
        ['{0: <20}'.format('Language(s)'),Color('{autogreen}%s{/autogreen}' % app.language)],
        ['{0: <20}'.format('Developer'),Color('{autogreen}%s{/autogreen}' % app.developer)],
        ['{0: <20}'.format('Compatibility'),Color('{autogreen}%s...{/autogreen}' % ".".join(app.compatibility.split('.')[:2]))],
        ['{0: <20}'.format('Description:'),Color('{autocyan}%-50s{/autocyan}' % app.description)],
    ]
    table = SingleTable(table_data)
    table.inner_column_border = False
    table.inner_heading_row_border = False
    return table
Beispiel #26
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)
Beispiel #27
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)
Beispiel #28
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
Beispiel #29
0
def show_app_item(a):
    x = lambda s: Color('{autogreen}%s{/autogreen}' % s)
    y = lambda s: '{0: <20}'.format(s)
    table_data = [
        [y('Title'), x(a.title)],
        [y('URL'), x(a.url)],
        [y('Price'), x(a.price)],
        [y('Category'), x(a.category)],
        [y('Release'), x(a.release)],
        [y('Version'), x(a.version)],
        [y('Size'), x(a.size)],
        [y('Language(s)'), x(a.language)],
        [y('Developer'), x(a.developer)],
        [y('Compatibility'), x(a.compatibility)],
        [y('Description:'), x(a.description)],
    ]
    table = SingleTable(table_data)
    table.inner_column_border = False
    table.inner_heading_row_border = False
    print(table.table)
Beispiel #30
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)
Beispiel #31
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)
Beispiel #32
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
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()
Beispiel #34
0
        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()
Beispiel #35
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)
Beispiel #36
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