Example #1
0
def menu():
    phone_book = {}

    while True:
        print(yellow("\n1-Mostrar lista de contactos"))
        print(yellow("2-Añadir contacto (nombre y teléfono)"))
        print(yellow("3-Borrar contacto (nombre)"))
        print(yellow("4-Salir\n"))

        menu = input("¿Menú a elegir?: ")

        if menu == "1":
            show_contacts(phone_book)
        elif menu == "2":
            name = input(green("¿Contacto que desea añadir?: "))
            if name not in phone_book:
                phone = input(green("¿Número de contacto?: "))
                add_contact(phone_book, name, phone)
            else:
                print(red("ERROR: este contacto ya existe"))
        elif menu == "3":
            name = input(green("¿Contacto que desea eliminar?: "))
            remove_contact(phone_book, name)
        elif menu == "4":
            break
        else:
            print(red("ERROR: menú incorrecto!!"))
Example #2
0
def annotated_source(sourcefile, marks=None, annotations=None, context=3, mark='*'):

    marks = marks or []
    annotations = annotations or {}

    interresting = set(marks) | set(annotations)
    printed = [range(n - context, n + context + 1) for n in interresting]
    printed = set(sum(printed, []))

    lastprinted = 0
    with codecs.open(sourcefile, 'r', 'utf-8', 'replace') as f:
        print yellow(sourcefile)
        for n, line in enumerate(f, 1):
            if n in printed:
                m = red(mark if n in marks else ' ' * len(mark))
                c = line.rstrip().expandtabs()
                if n in marks:
                    c = red(c)
                if n in annotations:
                    a = yellow('# ' + annotations[n])
                else:
                    a = ''
                print '  %4i %s   %-80s %s' % (n, m, c, a)
                lastprinted = n
            elif lastprinted == n - 1:
                print bold(black('  %4s' % ('.' * len(str(n)))))
            else:
                pass
Example #3
0
def run_as_hook(filename, commitA=None, commitB=None, skip=False):
    """
    Runs in "hook" mode, called solely by git.

    filename: str
    commitA: str
    commitB: str
    skip: bool

    commitA and commitB exist /solely/ for profiling and testing
    """
    # Initialize new repo (called from git hook so this directory works)
    repo = git.Repo('.')

    if commitA is not None and commitB is not None:
        previous_commit = repo.commit(commitB)
        current_commit = repo.commit(commitA)
    else:
        previous_commit = repo.commit('HEAD~1')
        current_commit = repo.commit('HEAD')
    # Get specific changes in each file
    todos = []
    potential_todos = []
    for filediff in previous_commit.diff(current_commit, create_patch=True):
        # Find all modified lines in file
        for line in str(filediff).split('\n'):
            if re.match('^\+', line) and re.match('^\+\+\+', line) is None:
                clean_line = re.sub('^\+ *', '', line)
                if check_is_todo(clean_line):
                    todos.append((filediff.b_path, clean_line))
                elif check_is_potential_todo(clean_line):
                    potential_todos.append((filediff.b_path, clean_line))
    if todos:
        print(color.bold(color.yellow(
            "Here's a list of TODOs you added in this commit:\n"
            "------------------------------------------------")))
        with open(filename, 'a') as todofile:
            for todo in todos:
                print('+ {} | {}'.format(*todo))
                check_date_and_save(todofile, todo[0], todo[1])
    if potential_todos:  # TODO: test
        print(color.bold(color.yellow(
            "These might be TODOs.  Did you mean to do them?\n"
            "-----------------------------------------------")))
        with open(filename, 'a') as todofile:
            for todo in potential_todos:
                if skip:
                    choice = 'n'
                else:
                    choice = input('+ {} | {} (y/N) '.format(*todo))
                if choice.lower() == 'y':
                    check_date_and_save(todofile, todo[0], todo[1])
    print('')
