Beispiel #1
0
def list_all():
    print '\n{}ENCODERS{}'.format(logs.bold(logs.purple('>>')),logs.bold(logs.purple('<<')))
    table_data = [['--NAME--', '--ARCH--', '--DESCRIPTION--', '--RANK--']]
    encoders = []
    for enc in os.walk(PATH+'encoders'):
        encoders.append(enc)
    encoders = encoders[0][2]
    cdrs = []
    for enc in encoders:
        if ('init' in enc or '.pyc' in enc):
            pass
        else:
            cdrs.append(enc.replace('.py', ''))
    for encoder in cdrs:
        try:
            encoder = importlib.import_module('encoders.'+encoder).Encoder()
            if encoder.rank == 'unstable':
                rank = logs.red('UNSTABLE')
            if encoder.rank == 'manual':
                rank = logs.yellow('MANUAL')
            elif encoder.rank == 'good':
                rank = logs.green('GOOD')
            elif encoder.rank == 'excellent':
                rank = logs.blue('EXCELLENT')
        except:
            rank = 'N/A'
        table_data.append([encoder.name, encoder.arch, encoder.description, rank])
    table_instance = SingleTable(table_data) 
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = False
    table_instance.justify_columns = {0: 'left', 1: 'left', 2: 'left'}
    print table_instance.table

    print '\n{}EGGHUNTERS{}'.format(logs.bold(logs.purple('>>')),logs.bold(logs.purple('<<')))
    table_data = [['--NAME--', '--PLATFORM--', '--SIZE--', '--EGG SIZE--']]
    for egg in eggs:
        table_data.append([egg, eggs[egg][1],'{} bytes'.format(eggs[egg][2]),'{} bytes'.format(eggs[egg][3])])
    table_instance = SingleTable(table_data) 
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = False
    table_instance.justify_columns = {0: 'left', 1: 'left', 2: 'left'}
    print table_instance.table

    print '\n{}FORMATS{}'.format(logs.bold(logs.purple('>>')),logs.bold(logs.purple('<<')))
    table_data = [['--FORMAT--', '--DESCRIPTION--']]
    for func in dir(wrappers):
        if "format_"  in func:
            table_data.append([func.replace("format_", ''), eval("wrappers.{}".format(func)).__doc__])
    table_instance = SingleTable(table_data) 
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = False
    table_instance.justify_columns = {0: 'left', 1: 'left', 2: 'left'}
    print table_instance.table
Beispiel #2
0
    def _repr_tty_(self) -> str:
        """Return a summary of this sample sheet in a TTY compatible codec."""
        header_description = ['Sample_ID', 'Description']
        header_samples = [
            'Sample_ID',
            'Sample_Name',
            'Library_ID',
            'index',
            'index2',
        ]

        header = SingleTable([], 'Header')
        setting = SingleTable([], 'Settings')
        sample_main = SingleTable([header_samples], 'Identifiers')
        sample_desc = SingleTable([header_description], 'Descriptions')

        # All key:value pairs found in the [Header] section.
        max_header_width = max(MIN_WIDTH, sample_desc.column_max_width(-1))
        for key in self.Header.keys():
            if 'Description' in key:
                value = '\n'.join(
                    wrap(getattr(self.Header, key), max_header_width))
            else:
                value = getattr(self.Header, key)
            header.table_data.append([key, value])

        # All key:value pairs found in the [Settings] and [Reads] sections.
        for key in self.Settings.keys():
            setting.table_data.append((key, getattr(self.Settings, key) or ''))
        setting.table_data.append(('Reads', ', '.join(map(str, self.Reads))))

        # Descriptions are wrapped to the allowable space remaining.
        description_width = max(MIN_WIDTH, sample_desc.column_max_width(-1))
        for sample in self.samples:
            # Add all key:value pairs for this sample
            sample_main.table_data.append(
                [getattr(sample, title) or '' for title in header_samples])
            # Wrap and add the sample descrption
            sample_desc.table_data.append((
                sample.Sample_ID,
                '\n'.join(wrap(sample.Description or '', description_width)),
            ))

        # These tables do not have horizontal headers so remove the frame.
        header.inner_heading_row_border = False
        setting.inner_heading_row_border = False

        table = '\n'.join([
            header.table, setting.table, sample_main.table, sample_desc.table
        ])

        return table
