Ejemplo n.º 1
0
def lsa(asset=None, start=None, end=None):
    """
    Print list of assets or asset rates for the specified one

    Currency filter can be specified either as code, or as pair "code/code"

    If asset == '*' - print rates table

    Args:
        asset: asset code
        start: start date (for rates), default: first day of current month
        end: end date (for rates)
    """
    if not asset:
        ft = rapidtables.format_table(asset_list(),
                                      fmt=rapidtables.FORMAT_GENERATOR,
                                      align=(rapidtables.ALIGN_LEFT,
                                             rapidtables.ALIGN_RIGHT))
        if not ft:
            return
        h, tbl = ft
        neotermcolor.cprint(h, '@finac:title')
        neotermcolor.cprint('-' * len(h), '@finac:separator')
        for t in tbl:
            neotermcolor.cprint(t)
        neotermcolor.cprint('-' * len(h), '@finac:separator')
        print('Base asset: ', end='')
        neotermcolor.cprint(config.base_asset.upper(), style='finac:sum')
    else:
        rr = []
        for r in asset_list_rates(
                asset=(asset if asset != '*' else None),
                start=start if start else datetime.datetime.today().replace(
                    day=1, hour=0, minute=0, second=0,
                    microsecond=0).timestamp(),
                end=end,
                datefmt=True):
            row = OrderedDict()
            row['pair'] = '{}/{}'.format(r['asset_from'], r['asset_to'])
            row['date'] = r['date']
            row['value'] = r['value']
            rr.append(row)
        ft = rapidtables.format_table(rr, fmt=rapidtables.FORMAT_GENERATOR)
        if not ft:
            return
        h, tbl = ft
        neotermcolor.cprint(h, '@finac:title')
        neotermcolor.cprint('-' * len(h), '@finac:separator')
        for t in tbl:
            neotermcolor.cprint(t)
Ejemplo n.º 2
0
Archivo: help.py Proyecto: alttch/pptop
 def load_data(self):
     self.data.clear()
     try:
         pdoc = textwrap.dedent(self._previous_plugin['p'].__doc__)
     except:
         pdoc = None
     if pdoc:
         self.data.append({'help': ''})
         for x in pdoc.strip().split('\n'):
             self.data.append({'help': x})
         self.data.append({'help': ''})
         self.data.append({'help': '-' * scr.stdscr.getmaxyx()[1]})
     # global shortcuts
     keyhelp = {}
     for k, e in core.events_by_key.items():
         keyhelp.setdefault(e, []).append(core.format_shortcut(k))
     result = []
     for e in sorted(keyhelp):
         result.append({'e': e, 'k': ', '.join(sorted(keyhelp[e]))})
     self.data.append({'help': ''})
     self.data.append({'help': 'Global shorcuts'})
     keys_table = tuple(rapidtables.format_table(result,
                                           fmt=1,
                                           generate_header=False))
     self.data.append({'help': '-' * (len(keys_table[0]) + 4)})
     for d in keys_table:
         self.data.append({'help': ' ' * 4 + d})
     # end global shortcuts
     self.data.append({'help': ''})
     for x in textwrap.dedent(core.__doc__).split('\n'):
         self.data.append({'help': x})
Ejemplo n.º 3
0
def query(q):
    t_start = time.time()
    result = list(exec_query(q))
    t_spent = time.time() - t_start
    ft = rapidtables.format_table(result, fmt=rapidtables.FORMAT_GENERATOR)
    if ft:
        h, tbl = ft
        neotermcolor.cprint(h, '@finac:title')
        neotermcolor.cprint('-' * len(h), '@finac:separator')
        for t in tbl:
            print(t)
        neotermcolor.cprint('-' * len(h), '@finac:separator')
    print(f'SELECT {len(result)}')
    print(f'Time: {t_spent:.3f}s')
