示例#1
0
def test_py2():
    """Test python2.x methods."""
    value = Color("{red}this is a test.{/red}")

    assert "\033[31m \033[39m" == Color("{red} {/red}", "latin-1")
    assert "\033[31mabc\033[39m" == Color("{red}\x80abc{/red}", errors="ignore")

    assert "\033[31mthis is a test.\033[39m" == value.decode()
    assert "\033[31mth3s 3s 1 t2st.\033[39m" == value.translate(string.maketrans("aeioum", "123456").decode("latin-1"))
示例#2
0
def test_py2():
    """Test python2.x methods."""
    value = Color('this is a test.')

    assert ' ' == Color(' ', 'latin-1')
    assert 'abc' == Color('\x80abc', errors='ignore')

    assert 'this is a test.' == value.decode()
    assert 'th3s 3s 1 t2st.' == value.translate(string.maketrans('aeiou', '12345').decode('latin-1'))
示例#3
0
def test_all(image_output=False, container_output=False):
    results = []
    for dirname in os.listdir(__dir__):
        if not os.path.isdir(dirname):
            continue
        try:
            test_image(dirname, image_output=image_output, container_output=container_output)
        except ChildProcessError:
            results.append(False)
        else:
            results.append(True)
    print('-' * 60)
    print('PASSED: {} {}/{}'.format(
        ''.join([{False: Color.red('F'), True: Color.green('.')}[x] for x in results]),
        len(list(filter(lambda x: x, results))), len(results)
    ))
示例#4
0
def test_py3():
    """Test python3.x methods."""
    value = Color("{red}this is a test.{/red}")

    if hasattr(Color, "casefold"):
        assert "\033[31mss\033[39m" == Color("{red}ß{/red}").casefold()

    actual = Color("{red}{name} was born in {country}{/red}").format_map(_Default(name="Guido"))
    assert "\033[31mGuido was born in country\033[39m" == actual

    assert not Color("{red}var{/red}").isidentifier()
    assert not Color("var-").isidentifier()
    assert not Color("{red}var{/red}").isprintable()
    assert not Color("{red}\0{/red}").isprintable()

    assert "\033[31mth3s 3s 1 t2st.\033[39m" == value.translate(Color.maketrans("aeiou", "12345"))
示例#5
0
def test_py3():
    """Test python3.x methods."""
    value = Color('this is a test.')

    # assert '' == Color(b'', 'latin-1')  bytes has no .format().
    # assert 'abc' == Color(b'\x80abc', errors='ignore')

    if hasattr(Color, 'casefold'):
        assert 'ss' == Color('ß').casefold()

    assert 'Guido was born in country' == Color('{name} was born in {country}').format_map(_Default(name='Guido'))

    assert Color('var').isidentifier()
    assert not Color('var-').isidentifier()
    assert Color('var').isprintable()
    assert not Color('\0').isprintable()

    assert 'th3s 3s 1 t2st.' == value.translate(Color.maketrans('aeiou', '12345'))
示例#6
0
def colorize(color, text, auto=True):
    """
    A simple override of Color.colorize which sets the default auto colors value to True, since it's the more common
    use case.
    :param color: Color tag to use
    :param text: Text to color
    :param auto: Whether to apply auto colors
    :return: Colored text
    """
    return Color.colorize(color, text, auto)
示例#7
0
def colorize(color, text, auto=True):
    """
    A simple override of Color.colorize which sets the default auto colors value to True, since it's the more common
    use case. When output isn't TTY just return text

    :param color: Color tag to use
    :param text: Text to color
    :param auto: Whether to apply auto colors

    :return: Colored text or text
    """
    if not terminal_info()['isatty']:
        return text
    return Color.colorize(color, text, auto)
示例#8
0
def printLoad(desc):
    print(Color("-- {white}Loading{/white} {green}" + desc +
                "{/green} {white}test{/white}"))
示例#9
0
def invalidExpectedDataKey(key, conf):
    conf['errors'].append(Color(
        "invalid expected data key {yellow}" + key + "{/yellow}. " +
        "They is no property with this name in server's response."))
示例#10
0
def verifyNode(namespace, msg):
    print(Color("{white} [TEST] " + str(namespace) + "{/white} " + msg))
示例#11
0
def validationError(conf):
    errors = conf['errors']
    for msg in errors:
        print(Color("{red} [FAIL] {/red} Validation error: " + msg))
    conf['errors'] = []
示例#12
0
def printStep(desc):
    print(Color("{green}" + desc + "{/green}"))
示例#13
0
文件: LCS_bot.py 项目: mohamad007/csd
#!/usr/bin/env python3

#################################################
#                    IMPORTS                    #
#################################################
from colorclass import Color

print(Color(
    '{autored}[{/red}{autoyellow}+{/yellow}{autored}]{/red} {autocyan}Cargando plugins...{/cyan}'))