Beispiel #3
0
def print_secrets(secrets):
  data = [ ["id", "name", "website", "user", "password", "notes" ] ]
  for s in secrets:
    data = Secret.todict(s).items()
    table = SingleTable(data)
    table.inner_heading_row_border = False
    print(table.table)
Beispiel #4
0
    def validate_args(self):
        parser = argparse.ArgumentParser(description="")
        parser.add_argument("-A",
                            "--option",
                            metavar="<option>",
                            dest="algorithm",
                            default=None,
                            help="Choose hash' option between %s" % ALGORITHMS)
        parser.add_argument("-H",
                            "--hash",
                            metavar="<hash>",
                            dest="hash",
                            default=None,
                            help="Specify a hash to crack")
        args = parser.parse_args()

        if not args.hash:
            print_error("Missing --hash option!")
            sys.exit(-1)
        if not args.algorithm:
            print_error("Missing --option option!")
            sys.exit(-1)
        if args.algorithm not in ALGORITHMS:
            print_error("Wrong --option option!")
            data = []
            for x in ALGORITHMS:
                data.append([x])
            t = SingleTable(data, 'Available option')  #AsciiTable()
            t.inner_heading_row_border = False
            t.justify_columns[0] = 'center'
            print "Available option:"
            print t.table
            sys.exit(-1)
        return args
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 summary_arp_mon(pkts, res):
    table_data = [[]]

    def arp_mon_display(pkt):
        if pkt[ARP].op == 1:
            return f"{green('>')} Request: {pkt[ARP].psrc} is asking about {pkt[ARP].pdst}"
        if pkt[ARP].op == 2:
            return f"{red('<')} Response: {pkt[ARP].hwsrc} has address {pkt[ARP].hwdst}"
        if pkt[ARP].op == 2 and pkt[ARP].psrc == pkt[ARP].pdst:
            return f"{blue('*')} Cache exchange: {pkt[ARP].psrc}"

    for pkt in pkts:
        if pkt.haslayer(ARP):
            table_data.append([arp_mon_display(pkt)])
    print(f"{s} ARP monitor {s}")
    #if any(pkt.haslayer(ARP) for pkt in pkts):
    if len(table_data) != 0:
        table = SingleTable(table_data[1:])
    else:
        table = SingleTable([[red("No packets with ARP layer")]])
    table.inner_heading_row_border = False
    print(table.table)
    if res.OUTPUT:
        with open(res.OUTPUT, "a") as out_file:
            out_file.write(f"\n{table.table}\n")
    print("")
Beispiel #7
0
    def handleDiscovery(self, dev, isNewDev, isNewData):
        if not isNewDev:
            return
        elif self.opts.mac is not None and dev.addr != self.opts.mac:
            return
        elif dev.rssi < self.opts.sensitivity:
            return

        vendor = vendors.find(dev.addr)
        vlabel = yellow(vendor + ' ') if vendor is not None else '?'
        clabel = green(u'\u2713') if dev.connectable else red(u'\u2715')
        dlabel = "(no data) " if not dev.scanData else ""
        title = " %s (%s dBm) %s" % (bold(dev.addr), dev.rssi, dlabel)
        tdata = [['Vendor', vlabel], ['Allows Connections', clabel],
                 ['Address Type', dev.addrType]]

        for (tag, desc, val) in dev.getScanData():
            if desc == 'Flags':
                tdata.append(['Flags', self._parseFlags(val)])

            # short local name or complete local name
            elif tag in [8, 9]:
                try:
                    tdata.append([desc, yellow(val.decode('utf-8'))])
                except UnicodeEncodeError:
                    tdata.append([desc, yellow(repr(val))])
            else:
                tdata.append([desc, repr(val)])

        table = SingleTable(tdata, title)
        table.inner_heading_row_border = False

        print table.table + "\n"