Ejemplo n.º 4
0
    def pretty_print_table(data):
        if data:
            for d in data:
                for k, v in d.items():
                    if v is None:
                        d[k] = '<null>'
            from rapidtables import (format_table, FORMAT_GENERATOR,
                                     MULTILINE_ALLOW)

            header, rows = format_table(data,
                                        fmt=FORMAT_GENERATOR,
                                        multiline=MULTILINE_ALLOW)
            print(colored(header, color='blue'))
            print(colored('-' * len(header), color='grey'))
            for r in rows:
                print(r)
Ejemplo n.º 5
0
Archivo: gcli.py Proyecto: alttch/eva3
 def fancy_print_list(self, result, func, itype):
     table = []
     for r in self.prepare_result_data(result, func, itype):
         t = OrderedDict()
         if func in self.pd_cols:
             for c in self.pd_cols[func]:
                 t[c] = self.list_to_str(r[c])
         else:
             for i, c in r.items():
                 t[i] = self.list_to_str(c)
         table.append(t)
     import rapidtables
     header, rows = rapidtables.format_table(table,
                                             rapidtables.FORMAT_GENERATOR)
     # header = header[:w]
     print(self.colored(header, color='blue', attrs=[]))
     print(self.colored('-' * len(header), color='grey', attrs=[]))
     for r in rows:
         print(r)
Ejemplo n.º 6
0
        })

    result = {}
    outs = '{:.3f}'
    result_rapidtables = timeit.timeit(stmt=test_rapidtables,
                                       number=num) / num * 1000
    result_pandas = timeit.timeit(stmt=test_pandas, number=num) / num * 1000
    result['rapidtables'] = outs.format(result_rapidtables)
    if rec <= 3000:
        result_tabulate = timeit.timeit(stmt=test_tabulate,
                                        number=num) / num * 1000
        result['tabulate'] = outs.format(result_tabulate)
        f1 = '{:.1f}'.format(result_tabulate / result_rapidtables)
    result['pandas'] = outs.format(result_pandas)
    f2 = '{:.1f}'.format(result_pandas / result_rapidtables)
    raw = rapidtables.format_table([result], fmt=1)
    print(colored(raw[0], color='blue'))
    print(colored('-' * len(raw[0]), color='grey'))
    print(colored('\n'.join(raw[1]), color='yellow'))
    print()
    fg = partial(colored, color='green', attrs=['bold'])
    summary = colored('rapidtables', color='red', attrs=['bold']) + ': '
    if rec <= 3000:
        summary += '{}x faster than tabulate, '.format(fg(f1))
    summary += '{}x faster than pandas'.format(fg(f2))
    print(summary)
    try:
        print('=' * (os.get_terminal_size(0)[0] - 10))
    except:
        print('=' * 20)
    print('')
Ejemplo n.º 7
0
    salary: Optional[int]
    job: str


person: JD = {'name': 'John', 'salary': 2000, 'job': 'DevOps'}

data: List[JobsDict] = [
    {'name': 'John', 'salary': 2000, 'job': 'DevOps'},
    {'name': 'Jack', 'salary': 2500, 'job': 'Architect'},
    {'name': 'Diana', 'salary': None, 'job': 'Student'},
    {'name': 'Ken', 'salary': 1800, 'job': 'Q/A'},
    # {'name': 'Kelly', 'salary': 120},  # error, missing job
    # {'name': 'Karen', 'salary': '12', 'job': 'Q/A'}  # error, salary should be int
]

header, rows = format_table(data, fmt=FORMAT_GENERATOR_COLS)
spacer = '  '
print(colored(spacer.join(header), color='blue'))
print(colored('-' * sum([(len(x) + 2) for x in header]), color='grey'))
for r in rows:
    print(colored(r[0], color='white', attrs=['bold']) + spacer, end='')
    print(colored(r[1], color='cyan') + spacer, end='')
    print(colored(r[2], color='yellow'))


# ------------------------------------------------------------------------------------------------

my_list_ints: List[int] = [1, 3, 4, -5, 12]
try:
    my_array_chars: array[c_byte] = array('b', my_list_ints)  # type: ignore  # 'b' 1 byte -128 <= int < 128 e.g. ctype.signedchar
    my_array_short_ints: array[c_short] = array('h', my_list_ints)  # type: ignore # 'h' 2 byte int <= 65535 e.g. ctype.short