from config import *
import importdir
import sys

#################################################
#                    BOT BODY                   #
#################################################

if sys.version_info.major < 3:
    raise Exception("Must be using Python 3")

importdir.do('plugins', globals())

print(Color(
    '{autored}[{/red}{autoyellow}+{/yellow}{autored}]{/red} {autocyan}Plugins cargados.{/cyan}'))


try:
    bot.send_message(52033876, "@League_of_Legends_bot ha sido encendido")
except Exception as e:
    bot.send_message(52033876, str(e))
示例#14
0
def test_common():
    """Test common string methods."""
    value = Color("{red}this is a test.{/red}")

    assert Color("{red}this is a test.{/red}") == value
    assert Color("\033[31mthis is a test.\033[39m") == value
    assert 15 == len(value)
    assert "\033[31mthis is a test.\033[39m" == "{0}".format(value)

    assert "\033[31mThis is a test.\033[39m" == value.capitalize()
    assert "  \033[31mthis is a test.\033[39m   " == value.center(20)
    assert "@@\033[31mthis is a test.\033[39m@@@" == value.center(20, "@")
    assert 2 == value.count("is")
    assert 2 == Color("{red}I love m&ms{/red}").count("m")
    assert value.endswith("test.")
    assert "    \033[31mclass\033[39m" == Color("\t{red}class{/red}").expandtabs(4)
    assert 8 == value.find("a")
    assert 7 == Color("{red}I love m&ms{/red}").find("m")
    assert "\033[31mtest 123\033[39m" == Color("{red}test {0}{/red}").format("123")
    assert 8 == value.index("a")
    assert 7 == Color("{red}I love m&ms{/red}").index("m")

    assert Color("{red}a1{/red}").isalnum()
    assert not Color("{red}a1.{/red}").isalnum()
    assert Color("{red}a{/red}").isalpha()
    assert not Color("{red}a1{/red}").isalpha()
    assert Color("{red}1").isdecimal()
    assert not Color(u"{red}⅕{/red}").isdecimal()
    assert Color(u"{red}²{/red}").isdigit()
    assert not Color(u"{red}⅕{/red}").isdigit()
    assert Color("{red}a{/red}").islower()
    assert not Color("{red}A{/red}").islower()
    assert Color(u"{red}⅕{/red}").isnumeric()
    assert not Color("{red}A{/red}").isnumeric()
    assert Color("{red}    {/red}").isspace()
    assert not Color("{red}    x{/red}").isspace()
    assert Color("{red}I Love To Test{/red}").istitle()
    assert not Color("{red}I Love to Test{/red}").istitle()
    assert Color("{red}A{/red}").isupper()
    assert not Color("{red}a{/red}").isupper()

    assert "test\033[0mtest" == Color("{/all}").join(("test", "test"))
    assert "\033[31mthis is a test.\033[39m     " == value.ljust(20)
    assert "\033[31ma\033[39m" == Color("{red}A{/red}").lower()
    assert "\033[31ma\033[39m " == Color(" {red}a{/red} ").lstrip()
    assert "\033[31m a \033[39m" == Color("{red} a {/red}").lstrip()
    assert ("\033[31mthis", " ", "is a test.\033[39m") == value.partition(" ")
    assert "\033[31mthis was a test.\033[39m" == value.replace(" is ", " was ")
    assert 13 == value.rfind("t")
    assert 13 == value.rindex("t")
    assert "     \033[31mthis is a test.\033[39m" == value.rjust(20)
    assert ("\033[31mthis is a", " ", "test.\033[39m") == value.rpartition(" ")
    assert ["\033[31mthis is a", "test.\033[39m"] == value.rsplit(" ", 1)
    assert " \033[31ma\033[39m" == Color(" {red}a{/red} ").rstrip()
    assert "\033[31m a \033[39m" == Color("{red} a {/red}").rstrip()
    assert ["\033[31mthis", "is", "a", "test.\033[39m"] == value.split(" ")

    values = Color("{red}a{/red}\n{green}a{/green}").splitlines()
    assert ["\033[31ma\033[39m", "\033[32ma\033[39m"] == values
    assert [1, 1] == [len(i) for i in values]

    assert value.startswith("this")
    assert "\033[31ma\033[39m" == Color(" {red}a{/red} ").strip()
    assert "\033[31m a \033[39m" == Color("{red} a {/red}").strip()
    assert "\033[31mAa\033[39m" == Color("{red}aA{/red}").swapcase()
    assert "\033[31mThis Is A Test.\033[39m" == value.title()
    assert "\033[31mTHIS IS A TEST.\033[39m" == value.upper()
    assert "\033[31m000001\033[39m" == Color("{red}1{/red}").zfill(6)
    assert "00001\033[31m1\033[39m" == Color("1{red}1{/red}").zfill(6)