Beispiel #8
0
    def archs(self):
        filtered = []
        table = []

        archs = sorted(list(self.executor.get_archs()))

        cur = [archs[0]]
        loc_max = MN_INF
        for pos in range(1, len(archs)):
            if self.__is_similar(archs[pos], archs[pos - 1]):
                cur.append(archs[pos])
            else:
                loc_max = max(loc_max, len(cur))
                filtered.append(['<cyan>{}</>'.format(x) for x in cur])
                cur = [archs[pos]]
        filtered.append(['<cyan>{}</>'.format(x) for x in cur])
        loc_max = max(loc_max, len(cur))

        table.append(['\r'] * len(filtered))
        for i in range(loc_max):
            cur_row = []
            for j in range(len(filtered)):
                cur_row.append('' if i >= len(filtered[j]) else make_colors(
                    filtered[j][i]))
            table.append(cur_row)
        rtable = SingleTable(table)
        rtable.inner_heading_row_border = False
        return rtable.table
Beispiel #9
0
def print_inventory(emoji, emoji_you_have, title="Your Inventory"):
    newlist = [emoji[1:], emoji_you_have[1:]]
    table = SingleTable(newlist)
    table.inner_row_border = True
    table.inner_heading_row_border = False
    table.title = title
    print(table.table)
Beispiel #10
0
def viewSentiments(number):
    twits = getFile()
    table_data = [[
        Color('{cyan}TWEET{/cyan}'),
        Color('{autored}SENTIMENTS{/autored}')
    ]]
    for twit in tqdm(twits.items(),
                     total=number,
                     desc="Analysing sentiments..."):
        sentiment = twit[1]['sentiments']
        sentString = ''
        for item in sentiment:
            sentString += item + '\n'
        sentString = sentString.strip()
        text = '\n'.join(wrap(twit[1]['tweet'], 80))
        table_data.append([
            Color('{cyan}' + text + '{/cyan}'),
            Color('{red}' + sentString + '{/red}')
        ])
    table_instance = SingleTable(table_data,
                                 Color('{green}Sentiment Analysis{/green}'))
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = True
    table_instance.justify_columns = {0: 'left', 1: 'left'}
    return table_instance.table
Beispiel #11
0
def viewRanks(number):
    twits = getFile()
    stopWords = getStopwords()
    words = []
    for twit in tqdm(twits.items(), total=number, desc="Ranking words..."):
        words.extend(word_tokenize(twit[1]['tweet']))
    words = [
        word for word in words
        if word.lower() not in stopWords and re.match(r'\w', word)
    ]
    wordsDict = Counter(words)
    sortedList = sorted(wordsDict.items(), key=lambda x: x[1], reverse=True)
    table_data = [[
        Color('{cyan}WORDS{/cyan}'),
        Color('{autored}RANKS{/autored}')
    ]]
    for word in sortedList:
        table_data.append(
            [Color(word[0]),
             Color('{autored}' + str(word[1]) + '{/autored}')])
    table_instance = SingleTable(table_data,
                                 Color('{green}Word Frequency{/green}'))
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = True
    table_instance.justify_columns = {0: 'center', 1: 'center'}
    return table_instance.table
 def __str__(self):
     title = 'Prediction for ' + str(self.input)
     data = [[p[1], '{:6.2f}%'.format(100 * p[0])]
             for p in self.probabilities]
     table = SingleTable(data)
     table.inner_heading_row_border = False
     return title + '\n' + table.table
    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 #14
0
Datei: scan.py Projekt: ysf/bleah
    def printShortTable(self, addr):
        """ Print the short overview table for the given device

        @addr: mac addr of the device to print
        """

        vendor = self.devdata[addr]["vendor"]
        vlabel = yellow( vendor + ' ' ) if vendor is not None else '?'
        clabel = green( u'\u2713' ) if self.devdata[addr]["connectable"] else red( u'\u2715' )
        dlabel = "(no data) " if not self.devdata[addr]["scanData"] else ""
        title  = " %s (%s dBm) %s" % ( bold(addr), self.devdata[addr]["rssi"], dlabel )

        tdata  = [
            [ 'Vendor', vlabel ],
            [ 'Allows Connections', clabel ],
            [ 'Address Type', self.devdata[addr]["addrType"]]
        ]

        for desc in self.devdata[addr]["descs"]:
            tdata.append([ desc, self.devdata[addr][desc] ])
        if "Short Local Name" in self.devdata[addr].keys():
            tdata.append([ "Short Local Name", yellow( self.devdata[addr]["Short Local Name"] ) ])
        if "Complete Local Name" in self.devdata[addr].keys():
            tdata.append([ "Complete Local Name", yellow( self.devdata[addr]["Complete Local Name"] ) ])

        tdata.append([ 'Flags', ', '.join(self.devdata[addr].get("flags",[])) ])

        table = SingleTable(tdata, title)
        table.inner_heading_row_border = False

        print(table.table + "\n")