Ejemplo n.º 8
0
    def render_table(self,
                     table,
                     cursor=None,
                     hshift=0,
                     sorting_col=None,
                     sorting_rev=False,
                     print_selector=False):
        '''
        Used by table-like plugins
        '''
        def format_row(element=None, raw=None, max_width=0, hshift=0):
            return self.format_table_row(
                element=element,
                raw=raw)[hshift:].ljust(max_width - 1)[:max_width - 1]

        self.window.move(0, 0)
        self.window.clrtobot()
        height, width = self.window.getmaxyx()
        table_custom_col_colors = hasattr(self, 'get_table_col_color')
        if table:
            h, tbl = rapidtables.format_table(table, fmt=2)
            header = (' ' if print_selector else '') + '  '.join(h)
            if sorting_col:
                if sorting_rev:
                    s = glyph.ARROW_UP
                else:
                    s = glyph.ARROW_DOWN
                if header.startswith(sorting_col + ' '):
                    header = header.replace(sorting_col + ' ', s + sorting_col,
                                            1)
                else:
                    header = header.replace(' ' + sorting_col, s + sorting_col)
            self.window.addstr(
                0, 0, format_row(raw=header, max_width=width, hshift=hshift),
                palette.HEADER)
            if table_custom_col_colors:
                cols = [len(x) for x in h]
                spaces = 2
                pos = 0
                col_starts = [0]
                for i in range(len(cols) - 1):
                    col_starts.append(cols[i] + pos + spaces)
                    pos += cols[i] + spaces
            for i, (t, r) in enumerate(zip(tbl, table)):
                spacer = '  '
                if print_selector:
                    t = (glyph.SELECTOR
                         if cursor == i else ' ') + spacer.join(t)
                else:
                    t = spacer.join(t)
                if table_custom_col_colors and cursor != i:
                    self.window.move(i + 1, 0)
                    rraw = t[hshift:hshift + width - 1]
                    limit = width - 1
                    for z, c in enumerate(r):
                        start = col_starts[z] - hshift
                        end = start + cols[z] + spaces
                        if end > 0:
                            val = r.get(c)
                            raw = rraw[start if start > 0 else 0:end]
                            if raw:
                                color = self.get_table_col_color(element=r,
                                                                 key=c,
                                                                 value=val)
                                self.render_table_col(
                                    raw,
                                    color if color else curses.A_NORMAL,
                                    element=r,
                                    key=c,
                                    value=val)
                                limit -= len(raw)
                            else:
                                break
                else:
                    self.window.addstr(
                        1 + i, 0,
                        format_row(element=r,
                                   raw=t,
                                   max_width=width,
                                   hshift=hshift),
                        palette.CURSOR if cursor == i else
                        (self.get_table_row_color(r, t) or palette.DEFAULT))
        else:
            self.print_empty_sep()
Ejemplo n.º 9
0
        'job': 'Architect'
    },
    {
        'name': 'Diana',
        'salary': None,
        'job': 'Student'
    },
    {
        'name': 'Ken',
        'salary': 1800,
        'job': 'Q/A'
    }
]

# colorize every single column
header, rows = format_table(data, fmt=2)
spacer = '  '
print(colored(spacer.join(header), color='blue'))
print(colored('-' * sum([(len(x) + 2) for x in header]), color='grey'))
for r in rows:
    print(colored(r[0], color='white', attrs=['bold']) + spacer, end='')
    print(colored(r[1], color='cyan') + spacer, end='')
    print(colored(r[2], color='yellow'))

print()