示例#15
0
def test_common():
    """Test common string methods."""
    value = Color('this is a test.')

    assert '' == Color()
    assert 15 == len(value)
    assert 'this is a test.' == '{0}'.format(value)

    assert 'This is a test.' == value.capitalize()
    assert '  this is a test.   ' == value.center(20)
    assert '@@this is a test.@@@' == value.center(20, '@')
    assert 2 == value.count('is')
    assert value.endswith('test.')
    assert '    class' == Color('\tclass').expandtabs(4)
    assert 8 == value.find('a')
    assert 'test 123' == Color('test {0}').format('123')
    assert 8 == value.index('a')

    assert Color('a1').isalnum()
    assert not Color('a1.').isalnum()
    assert Color('a').isalpha()
    assert not Color('a1').isalpha()
    assert Color('1').isdecimal()
    assert not Color(u'⅕').isdecimal()
    assert Color(u'²').isdigit()
    assert not Color(u'⅕').isdigit()
    assert Color('a').islower()
    assert not Color('A').islower()
    assert Color(u'⅕').isnumeric()
    assert not Color('A').isnumeric()
    assert Color('    ').isspace()
    assert not Color('    x').isspace()
    assert Color('I Love To Test').istitle()
    assert not Color('I Love to Test').istitle()
    assert Color('A').isupper()
    assert not Color('a').isupper()

    assert 'test test' == Color(' ').join(('test', 'test'))
    assert 'this is a test.     ' == value.ljust(20)
    assert 'a' == Color('A').lower()
    assert 'a ' == Color(' a ').lstrip()
    assert ('this', ' ', 'is a test.') == value.partition(' ')
    assert 'this was a test.' == value.replace(' is ', ' was ')
    assert 13 == value.rfind('t')
    assert 13 == value.rindex('t')
    assert '     this is a test.' == value.rjust(20)
    assert ('this is a', ' ', 'test.') == value.rpartition(' ')
    assert ['this is a', 'test.'] == value.rsplit(' ', 1)
    assert ' a' == Color(' a ').rstrip()
    assert ['this', 'is', 'a', 'test.'] == value.split(' ')
    assert ['a', 'a'] == Color('a\na').splitlines()
    assert [1, 1] == [len(i) for i in Color('a\na').splitlines()]
    assert value.startswith('this')
    assert 'a' == Color(' a ').strip()
    assert 'Aa' == Color('aA').swapcase()
    assert 'This Is A Test.' == value.title()
    assert 'THIS IS A TEST.' == value.upper()
    assert '000001' == Color('1').zfill(6)
    assert '000000' == Color().zfill(6)
        os.system("cls||clear")
        print(start)
        dict_failed_check_old = get_failed_check_path(path2)
        # print(dict_failed_check_old, 'old_dict')
        dict_failed_check_result = get_list_failed_device(
            dict_failed_check_cur, dict_failed_check_old)
        # print(dict_failed_check_result, 'dict_result')
        print(create_table(dict_devices, dict_failed_check_result))
        with open(path2, "w"
                  ) as f:  # заполняем словарь с ранее проблемными устройствами
            for key in dict_failed_check_result:
                f.writelines('{0};{1}\r\n'.format(
                    key, dict_failed_check_result.get(key)))
        end = datetime.datetime.now()
        delta = "{autored}" + str(end - start) + "{/autored}"
        print(Color(delta))
        print(
            Color("{{{0}}}{1}{{/{0}}} - main path".format(
                "autogreen", "Color")))
        print(
            Color("{{{0}}}{1}{{/{0}}} - backup path".format(
                "autoyellow", "Color")))
        print(
            Color("{{{0}}}{1}{{/{0}}} - Internet or not in the file paths".
                  format("autowhite", "Color")))
        dict_failed_check_cur.clear()
        dict_failed_check_result.clear()
        dict_failed_check_old.clear()
        dict_devices.clear()
        time.sleep(10)