Beispiel #15
0
def info(ctx):
    redact = ctx.obj["redact"]
    card = get_reader(ctx.obj["reader"])
    apps = card.list_applications()

    click.secho("\n1PAY.SYS.DDF01 (Index of apps for chip payments)",
                bold=True)
    render_app(card, "1PAY.SYS.DDF01", redact)
    click.secho("\n2PAY.SYS.DDF01 (Index of apps for contactless payments)",
                bold=True)
    try:
        render_app(card, "2PAY.SYS.DDF01", redact)
    except MissingAppException:
        click.secho(
            "2PAY.SYS.DDF01 not available (this is normal on some cards)",
            fg="yellow")

    for app in apps:
        click.secho(
            "\nApplication %s, DF Name: %s" % (
                render_element(Tag.APP_LABEL, app[Tag.APP_LABEL]),
                render_element(Tag.DF, app[Tag.ADF_NAME]),
            ),
            bold=True,
        )
        render_app(card, app[Tag.ADF_NAME], redact)

    click.echo("\nFetching card metadata...")
    try:
        tab = SingleTable(card.get_metadata().items())
        tab.inner_heading_row_border = False
        click.echo(tab.table)
    except ErrorResponse as e:
        click.secho("Unable to fetch card data: %s" % e, fg="yellow")
Beispiel #16
0
def print_vending_machine():
    line1 = '   1     2     3   '
    line2 = '                   '
    line3 = '  ^_^ | T-T  | @_@ '
    line4 = '  20  |  60  | 100 '
    line5 = '   4     5     6   '
    line6 = '                   '
    line7 = '  @.@ | *-*  | :P  '
    line8 = '  150 | 200  | 250 '
    line9 = '                   '
    line10 = '       OUTPUT      '
    line11 = '                   '
    line12 = '   _______________ '

    newlist = []
    newlist.append([line1 + "\n" + line2 + "\n" + line3 + "\n" + line4])
    newlist.append([line5 + "\n" + line6 + "\n" + line7 + "\n" + line8])
    newlist.append([line9 + "\n" + line10 + "\n" + line11 + "\n" + line12])
    #print(newlist)

    table = SingleTable(newlist)
    table.inner_row_border = True
    table.inner_heading_row_border = False
    table.title = "Emoji Vending Machine"
    sp.call("clear", shell=True)
    print(table.table)
Beispiel #17
0
    def print_compare(self, src, dst, a, b, sym):

        from colorclass import Color, Windows

        from terminaltables import SingleTable

        Windows.enable(auto_colors=True, reset_atexit=True)  # Does nothing if not on Windows.

        max_width = 50
        l = [Color('{autocyan}' + self.wrap_text(src, max_width) + '{/autocyan}'),
             sym[0],
             Color('{autocyan}' + self.wrap_text(dst, max_width) + '{/autocyan}')]
        table_data = []
        table_data.append(l)

        for key, value in a.items():
            l = [self.wrap_text(key, max_width), sym[1], ""]
            table_data.append(l)
        for key, value in b.items():
            l = ["", sym[2], self.wrap_text(key, max_width)]
            table_data.append(l)

        table = SingleTable(table_data)
        table.inner_heading_row_border = True
        table.inner_row_border = True
        print(table.table)
Beispiel #18
0
def reevaluate():
    path = '*.lp'
    if DIRECTORY:
        path = os.path.join(DIRECTORY, path)
    files = glob.glob(path)
    if not files:
        print('No .lp files found')
        return

    # in case solving takes a while
    print('Solving...', end=' ', flush=True)

    res = solve_interruptible(files=files)

    if res.raw and 'UNSATISFIABLE' in res.raw:
        print(res.raw)
        return

    r, c = term_dimensions()

    facts = res.facts

    facts = sorted(facts)

    # before we destroy the structure for rendering
    facts = [wrap(f) for f in facts]

    facts = split_columns(facts, r - 3)

    table = SingleTable(facts)
    table.inner_heading_row_border = False
    clear()
    print(table.table)