# colorize only rows
header, rows = format_table(data, fmt=1)
print(colored(header, color='blue'))
print(colored('-' * len(header), color='grey'))
for r in rows:
Ejemplo n.º 10
0
def ls(account=None,
       asset=None,
       tp=None,
       passive=None,
       start=None,
       end=None,
       tag=None,
       pending=True,
       hide_empty=False,
       order_by=['tp', 'asset', 'account', 'balance'],
       group_by=None,
       base=None):
    """
    Primary interactive function. Prints account statement if account code
    is specified, otherwise prints summary for all accounts

    Account code may contain '%' symbol as a wildcard.

    Args:
        account: account code
        asset: filter by asset code
        tp: filter by account type (or types)
        passive: list passive, active or all (if None) accounts
        start: start date (for statement), default: first day of current month
        end: end date (or balance date for summary)
        tag: filter transactions by tag (for statement)
        pending: include pending transactions
        hide_empty: hide empty accounts (for summary)
        order_by: column ordering (ordering by base is not supported)
        base: specify base asset
    """
    if account and account.find('%') != -1:
        code = account
        account = None
    else:
        code = None
    if account:
        result = account_statement_summary(
            account=account,
            start=start if start else datetime.datetime.today().replace(
                day=1, hour=0, minute=0, second=0, microsecond=0).timestamp(),
            end=end,
            tag=tag,
            pending=pending,
            datefmt=True)
        stmt = result['statement'].copy()
        acc_info = account_info(account=account)
        precision = asset_precision(asset=acc_info['asset'])
        for i, r in enumerate(stmt):
            r = r.copy()
            del r['is_completed']
            r['amount'] = format_money(r['amount'], precision)
            stmt[i] = r
        ft = rapidtables.format_table(
            stmt,
            fmt=rapidtables.FORMAT_GENERATOR,
            align=(rapidtables.ALIGN_LEFT, rapidtables.ALIGN_RIGHT,
                   rapidtables.ALIGN_LEFT, rapidtables.ALIGN_LEFT,
                   rapidtables.ALIGN_LEFT, rapidtables.ALIGN_LEFT,
                   rapidtables.ALIGN_LEFT))
        rcur = base.upper() if base else acc_info['asset']
        if ft:
            h, tbl = ft
            neotermcolor.cprint(h, '@finac:title')
            neotermcolor.cprint('-' * len(h), '@finac:separator')
            for t, s in zip(tbl, result['statement']):
                neotermcolor.cprint(
                    t,
                    '@finac:credit' if s['amount'] < 0 else '@finac:debit',
                    attrs='')
            neotermcolor.cprint('-' * len(h), '@finac:separator')
            print('Debit turnover: ', end='')
            neotermcolor.cprint(format_money(result['debit'], precision),
                                style='finac:debit_sum',
                                end=', ')
            print('credit turnover: ', end='')
            neotermcolor.cprint(format_money(result['credit'], precision),
                                style='finac:credit_sum')
            print()
            if base:
                precision = asset_precision(base)
            print('Net profit/loss: ', end='')
            pl = result['debit'] - result['credit']
            if base:
                pl = pl * asset_rate(acc_info['asset'], base, date=end)
            neotermcolor.cprint('{} {}'.format(format_money(pl, precision),
                                               rcur),
                                attrs='bold',
                                end='')
            print(', balance', end='')
        else:
            print('Balance', end='')
        balance = account_balance(account=account, date=end)
        if base:
            balance = balance * asset_rate(acc_info['asset'], base, date=end)
        print('{}: '.format(' to date' if end else ''), end='')
        neotermcolor.cprint('{} {}'.format(format_money(balance, precision),
                                           rcur),
                            attrs='bold',
                            end='')
        print()
    else:
        if not base:
            base = config.base_asset
        base = base.upper()
        result = account_list_summary(asset=asset,
                                      tp=tp,
                                      passive=passive,
                                      code=code,
                                      date=end,
                                      order_by=order_by,
                                      group_by=group_by,
                                      hide_empty=hide_empty,
                                      base=base)
        if not group_by:
            kf = 'accounts'
            rt_align = (rapidtables.ALIGN_LEFT, rapidtables.ALIGN_LEFT,
                        rapidtables.ALIGN_CENTER, rapidtables.ALIGN_CENTER,
                        rapidtables.ALIGN_RIGHT, rapidtables.ALIGN_RIGHT)
        elif group_by == 'asset':
            kf = 'assets'
            rt_align = (rapidtables.ALIGN_LEFT, rapidtables.ALIGN_RIGHT,
                        rapidtables.ALIGN_RIGHT)
        else:
            kf = 'account_types'
            rt_align = (rapidtables.ALIGN_LEFT, rapidtables.ALIGN_RIGHT)
        res = result[kf]
        data = res.copy()
        bcp = asset_precision(asset=base)
        for i, r in enumerate(res):
            r = r.copy()
            if group_by not in ['type', 'tp']:
                r['balance'] = format_money(r['balance'],
                                            asset_precision(asset=r['asset']))
            r['balance ' + base] = format_money(r['balance_bc'], bcp)
            del r['balance_bc']
            if not group_by:
                del r['note']
            if 'passive' in r:
                r['passive'] = 'P' if r['passive'] else ''
            res[i] = r
        ft = rapidtables.format_table(res,
                                      fmt=rapidtables.FORMAT_GENERATOR,
                                      align=rt_align)
        if not ft:
            return
        h, tbl = ft
        neotermcolor.cprint(h, '@finac:title')
        neotermcolor.cprint('-' * len(h), '@finac:separator')
        for t, s in zip(tbl, data):
            if s.get('passive'):
                style = 'finac:passive'
            else:
                style = 'finac:credit' if s['balance_bc'] < 0 else None
            neotermcolor.cprint(t, style=style, attrs='')
        neotermcolor.cprint('-' * len(h), '@finac:separator')
        neotermcolor.cprint('Total: ', end='')
        neotermcolor.cprint('{} {}'.format(format_money(result['total'], bcp),
                                           base),
                            style='finac:sum')
        print()