示例#17
0
def list_launches(f, format):
    manifest = manifest_utils.load(f)
    if format == "table":
        click.echo("Getting details from your account...")
    all_regions = config.get_regions(os.environ.get("AWS_DEFAULT_REGION"))
    account_ids = [a.get('account_id') for a in manifest.get('accounts')]
    deployments = {}
    for account_id in account_ids:
        for region_name in all_regions:
            role = "arn:aws:iam::{}:role/{}".format(
                account_id, 'servicecatalog-puppet/PuppetRole')
            logger.info("Looking at region: {} in account: {}".format(
                region_name, account_id))
            with betterboto_client.CrossAccountClientContextManager(
                    'servicecatalog',
                    role,
                    'sc-{}-{}'.format(account_id, region_name),
                    region_name=region_name) as spoke_service_catalog:
                response = spoke_service_catalog.list_accepted_portfolio_shares(
                )
                portfolios = response.get('PortfolioDetails', [])
                response = spoke_service_catalog.list_portfolios()
                portfolios += response.get('PortfolioDetails', [])

                for portfolio in portfolios:
                    portfolio_id = portfolio.get('Id')
                    response = spoke_service_catalog.search_products_as_admin(
                        PortfolioId=portfolio_id)
                    for product_view_detail in response.get(
                            'ProductViewDetails', []):
                        product_view_summary = product_view_detail.get(
                            'ProductViewSummary')
                        product_id = product_view_summary.get('ProductId')
                        response = spoke_service_catalog.search_provisioned_products(
                            Filters={
                                'SearchQuery':
                                ["productId:{}".format(product_id)]
                            })
                        for provisioned_product in response.get(
                                'ProvisionedProducts', []):
                            launch_name = provisioned_product.get('Name')
                            status = provisioned_product.get('Status')

                            provisioning_artifact_response = spoke_service_catalog.describe_provisioning_artifact(
                                ProvisioningArtifactId=provisioned_product.get(
                                    'ProvisioningArtifactId'),
                                ProductId=provisioned_product.get('ProductId'),
                            ).get('ProvisioningArtifactDetail')

                            if deployments.get(account_id) is None:
                                deployments[account_id] = {
                                    'account_id': account_id,
                                    constants.LAUNCHES: {}
                                }

                            if deployments[account_id][constants.LAUNCHES].get(
                                    launch_name) is None:
                                deployments[account_id][
                                    constants.LAUNCHES][launch_name] = {}

                            deployments[account_id][constants.LAUNCHES][
                                launch_name][region_name] = {
                                    'launch_name':
                                    launch_name,
                                    'portfolio':
                                    portfolio.get('DisplayName'),
                                    'product':
                                    manifest.get(constants.LAUNCHES,
                                                 {}).get(launch_name,
                                                         {}).get('product'),
                                    'version':
                                    provisioning_artifact_response.get('Name'),
                                    'active':
                                    provisioning_artifact_response.get(
                                        'Active'),
                                    'region':
                                    region_name,
                                    'status':
                                    status,
                                }
                            output_path = os.path.sep.join([
                                constants.LAUNCHES_PATH,
                                account_id,
                                region_name,
                            ])
                            if not os.path.exists(output_path):
                                os.makedirs(output_path)

                            output = os.path.sep.join([
                                output_path,
                                "{}.json".format(provisioned_product.get('Id'))
                            ])
                            with open(output, 'w') as f:
                                f.write(
                                    json.dumps(provisioned_product,
                                               indent=4,
                                               default=str))

    results = {}
    tasks = generate_tasks(f)
    # deployments[account_id][constants.LAUNCHES][launch_name][region_name]
    for task in tasks:
        account_id = task.get('account_id')
        launch_name = task.get('launch_name')
        if deployments.get(account_id, {}).get(constants.LAUNCHES,
                                               {}).get(launch_name) is None:
            pass
        else:
            for region, regional_details in deployments[account_id][
                    constants.LAUNCHES][launch_name].items():
                results[f"{account_id}_{region}_{launch_name}"] = {
                    'account_id': account_id,
                    'region': region,
                    'launch': launch_name,
                    'portfolio': regional_details.get('portfolio'),
                    'product': regional_details.get('product'),
                    'expected_version': task.get('version'),
                    'actual_version': regional_details.get('version'),
                    'active': regional_details.get('active'),
                    'status': regional_details.get('status'),
                }

    if format == "table":
        table = [[
            'account_id',
            'region',
            'launch',
            'portfolio',
            'product',
            'expected_version',
            'actual_version',
            'active',
            'status',
        ]]

        for result in results.values():
            table.append([
                result.get('account_id'),
                result.get('region'),
                result.get('launch'),
                result.get('portfolio'),
                result.get('product'),
                result.get('expected_version'),
                Color("{green}" + result.get('actual_version') + "{/green}") if
                result.get('actual_version') == result.get('expected_version')
                else Color("{red}" + result.get('actual_version') + "{/red}"),
                Color("{green}" + str(result.get('active')) +
                      "{/green}") if result.get('active') else
                Color("{red}" + str(result.get('active')) + "{/red}"),
                Color("{green}" + result.get('status') +
                      "{/green}") if result.get('status') == "AVAILABLE" else
                Color("{red}" + result.get('status') + "{/red}")
            ])
        click.echo(terminaltables.AsciiTable(table).table)

    elif format == "json":
        click.echo(json.dumps(
            results,
            indent=4,
            default=str,
        ))

    else:
        raise Exception(f"Unsupported format: {format}")
示例#18
0
def handler(signum, frame):
    print(Color('\n{autogreen}Bye bye!{/autogreen}'))
    exit()