Example #4
0
def run_as_hook(filename, commitA=None, commitB=None):
    """
    Runs in "hook" mode, called solely by git.

    filename: str
    commitA: str
    commitB: str

    commitA and commitB exist /solely/ for profiling and testing
    """
    # Initialize new repo (called from git hook so this directory works)
    repo = git.Repo('.')

    if commitA is not None and commitB is not None:
        previous_commit = repo.commit(commitB)
        current_commit = repo.commit(commitA)
    else:
        previous_commit = repo.commit('HEAD~1')
        current_commit = repo.commit('HEAD')
    # Get specific changes in each file
    todos = []
    potential_todos = []
    for filediff in previous_commit.diff(current_commit, create_patch=True):
        # Find all modified lines in file
        for line in str(filediff).split('\n'):
            if re.match('^\+', line) and re.match('^\+\+\+', line) is None:
                clean_line = re.sub('^\+ *', '', line)
                if check_is_todo(clean_line):
                    todos.append((filediff.b_path, clean_line))
                elif check_is_potential_todo(clean_line):
                    potential_todos.append((filediff.b_path, clean_line))
    if todos:
        print(
            color.bold(
                color.yellow(
                    "Here's a list of TODOs you added in this commit:\n"
                    "------------------------------------------------")))
        for todo in todos:
            print('+ {} | {}'.format(*todo))
            check_date_and_save(filename, todo[0], todo[1])
    if potential_todos:
        print(
            color.bold(
                color.yellow(
                    "\n"
                    "These might be TODOs.  Did you mean to do them?\n"
                    "-----------------------------------------------")))
        for todo in potential_todos:
            print('+ {} | {}'.format(*todo))
            check_date_and_save(filename, todo[0], todo[1])
    print('')
Example #5
0
def clean(items):
    for name, props in items:
        # only attempt if the clean method exists
        if props["clean"]:
            print
            print "clean: %s" % (cyan(name))
            print "-"*30

            # move to this files parent directory and then to the bundle directory
            os.chdir(dirname + "/..")
            os.chdir(props["dir"])

            print yellow(props["clean"])
            subprocess.call(props["clean"].split())
Example #6
0
    def _printNode(self,
                   key,
                   val,
                   padding='',
                   last=False,
                   maxdepth=None,
                   maxcount=None):
        from fabulous.color import highlight_blue, red, blue, green, cyan, yellow, bold
        from tables import Array

        if isinstance(val, H5Node):
            val.printTree(padding=padding,
                          last=last,
                          maxdepth=maxdepth,
                          maxcount=maxcount)
        else:
            if isinstance(val, Array):
                val = yellow('Array(%s,__dtype__=%s)' %
                             (','.join(str(i) for i in val.shape), val.dtype))
            elif isinstance(val, Table):
                val = green(val)
            else:
                val = red('%s,__dtype__=%s' % (str(val), type(val).__name__))
            if last:
                print '%s `%s [%s]' % (padding[:-1], cyan(key), val)
            else:
                print '%s`%s [%s]' % (padding, cyan(key), val)
Example #7
0
def make(items):
    for name, props in items:
        print
        print "make: %s" % (cyan(name))
        print "-"*30

        # move to this files parent directory and then to the bundle directory
        os.chdir(dirname + "/..")
        os.chdir(props["dir"])

        for cmd in props["make"]:
            print yellow(cmd)
            c = subprocess.call(cmd_gen(cmd))
            if c != 0:
                print red("Error encountered (%s: %s)" % (cyan(name), yellow(cmd)))
                sys.exit()
Example #8
0
 def diff_all_table_data(self):
     failures = 0
     print(bold(red('Starting table analysis.')))
     with warnings.catch_warnings():
         warnings.simplefilter("ignore", category=sa_exc.SAWarning)
         tables = sorted(
             self.firstinspector.get_table_names(schema="public"))
         for table in tables:
             if table in self.exclude_tables:
                 print(bold(yellow(f"Ignoring table {table}")))
                 continue
             with Halo(text=f"Analysing table {table}. "
                       f"[{tables.index(table) + 1}/{len(tables)}]",
                       spinner='dots') as spinner:
                 result, message = self.diff_table_data(table)
                 if result is True:
                     spinner.succeed(f"{table} - {message}")
                 elif result is None:
                     spinner.warn(f"{table} - {message}")
                 else:
                     failures += 1
                     spinner.fail(f"{table} - {message}")
     print(bold(green('Table analysis complete.')))
     if failures > 0:
         return 1
     return 0