Beispiel #19
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 #20
0
    def tokenizer_stats(self, tokenizer):
        def chunk(iterable, n):
            for i in range(0, len(iterable), n):
                yield iterable[i:i + n]

        document_ids = [
            hit.meta.id for hit in tokenizer.documents.search()[:100]
        ]
        sentence_counts = [
            tokenizer.sentences.search().filter('term',
                                                document_id=doc).count()
            for doc in document_ids
        ]

        data = [[
            '%s | %s' % pair for pair in zip(l, r)
        ] for l, r in zip(chunk(document_ids, 5), chunk(sentence_counts, 5))]

        table = SingleTable(data,
                            title=' Documents: %d | Sentences: %d ' % (
                                tokenizer.documents.search().count(),
                                tokenizer.sentences.search().count(),
                            ))
        table.inner_heading_row_border = False

        self.stdout.write(table.table)
Beispiel #21
0
def summary_host_write(pkts, res):
    found_hosts = []
    for pkt in pkts:
        if pkt.haslayer(IP):
            found_hosts.append(pkt[IP].src)
            found_hosts.append(pkt[IP].dst)
    found_hosts = set(found_hosts)
    for h in found_hosts:
        table_data.append(host_formatter(h, pkts))
    print(f"{s} Hosts {s}")
    #if any(pkt.haslayer(ARP) for pkt in pkts):
    if len(table_data) == 0:
        table = SingleTable(table_data[1:])
    else:
        table = SingleTable([[red("No hosts found")]])
    table.inner_heading_row_border = False
    print(table.table)
    with open(res.HOST_WRITE, "w+") as host_write_file:
        host_write_file.write("\n".join(found_hosts))
        host_write_file.close()
        print_info(
            f"Saved addresses of {len(found_hosts)} found hosts in {res.HOST_WRITE}"
        )
    if res.OUTPUT:
        with open(res.OUTPUT, "a") as out_file:
            out_file.write(f"\n{table.table}\n")
    print("")
Beispiel #22
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 #23
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 #24
0
    def box(cls, width, height, title=''):
        table_structure = [[' ' * (width - 2)] for x in range(height - 2)]

        table = SingleTable(table_structure, ' {} '.format(title))
        table.inner_row_border = False
        table.inner_heading_row_border = False

        return table.table
Beispiel #25
0
def print_table(guessed_result):
    newlist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], guessed_result]
    table = SingleTable(newlist)
    table.inner_row_border = True
    table.inner_heading_row_border = False
    table.title = "Number List"
    # sp.call("clear",shell=True)
    print(table.table)
Beispiel #26
0
 def pprint(self):
     """
     Pretty prints the contents of the box
     """
     table = SingleTable(self.boxes)
     table.inner_heading_row_border = False
     table.inner_row_border = True
     print(table.table)
Beispiel #27
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 #28
0
def print_table(table_data,title=None):

    """Return table string to be printed."""
    table_instance = SingleTable(table_data.tolist(), title)
    table_instance.inner_heading_row_border = False
    table_instance.inner_row_border = True
#    table_instance.justify_columns = {0: 'center', 1: 'center', 2: 'center'}
    print (table_instance.table)
Beispiel #29
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 #30
0
 def show_sorted_gold(self):
     table = SingleTable(self.mat)
     table.title = Color('{blue}Sorted gold{/blue}')
     table.inner_row_border = True
     table.inner_heading_row_border = False
     for i in range(5):
         table.justify_columns[i] = 'center'
     print(table.table)
     print()