示例#19
0
 def add_bot_cell(data, cell):
     data.append([len(data), Color(cell), "", ""])
示例#20
0
文件: entry.py 项目: homonoid/apparat
def error(message):
    head = Color('{autored}=== SORRY! ==={/red}')
    print(f'\033[1;m{head}\033[0m\n{message}\n')
示例#21
0
def printDepError(id_orig, id_missing, execx, errno=1):
    print(Color("-- {red}Dependecy Error:{/red} {white} from id::" +
                id_orig + "; " + execx + "->{/white}{yellow}" + id_missing +
                "{/yellow}: {white}id does not exist!{/white}"))
    sys.exit(errno)
示例#22
0
def dash_if_none(item=None):
    """
    @type item: object
    """
    return str(item) if item else Color('{autoblack}-{/autoblack}')
示例#23
0
def printDeps(desc):
    print(Color("-- {white}Checking{/white} {green}" + desc +
                "{/green} {white}test{/white}"))
            prefix = ch * prefix_len
            suffix = ch * suffix_len
        else:
            prefix = ch * (prefix_len / len(ch)) + ch[:prefix_len % len(ch)]
            suffix = ch * (suffix_len / len(ch)) + ch[:suffix_len % len(ch)]
        return prefix + ' ' + text + ' ' + suffix


if __name__ == '__main__':
    from colorclass import Color
    print (Color(u'''{autoyellow}
     _____ _            __      _                  _
    /__   \ |__   ___  /__\_  _| |_ _ __ __ _  ___| |_ ___  _ __
      / /\/ '_ \ / _ \/_\ \ \/ / __| '__/ _` |/ __| __/ _ \| '__|
     / /  | | | |  __//__  >  <| |_| | | (_| | (__| || (_) | |
     \/   |_| |_|\___\__/ /_/\_\\\__|_|  \__,_|\___|\__\___/|_|

    {/autoyellow}
                                {autowhite}Developed and designed by Lazaar Sami
                                inspired by adisenum.rb, http://h.foofus.net/goons/n8/tools/exchange/{/autowhite}
                                {autogreen}[email protected]{/autogreen}
    '''))
    print(banner("An Exchange Autodiscovery Domain User IDs grabber",ch='*', length=70))
    print(Color(u'''
    {autowhite}This tool extracts domain users ID by using an email address dictionary
    and exploiting a flaw in the Autodiscovery service of the Exchange server.{/autowhite}
    Ref:Microsoft Exchange Autodiscover User Account Enumeration Information Disclosure.
    '''))
    print(Color('{autoyellow}[+]{/autoyellow} Loading external modules...'))
    import signal
    import requests
    from urlparse import urlparse
示例#25
0
def validationOk(conf):
    print(Color("{green} [PASS] {/green} Validation passed"))
示例#26
0
print "\n\n\n\n"

####################################################################################

# INPUT STRING
coin = raw_input("Name coin is : ")
nb_coins_string = raw_input("How many coins : ")

# SI VIDE
if not nb_coins_string:

    os.system('cls' if os.name == 'nt' else 'clear')

    print "\n\n"
    print Color("{autored}Put your coins amount or put 0{/autored}")
    print "\n\n"

# CONVERSION STRING -> FLOAT
nb_coins = float(nb_coins_string)

####################################################################################