Ejemplo n.º 11
0
}, {
    'name': 'Ken',
    'salary': 1800,
    'job': 'Q/A'
}]

from rapidtables import format_table, print_table
from rapidtables import FORMAT_GENERATOR, FORMAT_GENERATOR_COLS
from rapidtables import ALIGN_LEFT, ALIGN_CENTER
from rapidtables import ALIGN_RIGHT, ALIGN_HOMOGENEOUS_NUMBERS_RIGHT

from termcolor import colored

# colorize every single column
header, rows = format_table(data,
                            fmt=FORMAT_GENERATOR_COLS,
                            align=ALIGN_HOMOGENEOUS_NUMBERS_RIGHT)
spacer = '  '
print(colored(spacer.join(header), color='blue'))
print(colored('-' * sum([(len(x) + 2) for x in header]), color='grey'))
for r in rows:
    cols = ((colored(r[0], color='white', attrs=['bold'])),
            (colored(r[1], color='cyan')), (colored(r[2], color='yellow')))
    print(spacer.join(cols))
print('')

# colorize only rows, custom header. may not work properly, use ordered dicts
# for input data rows
header, rows = format_table(data,
                            headers=('first name', 'income', 'position'),
                            fmt=FORMAT_GENERATOR)
Ejemplo n.º 12
0
    'job': 'Architect'
}, {
    'name': 'Diana',
    'salary': None,
    'job': 'Student'
}, {
    'name': 'Ken',
    'salary': 1800,
    'job': 'Q/A'
}]

from rapidtables import format_table, print_table
from termcolor import colored

# colorize every single column
header, rows = format_table(data, fmt=2)
spacer = '  '
print(colored(spacer.join(header), color='blue'))
print(colored('-' * sum([(len(x) + 2) for x in header]), color='grey'))
for r in rows:
    cols = ((colored(r[0], color='white', attrs=['bold'])),
            (colored(r[1], color='cyan')), (colored(r[2], color='yellow')))
    print(spacer.join(cols))
print('')

# colorize only rows, custom header. may not work properly, use ordered dicts
# for input data rows
header, rows = format_table(data,
                            headers=('first name', 'income', 'position'),
                            fmt=1)
