Skip to content

Commit

Permalink
Working copy with graphics and tables.
Browse files Browse the repository at this point in the history
  • Loading branch information
weetabix committed Oct 23, 2016
1 parent 0eeaf8b commit 7e7fcd3
Show file tree
Hide file tree
Showing 2 changed files with 220 additions and 10 deletions.
101 changes: 101 additions & 0 deletions uomi/print_table.py
@@ -0,0 +1,101 @@
def print_table(items, header=None, wrap=True, max_col_width=20, wrap_style="wrap", row_line=False, fix_col_width=False):
''' Prints a matrix of data as a human readable table. Matrix
should be a list of lists containing any type of values that can
be converted into text strings.
Two different column adjustment methods are supported through
the *wrap_style* argument:
wrap: it will wrap values to fit max_col_width (by extending cell height)
cut: it will strip values to max_col_width
If the *wrap* argument is set to False, column widths are set to fit all
values in each column.
This code is free software. Updates can be found at
https://gist.github.com/jhcepas/5884168
'''

if fix_col_width:
c2maxw = dict([(i, max_col_width) for i in range(len(items[0]))])
# wrap = True
elif not wrap:
c2maxw = dict([(i, max([len(str(e[i])) for e in items])) for i in range(len(items[0]))])
else:
c2maxw = dict([(i, min(max_col_width, max([len(str(e[i])) for e in items])))
for i in range(len(items[0]))])
if header:
current_item = -1
row = header
if wrap and not fix_col_width:
for col, maxw in c2maxw.items():
c2maxw[col] = max(maxw, len(header[col]))
if wrap:
c2maxw[col] = min(c2maxw[col], max_col_width)
else:
current_item = 0
row = items[current_item]
while row:
is_extra = False
values = []
extra_line = [""]*len(row)
for col, val in enumerate(row):
cwidth = c2maxw[col]
wrap_width = cwidth
val = str(val)
try:
newline_i = val.index("\n")
except ValueError:
pass
else:
wrap_width = min(newline_i+1, wrap_width)
val = val.replace("\n", " ", 1)
if wrap and len(val) > wrap_width:
if wrap_style == "cut":
val = val[:wrap_width-1]+"+"
elif wrap_style == "wrap":
extra_line[col] = val[wrap_width:]
val = val[:wrap_width]
val = val.ljust(cwidth)
values.append(val)
print(' | '.join(values))
if not set(extra_line) - set(['']):
if header and current_item == -1:
print(' | '.join(['='*c2maxw[col] for col in range(len(row)) ]))
current_item += 1
try:
row = items[current_item]
except IndexError:
row = None
else:
row = extra_line
is_extra = True

if row_line and not is_extra and not (header and current_item == 0):
if row:
print(' | '.join(['-'*c2maxw[col] for col in range(len(row)) ]))
else:
print(' | '.join(['='*c2maxw[col] for col in range(len(extra_line)) ]))


print_table([[3, 2, "whadisdfasdfsdafsadfsadfsdfdsaever"], [5,"this dfsdfsdfasdfsadfsadfasdfs a test",777], [1,1,1]],
header=[ "number 1", "Column 2", "col3"],
wrap=True, max_col_width=15, wrap_style='wrap',
row_line=True, fix_col_width=True)


# This is column | Column number 2 | col3
# number 1 | |
# =============== | =============== | ===============
# 3 | 2 | {'bla': [1, 2],
# | | 'whatever': 1}
# --------------- | --------------- | ---------------
# 5 | this is a test | 777
# | of |
# | wrapping text |
# | with the new |
# | function |
# --------------- | --------------- | ---------------
# 1 | 1 | 1
# =============== | =============== | ===============
129 changes: 119 additions & 10 deletions uomi/uomi.py
Expand Up @@ -4,7 +4,7 @@
from datetime import datetime, timedelta
import os
import argparse