def cours_coins():

    table_data = [[
        'Cours ' + coin + ' --> $', 'Cours ' + coin + ' --> EURO',
        'Cours ' + coin + ' --> SATOSHIS'
    ],
                  [
示例#27
0
def invalidOperator(op, msg, conf):
    conf['errors'].append(Color("{yellow} [INVL] invalid operator {red}" +
                                op + "{/red}{/yellow}: " + msg))
示例#28
0
文件: es.py 项目: kalaiser/acli
def colour_created(state=None):
    if not state:
        return Color('{autoyellow}False{/autoyellow}')
    else:
        return Color('{autogreen}True{/autogreen}')
示例#29
0
def debug(msg):
    print(Color("{yellow} [DEBUG] {/yellow} " + msg))
示例#30
0
文件: es.py 项目: kalaiser/acli
def colour_deleted(state=None):
    if not state:
        return Color('{autogreen}False{/autogreen}')
    else:
        return Color('{autored}True{/autored}')
示例#31
0
 def add_user_cell(data, cell):
     data.append([len(data), "", "", Color(cell)])
示例#32
0
文件: es.py 项目: kalaiser/acli
def colour_processing(state=None):
    if not state:
        return Color('{autogreen}False{/autogreen}')
    else:
        return Color('{autoyellow}True{/autoyellow}')
def create_table(dict_devices, dict_failed_check_result):
    """
    Функция для создания отрисовки таблицы
    Function for creating a table
    """
    table_data = []
    table_data_temp = []
    hostname = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "HOSTNAME")
    status = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "STATUS")
    lost = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "LOST")
    aver_delay = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "AVERAGE DELAY")
    max_delay = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "MAXIMUM DELAY")
    date = "{{{0}}}{1}{{/{0}}}".format("autoyellow", "DATE")
    table_data.append([
        Color(hostname),
        Color(status),
        Color(lost),
        Color(aver_delay),
        Color(max_delay),
        Color(date)
    ])
    for key in dict_devices:
        hostname = key
        status = dict_devices.get(key)[0]
        lost = dict_devices.get(key)[1]
        aver_delay = dict_devices.get(key)[2]
        max_delay = dict_devices.get(key)[3]
        color = int(dict_devices.get(key)[4])
        if status == "FAILD":
            hostname = "{autored}" + hostname + "{/autored}"
            status = "{autored}" + status + "{/autored}"
            lost = "{autored}" + lost + "{/autored}"
            aver_delay = max_delay = '{autored}0{/autored}'
            date = "{autored}" + dict_failed_check_result.get(
                key) + "{/autored}"
            table_data_temp.append([
                Color(hostname),
                Color(status),
                Color(lost),
                Color(aver_delay),
                Color(max_delay),
                Color(date)
            ])
        else:
            if color == 0:
                hostname = "{{{0}}}{1}{{/{0}}}".format("autogreen", hostname)
                status = "{{{0}}}{1}{{/{0}}}".format("autogreen", status)
                if lost != "0%":
                    lost = "{autocyan}" + lost + "{/autocyan}"
                else:
                    lost = "{{{0}}}{1}{{/{0}}}".format("autogreen", lost)
                aver_delay = "{{{0}}}{1}{{/{0}}}".format(
                    "autogreen", aver_delay)
                max_delay = "{{{0}}}{1}{{/{0}}}".format("autogreen", max_delay)
                date = '{autored}-{/autored}'
                table_data_temp.append([
                    Color(hostname),
                    Color(status),
                    Color(lost),
                    Color(aver_delay),
                    Color(max_delay),
                    Color(date)
                ])
            elif color == 1:
                hostname = "{{{0}}}{1}{{/{0}}}".format("autoyellow", hostname)
                status = "{{{0}}}{1}{{/{0}}}".format("autoyellow", status)
                if lost != "0%":
                    lost = "{autocyan}" + lost + "{/autocyan}"
                else:
                    lost = "{{{0}}}{1}{{/{0}}}".format("autoyellow", lost)
                aver_delay = "{{{0}}}{1}{{/{0}}}".format(
                    "autoyellow", aver_delay)
                max_delay = "{{{0}}}{1}{{/{0}}}".format(
                    "autoyellow", max_delay)
                date = "{autored}" + dict_failed_check_result.get(
                    key) + "{/autored}"
                table_data_temp.append([
                    Color(hostname),
                    Color(status),
                    Color(lost),
                    Color(aver_delay),
                    Color(max_delay),
                    Color(date)
                ])

            else:
                hostname = "{{{0}}}{1}{{/{0}}}".format("autowhite", hostname)
                status = "{{{0}}}{1}{{/{0}}}".format("autowhite", status)
                if lost != "0%":
                    lost = "{autocyan}" + lost + "{/autocyan}"
                else:
                    lost = "{{{0}}}{1}{{/{0}}}".format("autowhite", lost)
                aver_delay = "{{{0}}}{1}{{/{0}}}".format(
                    "autowhite", aver_delay)
                max_delay = "{{{0}}}{1}{{/{0}}}".format("autowhite", max_delay)
                date = "{autored}" + dict_failed_check_result.get(
                    key) + "{/autored}"
                table_data_temp.append([
                    Color(hostname),
                    Color(status),
                    Color(lost),
                    Color(aver_delay),
                    Color(max_delay),
                    Color(date)
                ])
    for i in sorted(table_data_temp):
        table_data.append(i)

    table_instance = SingleTable(table_data)
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = False
    table_instance.justify_columns = {
        0: 'center',
        1: 'center',
        2: 'center',
        3: 'center',
        4: 'center',
        5: 'center'
    }
    return table_instance.table