Example #9
0
    def _printNode(self, key, val, padding= '', last=False,maxdepth=None,maxcount=None):
        from fabulous.color import highlight_blue,red,blue,green,cyan,yellow,bold
        from tables import Array

        if isinstance(val,H5Node):
            val.printTree(padding=padding,last=last,maxdepth=maxdepth,maxcount=maxcount)
        else:
            if isinstance(val,Array):
                val = yellow('Array(%s,__dtype__=%s)'% (','.join(str(i) for i in val.shape),val.dtype))
            elif isinstance(val,Table):
                val = green(val)
            else:
                val = red('%s,__dtype__=%s' % (str(val),type(val).__name__))
            if last:
                print '%s `%s [%s]' % (padding[:-1], cyan(key), val )
            else:
                print '%s`%s [%s]' % (padding, cyan(key), val )
Example #10
0
 def yellow(self):
     return ansi(c.yellow(self.txt))
Example #11
0
import requests
import os
import sys
from fabulous import text
try:
    from BeautifulSoup import BeautifulSoup
except ImportError:
    from bs4 import BeautifulSoup
from humanfriendly.tables import format_pretty_table
from fabulous.color import highlight_green, green, red, yellow

baku_header = [
    highlight_green('Qatar №-si'.decode("utf-8").strip()),
    green('Bakıdan çıxma'.decode("utf-8").strip()),
    green('Biləcəriyə çatma'.decode("utf-8").strip()),
    yellow('Biləcəridən getmə'.decode("utf-8").strip()),
    yellow('Xırdalana çatma'.decode("utf-8").strip()),
    red('Xırdalandan getmə'.decode("utf-8").strip()),
    red('Sumqayıta çatma'.decode("utf-8").strip())
]

sum_header = [
    highlight_green('Qatar №-si'.decode("utf-8").strip()),
    green('Sumqayıtdan çıxma'.decode("utf-8").strip()),
    green('Xırdalana çatma'.decode("utf-8").strip()),
    yellow('Xırdalana getmə'.decode("utf-8").strip()),
    yellow('Biləcəriyə çatma'.decode("utf-8").strip()),
    red('Biləcəriyə getmə'.decode("utf-8").strip()),
    red('Bakıya çatma'.decode("utf-8").strip())
]
Example #12
0
#!/usr/bin/env python

"""Colour theme for terminals which support only 8-bit colors.
"""

from fabulous import color as col

messagefmt = {
	None: '{asctime} {module} {levelname} {msg}'.format(
		asctime=col.highlight_blue('{r.asctime}'),
		module=col.cyan(('{r.module}')),
		levelname=col.cyan('{r.levelname}'),
		msg=col.bold(col.yellow('{r.msg}')),
		),

	'INFO': '{asctime} {module} {levelname} {msg}'.format(
		asctime=col.highlight_blue('{r.asctime}'),
		module=col.cyan(('{r.module}')),
		levelname=col.green('{r.levelname}'),
		msg=col.bold(col.yellow('{r.msg}')),
		),

	'WARNING': '{asctime} {module} {levelname} {msg}'.format(
		asctime=col.highlight_blue('{r.asctime}'),
		module=col.cyan(('{r.module}')),
		levelname=col.bold(col.magenta('{r.levelname}')),
		msg=col.bold(col.yellow('{r.msg}')),
		),

	'ERROR': '{asctime} {module} {levelname} {msg}'.format(
		asctime=col.highlight_blue('{r.asctime}'),