Beispiel #31
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 #32
0
def display_latest_rankings(date=None,
                            json_output=False,
                            data_dir=None,
                            esi_filename=None,
                            esi_sheet_name=None):
    """Display ESI rankings in the console or output as JSON."""
    BOLD = '\033[1m'
    ENDC = '\033[0m'
    GREEN = '\033[92m'
    RED = '\033[91m'
    indicators = [
        'esi', 'industrial_confidence', 'services_confidence',
        'consumer_confidence', 'retail_confidence', 'construction_confidence'
    ]
    esi = ESIDataWrapper()
    if data_dir:
        esi.data_dir = data_dir
    if esi_filename:
        esi.esi_filename = esi_filename
    if esi_sheet_name:
        esi.esi_sheet_name = esi_sheet_name
    num_entries = len(esi.ESI_ENTITIES)
    rankings = esi.get_latest_rankings(date=date)

    if json_output:
        print(json.dumps(rankings))
    else:
        table_data = [
            # Headers.
            [
                BOLD + 'ESI' + ENDC, 'Industrial Confidence (40%)',
                'Services Confidence (30%)', 'Consumer Confidence (20%)',
                'Retail Trade Confidence (5%)', 'Construction Confidence (5%)'
            ]
        ]
        for i in range(num_entries):
            if i == 0:
                tmpl = GREEN + '{} ({})' + ENDC
            elif i == 15:
                tmpl = RED + '{} ({})' + ENDC
            else:
                tmpl = '{} ({})'

            row = [
                tmpl.format(rankings[indicator][i][0],
                            rankings[indicator][i][1])
                for indicator in indicators
            ]
            table_data.append(row)

        rankings_table = SingleTable(table_data)
        rankings_table.inner_heading_row_border = False
        rankings_table.inner_heading_row_border = True
        if date:
            rankings_table.title = 'Rankings for {}'.format(date)

        print(rankings_table.table)
Beispiel #33
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 #34
0
def table_server_timings():
    """Return table string to be printed."""
    table_data = [
        [Color('{autogreen}<10ms{/autogreen}'), '192.168.0.100, 192.168.0.101'],
        [Color('{autoyellow}10ms <= 100ms{/autoyellow}'), '192.168.0.102, 192.168.0.103'],
        [Color('{autored}>100ms{/autored}'), '192.168.0.105'],
    ]
    table_instance = SingleTable(table_data)
    table_instance.inner_heading_row_border = False
    return table_instance.table
Beispiel #35
0
def test():
    #Windows.enable(auto_colors=True, reset_atexit=True)
    table_data = [
        [Color('{autogreen}TITLE{/autogreen}'), '192.168.0.100, 192.168.0.101'],
        [Color('{autocyan}10ms <= 100ms{/autocyan}'), '192.168.0.102, 192.168.0.103'],
        [Color('{autored}>100ms{/autored}'), '192.168.0.105'],
    ]
    table = SingleTable(table_data)
    table.inner_heading_row_border = False
    print(table.table)
Beispiel #36
0
def table_server_status():
    """Return table string to be printed."""
    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')],
    ]
    table_instance = SingleTable(table_data, '192.168.0.105')
    table_instance.inner_heading_row_border = False
    table_instance.inner_row_border = True
    table_instance.justify_columns = {0: 'center', 1: 'center', 2: 'center'}
    return table_instance.table
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 #38
0
def _print_deployment_summary(env):
    table_data = [
        ["Project name:", env.project_name],
        ["Target:", env.target_name],
        ["User:"******"Host(s):", "; ".join(env.hosts)],
    ]

    table = SingleTable(table_data)
    table.title = Color('{autoyellow}Deployment configuration{/autoyellow}')
    table.justify_columns = {0: 'left', 1: 'left'}
    table.inner_row_border = False
    table.inner_heading_row_border = False

    _print_table(table)
Beispiel #39
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 #40
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 #41
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 #42
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 #43
0
    def handleDiscovery(self, dev, isNewDev, isNewData):
        if not isNewDev:
            return 
        elif self.opts.mac is not None and dev.addr != self.opts.mac:
            return 
        elif dev.rssi < self.opts.sensitivity:
            return

        vendor = vendors.find(dev.addr)
        vlabel = yellow( vendor + ' ' ) if vendor is not None else '?'
        clabel = green( u'\u2713' ) if dev.connectable else red( u'\u2715' )
        dlabel = "(no data) " if not dev.scanData else ""
        title  = " %s (%s dBm) %s" % ( bold(dev.addr), dev.rssi, dlabel )
        tdata  = [
            [ 'Vendor', vlabel ],
            [ 'Allows Connections', clabel ],
            [ 'Address Type', dev.addrType]
        ]

        for ( tag, desc, val ) in dev.getScanData():
            if desc == 'Flags':
                tdata.append([ 'Flags', self._parseFlags(val) ])

            # short local name or complete local name
            elif tag in [8, 9]:
                try:
                    tdata.append([ desc, yellow( val.decode('utf-8') ) ])
                except UnicodeEncodeError:
                    tdata.append([ desc, yellow( repr(val) ) ])
            else:
                tdata.append([ desc, repr(val) ])


        table = SingleTable(tdata, title)
        table.inner_heading_row_border = False

        print table.table + "\n"