示例#34
0
文件: es.py 项目: kalaiser/acli
def output_domain_info(domain=None):
    """
    @type domain: dict
    """
    if domain:
        domain_details = domain.get('DomainStatusList')[0]
        cluster_conf = domain_details.get('ElasticsearchClusterConfig')
        td = list()
        td.append([
            Color('{autoblue}domain name{/autoblue}'),
            domain_details.get('DomainName')
        ])
        td.append([
            Color('{autoblue}endpoint{/autoblue}'),
            domain_details.get('Endpoint')
        ])
        td.append([
            Color('{autoblue}created{/autoblue}'),
            colour_created(domain_details.get('Created'))
        ])
        td.append([
            Color('{autoblue}deleted{/autoblue}'),
            colour_deleted(domain_details.get('Deleted'))
        ])
        td.append([
            Color('{autoblue}processing{/autoblue}'),
            colour_processing(domain_details.get('Processing'))
        ])
        td.append([Color('{autoblue}cluster config{/autoblue}'), ' '])
        td.append([
            Color('{autoblue} dedicated master enabled{/autoblue}'),
            str(cluster_conf.get('DedicatedMasterEnabled'))
        ])
        td.append([
            Color('{autoblue} instance type{/autoblue}'),
            str(cluster_conf.get('InstanceType'))
        ])
        td.append([
            Color('{autoblue} instance count{/autoblue}'),
            str(cluster_conf.get('InstanceCount'))
        ])
        td.append([
            Color('{autoblue} zone awareness{/autoblue}'),
            str(cluster_conf.get('ZoneAwarenessEnabled'))
        ])
        td.append([
            Color('{autoblue}domain id{/autoblue}'),
            domain_details.get('DomainId')
        ])
        td.append([
            Color('{autoblue}snapshot options{/autoblue}'),
            output_dict(domain_details.get('SnapshotOptions'))
        ])
        td.append([
            Color('{autoblue}advanced options{/autoblue}'),
            output_dict(domain_details.get('AdvancedOptions'))
        ])
        td.append(
            [Color('{autoblue}ARN{/autoblue}'),
             domain_details.get('ARN')])
        output_ascii_table(
            table_title=Color('{autowhite}ES domain info{/autowhite}'),
            table_data=td)
    else:
        exit('Domain does not exist.')
    exit(0)
示例#35
0
def execute_status(args, root_dir=None):
    """Print the status of the daemon.

    This function displays the current status of the daemon as well
    as the whole queue and all available information about every entry
    in the queue.
    `terminaltables` is used to format and display the queue contents.
    `colorclass` is used to color format the various items in the queue.

    Args:
        root_dir (string): The path to the root directory the daemon is running in.
    """

    status = command_factory('status')({}, root_dir=root_dir)
    # First rows, showing daemon status
    if status['status'] == 'running':
        status['status'] = Color('{autogreen}' +
                                 '{}'.format(status['status']) +
                                 '{/autogreen}')
    elif status['status'] in ['paused']:
        status['status'] = Color('{autoyellow}' +
                                 '{}'.format(status['status']) +
                                 '{/autoyellow}')

    print('Daemon: {}\n'.format(status['status']))

    # Handle queue data
    data = status['data']
    if isinstance(data, str):
        print(data)
    elif isinstance(data, dict):
        # Format incomming data to be compatible with Terminaltables
        formatted_data = []
        formatted_data.append(
            ['Index', 'Status', 'Code', 'Command', 'Path', 'Start', 'End'])
        for key, entry in sorted(data.items(), key=operator.itemgetter(0)):
            formatted_data.append([
                '#{}'.format(key), entry['status'],
                '{}'.format(entry['returncode']), entry['command'],
                entry['path'], entry['start'], entry['end']
            ])

        # Create AsciiTable instance and define style
        table = AsciiTable(formatted_data)
        table.outer_border = False
        table.inner_column_border = False

        terminal_width = terminal_size()
        customWidth = table.column_widths
        # If the text is wider than the actual terminal size, we
        # compute a new size for the Command and Path column.
        if (reduce(lambda a, b: a + b, table.column_widths) +
                10) > terminal_width[0]:
            # We have to subtract 14 because of table paddings
            left_space = math.floor(
                (terminal_width[0] - customWidth[0] - customWidth[1] -
                 customWidth[2] - customWidth[5] - customWidth[6] - 14) / 2)

            if customWidth[3] < left_space:
                customWidth[4] = 2 * left_space - customWidth[3]
            elif customWidth[4] < left_space:
                customWidth[3] = 2 * left_space - customWidth[4]
            else:
                customWidth[3] = left_space
                customWidth[4] = left_space

        # Format long strings to match the console width
        for i, entry in enumerate(table.table_data):
            for j, string in enumerate(entry):
                max_width = customWidth[j]
                wrapped_string = '\n'.join(wrap(string, max_width))
                if j == 1:
                    if wrapped_string == 'done' or wrapped_string == 'running' or wrapped_string == 'paused':
                        wrapped_string = Color('{autogreen}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autogreen}')
                    elif wrapped_string in ['queued', 'stashed']:
                        wrapped_string = Color('{autoyellow}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autoyellow}')
                    elif wrapped_string in ['failed', 'stopping', 'killing']:
                        wrapped_string = Color('{autored}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autored}')
                elif j == 2:
                    if wrapped_string == '0' and wrapped_string != 'Code':
                        wrapped_string = Color('{autogreen}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autogreen}')
                    elif wrapped_string != '0' and wrapped_string != 'Code':
                        wrapped_string = Color('{autored}' +
                                               '{}'.format(wrapped_string) +
                                               '{/autored}')

                table.table_data[i][j] = wrapped_string

        print(table.table)
    print('')