print(colored(header, color='blue'))
Ejemplo n.º 13
0
            except IndexError:
                Print.colored("Add mins!", card_name)
            try:
                card_counts = Str.get_integers(card_time)[1]
            except IndexError:
                Print.colored("Add counts!", card_name)
        time.append({
            # "list_id": list_id,
            "list_name": list_name,
            "time": humanify_minutes(all_time),
            "task_count": task_count
            # "time_int": all_time
        })
        # Print("   ", list_name, list_id, f"\ttime: {all_time} mins")

header, rows = rapidtables.format_table(time,
                                        fmt=rapidtables.FORMAT_GENERATOR_COLS)
spacer = '  '
print("```")
print(spacer.join(header))
print('-' * sum([(len(x) + 2) for x in header]))
for row in rows:
    print(spacer.join(row))
print("```")

print()
if current_tasks:
    Print(f"Current tasks:")
    for task in current_tasks:
        Print(task["name"])
elif proposed_tasks:
    Print(f"Random task: {Random.item(proposed_tasks)['name']}")
Ejemplo n.º 14
0
    with tqdm(total=num * 6, desc=colored(str(rec).rjust(6),
                                          color='white')) as pbar:
        r_fixed = timeit.timeit(stmt=test_fixed_align, number=num) / num * 1000
        r_numbers = timeit.timeit(stmt=test_align_numbers,
                                  number=num) / num * 1000
        r_numbers_h = timeit.timeit(stmt=test_align_numbers_h,
                                    number=num) / num * 1000
        r_predefined = timeit.timeit(stmt=test_align_predefined,
                                     number=num) / num * 1000
        r_numbers_h_col_h = timeit.timeit(stmt=test_align_numbers_h_cols_h,
                                          number=num) / num * 1000
        r_all_fixed = timeit.timeit(stmt=test_all_fixed,
                                    number=num) / num * 1000
    nfmt = '{:.3f}'
    res = OrderedDict()
    res['records'] = rec
    res['align-f'] = nfmt.format(r_fixed)
    res['align-n'] = nfmt.format(r_numbers)
    res['num hom'] = nfmt.format(r_numbers_h)
    res['align-p'] = nfmt.format(r_predefined)
    res['all hom'] = nfmt.format(r_numbers_h_col_h)
    res['all fixed'] = nfmt.format(r_all_fixed)
    result.append(res)

header, rows = rapidtables.format_table(result,
                                        fmt=rapidtables.FORMAT_GENERATOR)
print(colored(header, color='blue'))
print(colored('-' * len(header), color='grey'))
for r in rows:
    print(colored(r, color='yellow'))
Ejemplo n.º 15
0
    'name': 'Ken',
    'salary': 1800,
    'job': 'Q/A'
}]

from rapidtables import format_table, print_table
from rapidtables import FORMAT_GENERATOR, FORMAT_GENERATOR_COLS
from rapidtables import ALIGN_LEFT, ALIGN_CENTER
from rapidtables import ALIGN_RIGHT, ALIGN_HOMOGENEOUS_NUMBERS_RIGHT
from rapidtables import MULTILINE_ALLOW, MULTILINE_EXTENDED_INFO

from termcolor import colored

# colorize every single column
header, rows = format_table(data,
                            fmt=FORMAT_GENERATOR_COLS,
                            align=ALIGN_HOMOGENEOUS_NUMBERS_RIGHT,
                            multiline=MULTILINE_ALLOW)
spacer = '  '
print(colored(spacer.join(header), color='blue'))
print(colored('-' * sum([(len(x) + 2) for x in header]), color='grey'))
for r in rows:
    cols = ((colored(r[0], color='white', attrs=['bold'])),
            (colored(r[1], color='cyan')), (colored(r[2], color='yellow')))
    print(spacer.join(cols))
print('')

# colorize only rows, custom header. may not work properly, use ordered dicts
# for input data rows
header, rows = format_table(data,
                            headers=('first name', 'income', 'position'),
                            fmt=FORMAT_GENERATOR,