from __future__ import print_function

from colorclass import Color, Windows

from terminaltables import SingleTable


Windows.enable(auto_colors=True, reset_atexit=True)  # Does nothing if not on Windows.

table_data = [
    [Color('{autobgred}{autogreen}<10ms{/autogreen}{/bgred}'), '192.168.0.100, 192.168.0.101'],
    [Color('{autoyellow}10ms <= 100ms{/autoyellow}'), '192.168.0.102, 192.168.0.103'],
    [Color('{autored}>100ms{/autored}'), '192.168.0.105'],
]
table = SingleTable(table_data)
table.inner_heading_row_border = False
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
Beispiel #45
0
	def print_pokemon(self):
		sorted_mons = sorted(self.pokemon, key=lambda k: (k['pokedex_number'], -k['iv_percent']))
		groups = groupby(sorted_mons, key=lambda k: k['pokedex_number'])
		table_data = [
			[u'Pokémon', 'Level', 'CP', 'IV %', 'ATK', 'DEF', 'STA', 'Candy', 'Recommendation']
		]
		total_evolutions = 0
		total_transfers = 0
		print u'%d Pokémon found.' % len(sorted_mons)
		for key, group in groups:
			group = list(group)
			pokemon_name = self.pokemon_list[str(key)]
			best_iv_pokemon = max(group, key=lambda k: k['iv_percent'])
			best_iv_pokemon['best_iv'] = True
			candy_count=self.candy[key]
			result = pogotransfercalc.calculate(
				pokemon_count=len(group),
				candy_count=candy_count,
				pokedex_number=key)
			evolutions = result['evolutions']
			total_evolutions += evolutions
			if evolutions:
				for pokemon in group[:evolutions]:
					pokemon['message'] = 'evolve'
			transfers = result['transfers']
			transfer_count = 0
			if transfers:
				for pokemon in reversed(group[evolutions:]):
					if pokemon['is_favorite']:
						pokemon['message'] = u'keep (★)'
						continue
					if pokemon['has_costume']:
						pokemon['message'] = u'keep (costume)'
						continue
					if pokemon['is_shiny']:
						pokemon['message'] = u'keep (shiny)'
						continue
					if pokemon['iv_percent'] < self.config.iv:
						pokemon['message'] = 'transfer'
						pokemon['transfer'] = True
						transfer_count += 1
						total_transfers += 1
						if transfer_count == transfers:
							break
						continue
			for pokemon in group:
				if pokemon['iv_percent'] >= self.config.iv:
					iv_msg = u'(IV ≥ %d%%)' % self.config.iv
					if 'message' in pokemon:
						pokemon['message'] += ' %s' % iv_msg
					else:
						pokemon['message'] = 'keep %s' % iv_msg
				row_data = [
					pokemon_name + pokemon['gender'] + (u'✨' if pokemon['is_shiny'] else '') + (u'☃' if pokemon['has_costume'] else '') + (u'★' if pokemon['is_favorite'] else ''),
					pokemon['level'],
					pokemon['cp'],
					'{0:.0f}%'.format(pokemon['iv_percent']),
					pokemon['attack'],
					pokemon['defense'],
					pokemon['stamina'],
					candy_count,
					pokemon.get('message', '')
				]
				table_data.append(row_data)
		table = SingleTable(table_data)
		table.justify_columns = {
			0: 'left', 1: 'right', 2: 'right', 3: 'right',
			4: 'right', 5: 'right', 6: 'right', 7: 'right'
		}
		print table.table
		table = SingleTable([
			['Total suggested transfers', format_number(total_transfers)],
			['Total evolutions', format_number(total_evolutions)],
			['Total XP from evolutions', format_number(total_evolutions * 500)],
			['Total XP from evolutions with lucky egg', format_number(total_evolutions * 1000)],
		])
		table.inner_heading_row_border = False
		table.justify_columns = { 0: 'left', 1: 'right' }
		print table.table