示例#36
0
    return '-'


def signal_power(signal):
    if signal <= -70:
        return Color("{autored}" + str(signal) + "{/autored}")
    elif signal > -70 and signal < -55:
        return Color("{autoyellow}" + str(signal) + "{/autoyellow}")
    else:
        return Color("{autogreen}" + str(signal) + "{/autogreen}")


data = []
registered = {}
data.append([
    Color("{autogreen}Freq. (MHz){/autogreen}"),
    Color("{autogreen}Pow. (dBm){/autogreen}"),
    Color("{autogreen}MAC{/autogreen}"),
    Color("{autogreen}SSID{/autogreen}"),
    Color("{autogreen}Vendor{/autogreen}"),
    Color("{autogreen}Coords. (Lat-Long){/autogreen}")
])

process = Popen('tcpdump -l -I -i ' + args.iface +
                ' -e -s 256 type mgt subtype probe-req',
                bufsize=1,
                universal_newlines=True,
                shell=True,
                stdout=PIPE,
                stderr=PIPE)
threading.Thread(target=print_data).start()
示例#37
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
示例#38
0
def _colorize_status(status):
    if status in ('active'):
        return Color('{green}'+status+'{/green}')
    return Color('{red}'+status+'{/red}')
示例#39
0
def printLoadError(file, id, msg, errno=1):
    print(Color("-- {red}Error on loading{/red} {white}" + file +
                "::id[" + id + "]: " + msg + "{/white}"))
    sys.exit(errno)
示例#40
0
def test_static_color_methods():
    """Test all convenience methods."""
    assert Color('{autored}this is a test.{/autored}') == Color.red('this is a test.', auto=True)
    assert Color('{red}this is a test.{/red}') == Color.red('this is a test.')
    assert Color('{autobgred}this is a test.{/autobgred}') == Color.bgred('this is a test.', auto=True)
    assert Color('{bgred}this is a test.{/bgred}') == Color.bgred('this is a test.')
    assert Color('{autogreen}this is a test.{/autogreen}') == Color.green('this is a test.', auto=True)
    assert Color('{green}this is a test.{/green}') == Color.green('this is a test.')
    assert Color('{autobggreen}this is a test.{/autobggreen}') == Color.bggreen('this is a test.', auto=True)
    assert Color('{bggreen}this is a test.{/bggreen}') == Color.bggreen('this is a test.')
    assert Color('{autoblue}this is a test.{/autoblue}') == Color.blue('this is a test.', auto=True)
    assert Color('{blue}this is a test.{/blue}') == Color.blue('this is a test.')
    assert Color('{autobgblue}this is a test.{/autobgblue}') == Color.bgblue('this is a test.', auto=True)
    assert Color('{bgblue}this is a test.{/bgblue}') == Color.bgblue('this is a test.')
    assert Color('{autogreen}this is a test.{/autogreen}') == Color.green('this is a test.', auto=True)
    assert Color('{green}this is a test.{/green}') == Color.green('this is a test.')
    assert Color('{autobggreen}this is a test.{/autobggreen}') == Color.bggreen('this is a test.', auto=True)
    assert Color('{bggreen}this is a test.{/bggreen}') == Color.bggreen('this is a test.')
    assert Color('{autoyellow}this is a test.{/autoyellow}') == Color.yellow('this is a test.', auto=True)
    assert Color('{yellow}this is a test.{/yellow}') == Color.yellow('this is a test.')
    assert Color('{autobgyellow}this is a test.{/autobgyellow}') == Color.bgyellow('this is a test.', auto=True)
    assert Color('{bgyellow}this is a test.{/bgyellow}') == Color.bgyellow('this is a test.')
    assert Color('{autocyan}this is a test.{/autocyan}') == Color.cyan('this is a test.', auto=True)
    assert Color('{cyan}this is a test.{/cyan}') == Color.cyan('this is a test.')
    assert Color('{autobgcyan}this is a test.{/autobgcyan}') == Color.bgcyan('this is a test.', auto=True)
    assert Color('{bgcyan}this is a test.{/bgcyan}') == Color.bgcyan('this is a test.')
    assert Color('{automagenta}this is a test.{/automagenta}') == Color.magenta('this is a test.', auto=True)
    assert Color('{magenta}this is a test.{/magenta}') == Color.magenta('this is a test.')
    assert Color('{autobgmagenta}this is a test.{/autobgmagenta}') == Color.bgmagenta('this is a test.', auto=True)
    assert Color('{bgmagenta}this is a test.{/bgmagenta}') == Color.bgmagenta('this is a test.')