import textwrap
parser = argparse.ArgumentParser(description='A tool to manage debts and credits owed.\
The default behaviour is to list everything.')
parser.add_argument('-ad', '--add-debt',
Expand Down Expand Up @@ -34,7 +34,7 @@
def main():
"""Main is here so I can hide long ugly lists of SQL variables at the bottom."""
os.system('clear')
print('\nUoMi\n\n')
print('\nUoMi\n')
try:
cnx = mysql.connector.connect(user='uomi',
password='B9cSPPc73AKUSuX6',
Expand Down Expand Up @@ -68,8 +68,9 @@ def main():
print("type")
if args.type == "+D":
add_debt(cursor)
print_debt(cursor)
cnx.commit()
print_debt(cursor)

elif args.type == "+C":
add_credit(cursor)
print_credit(cursor)
Expand All @@ -84,11 +85,9 @@ def main():
cnx.commit()

else:
print("\n")
print('{:═^80}'.format(" Debts "))

print_debt(cursor)
print("\n")
print('{:═^80}'.format(" Credits "))
print("\n"*4)
print_credit(cursor)


Expand Down Expand Up @@ -155,13 +154,25 @@ def print_debt(in_cursor):
query = "SELECT `debt_no`, `date`, `name`, `type`, `value`, `barter`, `other`, `pay_date` FROM `debt` WHERE 1"
in_cursor.execute(query)
total = 0
row = 0
print("Debts\n")
for rec in in_cursor:
total += int(rec[4])
r = [str(rec[i]) for i in range(0, 8)] # Reordering the record too.
print('{} {} {} {:12} ${:5} {:16} {:16} {}'.format(r[0], r[1], r[3], r[2], r[4], r[5], r[6], r[7]))
if row == 0:
print_table(
[[r[0].zfill(3), r[1], r[7], r[2], r[4], r[5], r[6]], ],
header=["#", "Date", "Paydate", "Name", "Cash", "Barter", "Other"],
wrap=True, max_col_width=14, wrap_style='wrap',
row_line=False, fix_col_width=True)
row = 1
else:
print_table(
[[r[0].zfill(3), r[1], r[7], r[2], r[4], r[5], r[6]], ],
wrap=True, max_col_width=14, wrap_style='wrap',
row_line=False, fix_col_width=True)
print("Cash $" + str(total), "\n")


def add_credit(in_cursor):
"""Insert a credit I am owed into the database.
Repay time is calculated as slightly less than two days (160ksec)
Expand Down Expand Up @@ -201,10 +212,26 @@ def print_credit(in_cursor):
query = "SELECT `credit_no`, `date`, `name`, `type`, `value`, `barter`, `other`, `pay_date` FROM `credit` WHERE 1"
in_cursor.execute(query)
total = 0
row = 0
print("Credit\n")
for rec in in_cursor:
total += int(rec[4])
r = [str(rec[i]) for i in range(0, 8)] # Reordering the record too.
print('{} {} {} {:12} ${:5} {:16} {:16} {}'.format(r[0], r[1], r[3], r[2], r[4], r[5], r[6], r[7]))
if row == 0:
print_table(
[[r[0].zfill(3), r[1], r[7], r[2], r[4], r[5], r[6]], ],
header=["#", "Date", "Paydate", "Name", "Cash", "Barter", "Other"],
wrap=True, max_col_width=14, wrap_style='wrap',
row_line=False, fix_col_width=True)
row = 1
else:
print_table(
[[r[0].zfill(3), r[1], r[7], r[2], r[4], r[5], r[6]], ],
wrap=True, max_col_width=14, wrap_style='wrap',
row_line=False, fix_col_width=True)

# r = [str(rec[i]) for i in range(0, 8)] # Reordering the record too.
# print('{} {} {} {:12} ${:5} {:16} {:16} {}'.format(r[0], r[1], r[3], r[2], r[4], r[5], r[6], r[7]))
print("Cash $" + str(total), "\n")


Expand Down Expand Up @@ -235,4 +262,86 @@ def print_credit(in_cursor):
" PRIMARY KEY (`credit_no`)"
") ENGINE=MyISAM")


def print_table(items, header=None, wrap=True, max_col_width=20, wrap_style="wrap", row_line=False, fix_col_width=False):
""" Prints a matrix of data as a human readable table. Matrix
should be a list of lists containing any type of values that can
be converted into text strings.
Two different column adjustment methods are supported through
the *wrap_style* argument:
wrap: it will wrap values to fit max_col_width (by extending cell height)
cut: it will strip values to max_col_width
If the *wrap* argument is set to False, column widths are set to fit all
values in each column.
This code is free software. Updates can be found at
https://gist.github.com/jhcepas/5884168
"""
if fix_col_width:
c2maxw = dict([(i, max_col_width) for i in range(len(items[0]))])
wrap = True
elif not wrap:
c2maxw = dict([(i, max([len(str(e[i])) for e in items])) for i in range(len(items[0]))])
else:
c2maxw = dict([(i, min(max_col_width, max([len(str(e[i])) for e in items])))
for i in range(len(items[0]))])
if header:
current_item = -1
row = header
if wrap and not fix_col_width:
for col, maxw in c2maxw.items():
c2maxw[col] = max(maxw, len(header[col]))
if wrap:
c2maxw[col] = min(c2maxw[col], max_col_width)
else:
current_item = 0
row = items[current_item]
while row:
is_extra = False
values = []
extra_line = [""]*len(row)
for col, val in enumerate(row):
cwidth = c2maxw[col]
wrap_width = cwidth
val = str(val)
try:
newline_i = val.index("\n")
except ValueError:
pass
else:
wrap_width = min(newline_i+1, wrap_width)
val = val.replace("\n", " ", 1)
if wrap and len(val) > wrap_width:
if wrap_style == "cut":
val = val[:wrap_width-1]+"+"
elif wrap_style == "wrap":
extra_line[col] = val[wrap_width:]
val = val[:wrap_width]
val = val.ljust(cwidth)
values.append(val)
print(' │ '.join(values))
if not set(extra_line) - set(['']):
if header and current_item == -1:
print('═╪═'.join(['═'*c2maxw[col] for col in range(len(row)) ]))
current_item += 1
try:
row = items[current_item]
except IndexError:
row = None
else:
row = extra_line
is_extra = True

if row_line and not is_extra and not (header and current_item == 0):
if row:
print('?╪═'.join(['-'*c2maxw[col] for col in range(len(row)) ]))
else:
print('!╪═'.join(['═'*c2maxw[col] for col in range(len(extra_line)) ]))



main()

0 comments on commit 7e7fcd3

Please sign in to comment.