Пример #1
0
def test_control():
    console = Console(file=io.StringIO(), force_terminal=True)
    console.control("FOO")
    console.print("BAR")
    assert console.file.getvalue() == "FOOBAR\n"
Пример #2
0
def main():
    colorama.init(autoreset=True)
    c5 = colorama.Fore.RED + colorama.Back.LIGHTYELLOW_EX
    c7 = colorama.Fore.BLACK + colorama.Back.MAGENTA
    cr = colorama.Style.RESET_ALL
    line_numbers = False
    word_wrap = True  # Always use word wrap now
    help_me = False
    invalid_cmd = None
    is_python_file = False
    code_lang = None

    command_args = sys.argv[2:]
    file_to_print = command_args[0]
    if file_to_print.lower().endswith(".py"):
        is_python_file = True
        code_lang = "python"
    elif file_to_print.lower().endswith(".js"):
        code_lang = "javascript"
    elif file_to_print.lower().endswith(".md"):
        code_lang = "markdown"
    elif file_to_print.lower().endswith(".html"):
        code_lang = "html"
    elif file_to_print.lower().endswith(".css"):
        code_lang = "css"
    elif file_to_print.lower().endswith(".go"):
        code_lang = "go"
    elif file_to_print.lower().endswith(".java"):
        code_lang = "java"
    elif "." not in file_to_print:
        code_lang = "markdown"
    else:
        code_lang = file_to_print.split(".")[-1].lower()

    if len(command_args) >= 2:
        options = command_args[1:]
        for option in options:
            option = option.lower()
            if option == "-n":
                line_numbers = True
            elif option == "-w":
                word_wrap = True
            else:
                invalid_cmd = "\n===> INVALID OPTION: >> %s <<\n" % option
                invalid_cmd = invalid_cmd.replace(">> ", ">>" + c5 + " ")
                invalid_cmd = invalid_cmd.replace(" <<", " " + cr + "<<")
                invalid_cmd = invalid_cmd.replace(">>", c7 + ">>" + cr)
                invalid_cmd = invalid_cmd.replace("<<", c7 + "<<" + cr)
                help_me = True
                break

    if help_me:
        invalid_run_command(invalid_cmd)

    with open(file_to_print, "r", encoding="utf-8") as f:
        all_code = f.read()
    all_code = all_code.replace("\t", "    ")
    code_lines = all_code.split("\n")

    console_width = None  # width of console output when running script
    used_width = None  # code_width and few spaces on right for padding
    magic_console = None
    magic_syntax = None
    try:
        console_width = os.popen("stty size", "r").read().split()[1]
        if console_width:
            console_width = int(console_width)
    except Exception:
        console_width = None

    use_rich = False
    if sys.version_info[0] == 3 and sys.version_info[1] >= 6:
        use_rich = True

    if use_rich:
        from rich.console import Console
        from rich.syntax import Syntax

        the_code = "\n".join(code_lines)
        code_width = 1

        w = 0  # line number whitespace
        if line_numbers:
            w = 4
            num_lines = len(code_lines)
            if num_lines >= 10:
                w = 5
            if num_lines >= 100:
                w = 6
            if num_lines >= 1000:
                w = 7

        if is_python_file:
            new_sb_lines = []
            for line in code_lines:
                if line.endswith("  # noqa") and line.count("  # noqa") == 1:
                    line = line.replace("  # noqa", "")
                line_length2 = len(line)  # Normal Python string length used
                line_length = get_width(line)  # Special characters count 2X
                if line_length > code_width:
                    code_width = line_length

                if console_width:
                    # If line is larger than console_width, try to optimize it.
                    # Smart Python word wrap to be used with valid indentation.
                    if line_length + w > console_width:  # 5 is line number ws
                        if line.strip().startswith("#"):
                            new_sb_lines.append(line)
                            continue
                        elif (line.count("  # ") == 1
                              and get_width(line.split("  # ")[0]) + w <=
                              console_width):
                            # Line is short enough once comment is removed
                            line = line.split("  # ")[0]
                            new_sb_lines.append(line)
                            continue
                        elif (line.count(" # ") == 1
                              and get_width(line.split(" # ")[0]) + w <=
                              console_width):
                            # L-Length good if removing bad flake8 comment
                            line = line.split("  # ")[0]
                            new_sb_lines.append(line)
                            continue
                        if line.startswith("from") and " import " in line:
                            line1 = line.split(" import ")[0] + " \\"
                            line2 = "    import " + line.split(" import ")[1]
                            new_sb_lines.append(line1)
                            new_sb_lines.append(line2)
                            continue
                        if line.count("(") == 1 and line.count(")") == 1:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split("(")[0] + "("
                            line2 = new_ws + line.split("(")[1]
                            if not ("):") in line2:
                                new_sb_lines.append(line1)
                                if get_width(line2) + w > console_width:
                                    if line2.count('", "') == 1:
                                        line2a = line2.split('", "')[0] + '",'
                                        line2b = (new_ws + '"' +
                                                  (line2.split('", "')[1]))
                                        new_sb_lines.append(line2a)
                                        new_sb_lines.append(line2b)
                                        continue
                                    elif line2.count("', '") == 1:
                                        line2a = line2.split("', '")[0] + "',"
                                        line2b = (new_ws + "'" +
                                                  (line2.split("', '")[1]))
                                        new_sb_lines.append(line2a)
                                        new_sb_lines.append(line2b)
                                        continue
                                    elif line2.count("://") == 1 and (
                                            line2.count('")') == 1):
                                        line2a = line2.split("://")[0] + '://"'
                                        line2b = (new_ws + '"' +
                                                  (line2.split("://")[1]))
                                        new_sb_lines.append(line2a)
                                        if get_width(line2b) + w > (
                                                console_width):
                                            if line2b.count("/") > 0:
                                                slash_one = line2b.find("/")
                                                slash_one_p1 = slash_one + 1
                                                line2b1 = (
                                                    line2b[:slash_one + 1] +
                                                    '"')
                                                line2b2 = (
                                                    new_ws + '"' +
                                                    (line2b[slash_one_p1:]))
                                                new_sb_lines.append(line2b1)
                                                if line2b2.count(")  # ") == 1:
                                                    line2b2 = (line2b2.split(
                                                        ")  # ")[0] + ")")
                                                new_sb_lines.append(line2b2)
                                                continue
                                        new_sb_lines.append(line2b)
                                        continue
                                    elif line2.count("://") == 1 and (
                                            line2.count("')") == 1):
                                        line2a = line2.split("://")[0] + "://'"
                                        line2b = (new_ws + "'" +
                                                  (line2.split("://")[1]))
                                        new_sb_lines.append(line2a)
                                        if get_width(line2b) + w > (
                                                console_width):
                                            if line2b.count("/") > 0:
                                                slash_one = line2b.find("/")
                                                slash_one_p1 = slash_one + 1
                                                line2b1 = (
                                                    line2b[:slash_one + 1] +
                                                    "'")
                                                line2b2 = (
                                                    new_ws + "'" +
                                                    (line2b[slash_one_p1:]))
                                                new_sb_lines.append(line2b1)
                                                if line2b2.count(")  # ") == 1:
                                                    line2b2 = (line2b2.split(
                                                        ")  # ")[0] + ")")
                                                new_sb_lines.append(line2b2)
                                                continue
                                        new_sb_lines.append(line2b)
                                        continue
                                    elif line2.count(", ") == 1:
                                        line2a = line2.split(", ")[0] + ","
                                        line2b = new_ws + (
                                            line2.split(", ")[1])
                                        new_sb_lines.append(line2a)
                                        new_sb_lines.append(line2b)
                                        continue
                                    elif line2.count('="') == 1 and (
                                            line2.lstrip().startswith("'")):
                                        line2a = line2.split('="')[0] + "='"
                                        line2b = (new_ws + "'\"" +
                                                  (line2.split('="')[1]))
                                        new_sb_lines.append(line2a)
                                        new_sb_lines.append(line2b)
                                        continue
                                    elif line2.count("='") == 1 and (
                                            line2.lstrip().startswith('"')):
                                        line2a = line2.split("='")[0] + '="'
                                        line2b = (new_ws + "\"'" +
                                                  (line2.split("='")[1]))
                                        new_sb_lines.append(line2a)
                                        new_sb_lines.append(line2b)
                                        continue
                                new_sb_lines.append(line2)
                            elif get_width(line2) + 4 + w <= console_width:
                                line2 = "    " + line2
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                            else:
                                new_sb_lines.append(line)
                            continue
                        if line.count('("') == 1:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split('("')[0] + "("
                            line2 = new_ws + '"' + line.split('("')[1]
                            if not ("):") in line2:
                                new_sb_lines.append(line1)
                                if get_width(line2) + w > console_width:
                                    if line2.count('" in self.') == 1:
                                        line2a = (
                                            line2.split('" in self.')[0] +
                                            '" in')
                                        line2b = (
                                            new_ws + "self." +
                                            (line2.split('" in self.')[1]))
                                        new_sb_lines.append(line2a)
                                        new_sb_lines.append(line2b)
                                        continue
                                new_sb_lines.append(line2)
                            elif get_width(line2) + 4 + w <= console_width:
                                line2 = "    " + line2
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                            else:
                                new_sb_lines.append(line)
                            continue
                        if line.count("('") == 1:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split("('")[0] + "("
                            line2 = new_ws + "'" + line.split("('")[1]
                            if not ("):") in line2:
                                new_sb_lines.append(line1)
                                if get_width(line2) + w > console_width:
                                    if line2.count("' in self.") == 1:
                                        line2a = (
                                            line2.split("' in self.")[0] +
                                            "' in")
                                        line2b = (
                                            new_ws + "self." +
                                            (line2.split("' in self.")[1]))
                                        new_sb_lines.append(line2a)
                                        new_sb_lines.append(line2b)
                                        continue
                                new_sb_lines.append(line2)
                            elif get_width(line2) + 4 + w <= console_width:
                                line2 = "    " + line2
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                            else:
                                new_sb_lines.append(line)
                            continue
                        if line.count('= "') == 1 and line.count("://") == 1:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split("://")[0] + '://" \\'
                            line2 = new_ws + '"' + line.split("://")[1]
                            new_sb_lines.append(line1)
                            if get_width(line2) + w > console_width:
                                if line2.count("/") > 0:
                                    slash_one = line2.find("/")
                                    slash_one_p1 = slash_one + 1
                                    line2a = line2[:slash_one + 1] + '" \\'
                                    line2b = (new_ws + '"' +
                                              line2[slash_one_p1:])
                                    new_sb_lines.append(line2a)
                                    new_sb_lines.append(line2b)
                                    continue
                            new_sb_lines.append(line2)
                            continue
                        if line.count("= '") == 1 and line.count("://") == 1:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split("://")[0] + "://' \\"
                            line2 = new_ws + "'" + line.split("://")[1]
                            new_sb_lines.append(line1)
                            if get_width(line2) + w > console_width:
                                if line2.count("/") > 0:
                                    slash_one = line2.find("/")
                                    slash_one_p1 = slash_one + 1
                                    line2a = line2[:slash_one + 1] + "' \\"
                                    line2b = (new_ws + "'" +
                                              line2[slash_one_p1:])
                                    new_sb_lines.append(line2a)
                                    new_sb_lines.append(line2b)
                                    continue
                            new_sb_lines.append(line2)
                            continue
                        if line.count("(self.") == 1 and not ("):") in line:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split("(self.")[0] + "("
                            line2 = new_ws + "self." + line.split("(self.")[1]
                            if get_width(line1) + w <= console_width:
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                                continue
                        if line.count(" == ") == 1 and not (line.endswith(":")
                                                            or
                                                            (":  #") in line):
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split(" == ")[0] + " == ("
                            line2 = new_ws + line.split(" == ")[1] + ")"
                            if get_width(line1) + w <= console_width and (
                                    get_width(line2) + w <= console_width):
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                                continue
                        if line.count(" == ") == 1 and line.endswith(":"):
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "        "
                            line1 = line.split(" == ")[0] + " == ("
                            line2 = new_ws + line.split(" == ")[1][:-1] + "):"
                            if get_width(line1) + w <= console_width and (
                                    get_width(line2) + w <= console_width):
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                                continue
                        if (line.count(" == ") == 1
                                and (line.count(":  #") == 1)
                                and (line.find(" == ") < line.find(":  #"))):
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "        "
                            comments = "  #" + line.split(":  #")[1]
                            line0 = line.split(":  #")[0] + ":"
                            line1 = line0.split(" == ")[0] + " == ("
                            line2 = new_ws + line0.split(" == ")[1][:-1] + "):"
                            if get_width(line1) + w <= console_width and (
                                    get_width(line2) + w <= console_width):
                                new_sb_lines.append(line1)
                                if (get_width(line2 + comments) + w <=
                                        console_width):
                                    new_sb_lines.append(line2 + comments)
                                else:
                                    new_sb_lines.append(line2)
                                continue
                        if line.count(" % ") == 1 and not ("):") in line:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split(" % ")[0] + " \\"
                            line2 = new_ws + "% " + line.split(" % ")[1]
                            if get_width(line1) + w <= console_width:
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                                continue
                        if line.count(" = ") == 1 and not ("  # ") in line:
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "    "
                            line1 = line.split(" = ")[0] + " = ("
                            line2 = new_ws + line.split(" = ")[1] + ")"
                            if get_width(line1) + w <= console_width and (
                                    get_width(line2) + w <= console_width):
                                new_sb_lines.append(line1)
                                new_sb_lines.append(line2)
                                continue
                            elif get_width(line1) + w <= console_width:
                                if line2.count(" % ") == 1 and not (
                                        line2.endswith(":")):
                                    whitespace = line_length2 - len(
                                        line2.lstrip())
                                    line2a = line2.split(" % ")[0] + " \\"
                                    line2b = (new_ws + "% " +
                                              line2.split(" % ")[1])
                                    if get_width(line2a) + w <= console_width:
                                        if (get_width(line2b) + w <=
                                                console_width):
                                            new_sb_lines.append(line1)
                                            new_sb_lines.append(line2a)
                                            new_sb_lines.append(line2b)
                                            continue
                        if (line.count(" = ") == 1
                                and (line.count("  # ") == 1)
                                and (line.find(" = ") < line.find("  # "))):
                            whitespace = line_length2 - len(line.lstrip())
                            new_ws = line[0:whitespace] + "        "
                            comments = "  # " + line.split("  # ")[1]
                            line0 = line.split("  # ")[0]
                            line1 = line0.split(" = ")[0] + " = ("
                            line2 = new_ws + line0.split(" = ")[1] + ")"
                            if get_width(line1) + w <= console_width and (
                                    get_width(line2) + w <= console_width):
                                new_sb_lines.append(line1)
                                if (get_width(line2 + comments) + w <=
                                        console_width):
                                    new_sb_lines.append(line2 + comments)
                                else:
                                    new_sb_lines.append(line2)
                                continue
                    new_sb_lines.append(line)

            if new_sb_lines:
                code_lines = new_sb_lines
                the_code = "\n".join(code_lines)

        if code_lang != "python":
            for line in code_lines:
                line_length = get_width(line)
                if line_length > code_width:
                    code_width = line_length

        extra_r_spaces = 2
        if console_width and (code_width + extra_r_spaces < console_width):
            used_width = code_width + extra_r_spaces

        try:
            if "🗺�" in the_code:
                # Fix width of an emoji
                the_code = the_code.replace("🗺�", "🗺� ")
        except Exception:
            pass

        magic_syntax = Syntax(
            the_code,
            code_lang,
            theme="monokai",
            line_numbers=line_numbers,
            code_width=used_width,
            word_wrap=word_wrap,
        )
        magic_console = Console()
    # ----------------------------------------
    dash_length = 62  # May change
    if used_width and used_width + w < console_width:
        dash_length = used_width + w
    elif console_width:
        dash_length = console_width
    dashes = "-" * dash_length
    print(dashes)
    print_success = False
    if use_rich and code_lang == "markdown":
        try:
            from rich.markdown import Markdown

            markdown = Markdown(all_code)
            markdown_console = Console()
            markdown_console.print(markdown)  # noqa
            print_success = True
        except Exception:
            pass
    elif use_rich and magic_syntax:
        try:
            magic_console.print(magic_syntax)  # noqa
            print_success = True
        except Exception:
            pass
    if not use_rich or not magic_syntax or not print_success:
        for line in code_lines:
            print(line)
    print(dashes)
from enum import Enum

import requests
from brownie import Wei, accounts, interface, rpc
from helpers.constants import *
from helpers.constants import MaxUint256
from helpers.gnosis_safe import GnosisSafe, MultisigTxMetadata
from helpers.registry import registry
from helpers.utils import val
from rich.console import Console
from scripts.systems.badger_system import BadgerSystem, connect_badger
from scripts.systems.uniswap_system import UniswapSystem
from helpers.gas_utils import gas_strategies

console = Console()

gas_strategies.set_default(gas_strategies.exponentialScalingFast)


def main():
    badger = connect_badger(load_deployer=True)
    dev = accounts.at("0xd41f7006bcb2B3d0F9C5873272Ebed67B37F80Dc", force=True)

    guestList = VipCappedGuestListBbtcUpgradeable.at(
        "0x7dD08c5a4Ce91Cf862223330dD373E36fe94189B")

    guestRoot = guestList.guestRoot()
    userDepositCap = guestList.userDepositCap()
    totalDepositCap = guestList.totalDepositCap()
    owner = guestList.owner()
Пример #4
0
def test_print_sep_end(print_text, result):
    console = Console(record=True, file=StringIO())
    console.print(*print_text, sep="", end="X")
    assert console.file.getvalue() == result
Пример #5
0
def test_emoji():
    """Test printing emoji codes."""
    console = Console(file=StringIO())
    console.print(":+1:")
    assert console.file.getvalue() == "👍\n"
Пример #6
0
def run(feed_url):
    """
    Pull a podcast rss feed from a given url and print a table
    with all episodes sorted by time between episodes

    :raises ValueError:
        If the feed does not have all of the required data
    """
    console = Console(width=150)
    # get the feed and parse it
    parsed_feed = []
    for url in feed_url:
        parsed_feed.extend(get_parsed_feed(url))

    # Draw weekday distribution
    heatmap = Table(title="Weekday Heatmap")
    heat = {
        0:
        Style(bgcolor=Color.from_rgb(red=153, green=0, blue=13)),
        1:
        Style(bgcolor=Color.from_rgb(red=203, green=24, blue=29)),
        2:
        Style(bgcolor=Color.from_rgb(red=239, green=59, blue=44)),
        3:
        Style(bgcolor=Color.from_rgb(red=251, green=106, blue=74),
              color="black"),
        4:
        Style(bgcolor=Color.from_rgb(red=252, green=146, blue=114),
              color="black"),
        5:
        Style(bgcolor=Color.from_rgb(red=252, green=187, blue=161),
              color="black"),
        6:
        Style(bgcolor=Color.from_rgb(red=254, green=229, blue=217),
              color="black"),
    }

    count = weekday_distribution(parsed_feed)
    result = {}
    for i, item in enumerate(count.most_common()):
        result[item[0]] = {"value": str(item[1]), "style": heat[i]}

    row = []
    for d in ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]:
        day = result.get(d, {"value": "0", "style": ""})
        heatmap.add_column(d, style=day["style"], justify="center")
        row.append(day["value"])

    heatmap.add_row(*row)

    console.print(heatmap)

    table = Table(
        "Podcast",
        "Title",
        "Date published",
        "Days since last",
        title="Episodes",
    )
    for episode in sorted(parsed_feed,
                          key=lambda x: x["published_datetime"],
                          reverse=True):
        table.add_row(
            episode["podcast"],
            " ".join(episode["title"].split()),
            episode["published_datetime"].in_timezone(
                pendulum.local_timezone()).to_day_datetime_string(),
            str(episode["time_since_last"].days),
        )

    console.print(table)
Пример #7
0
def test_console_width():
    console = Console()
    test = Text("Hello World!\nfoobarbaz")
    assert test.__measure__(console, 80) == Measurement(9, 12)
    assert Text(" " * 4).__measure__(console, 80) == Measurement(4, 4)
Пример #8
0
def test_soft_wrap():
    console = Console(width=10, file=io.StringIO())
    console.print("foo bar baz egg", soft_wrap=True)
    assert console.file.getvalue() == "foo bar baz egg\n"
Пример #9
0
def test_init():
    console = Console(color_system=None)
    assert console._color_system == None
    console = Console(color_system="standard")
    assert console._color_system == ColorSystem.STANDARD
    console = Console(color_system="auto")
Пример #10
0
def test_export_text():
    console = Console(record=True, width=100)
    console.print("[b]foo")
    text = console.export_text()
    expected = "foo\n"
    assert text == expected
Пример #11
0
def test_export_html_inline():
    console = Console(record=True, width=100)
    console.print("[b]foo [link=https://example.org]Click[/link]")
    html = console.export_html(inline_styles=True)
    expected = '<!DOCTYPE html>\n<head>\n<meta charset="UTF-8">\n<style>\n\nbody {\n    color: #000000;\n    background-color: #ffffff;\n}\n</style>\n</head>\n<html>\n<body>\n    <code>\n        <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace"><span style="font-weight: bold">foo </span><a href="https://example.org"><span style="font-weight: bold">Click</span></a>\n</pre>\n    </code>\n</body>\n</html>\n'
    assert html == expected
Пример #12
0
def test_render_broken_renderable():
    console = Console()
    broken = BrokenRenderable()
    with pytest.raises(errors.NotRenderableError):
        list(console.render(broken, console.options))
Пример #13
0
def test_16color_terminal():
    console = Console(force_terminal=True,
                      _environ={"TERM": "xterm-16color"},
                      legacy_windows=False)
    assert console.color_system == "standard"
Пример #14
0
def test_justify_right():
    console = Console(file=io.StringIO(), force_terminal=True, width=20)
    console.print("FOO", justify="right")
    assert console.file.getvalue() == "                 FOO\n"
Пример #15
0
        dest="background_color",
        default=None,
        help="Overide background color",
    )
    parser.add_argument(
        "-x",
        "--lexer",
        default="default",
        dest="lexer_name",
        help="Lexer name",
    )
    args = parser.parse_args()

    from rich.console import Console

    console = Console(force_terminal=args.force_color, width=args.width)

    if args.path == "-":
        code = sys.stdin.read()
        syntax = Syntax(
            code=code,
            lexer_name=args.lexer_name,
            line_numbers=args.line_numbers,
            word_wrap=args.word_wrap,
            theme=args.theme,
            background_color=args.background_color,
            indent_guides=args.indent_guides,
        )
    else:
        syntax = Syntax.from_path(
            args.path,
Пример #16
0
def test_repr():
    console = Console()
    assert isinstance(repr(console), str)
    assert isinstance(str(console), str)
def create_console():

    return Console()
Пример #18
0
def test_print_empty():
    console = Console(file=io.StringIO(), color_system="truecolor")
    console.print()
    assert console.file.getvalue() == "\n"
Пример #19
0
\b
* kettle.properties
* spoon.sh
* shared.xml

This script is designed only to be run on Mac OSX or Linux."""
cli = typer.Typer(name="pdi_config", add_completion=False, help=usage)

default_path = (
    Path("/Applications/data-integration")  # default path for Mac
    if sys.platform == "darwin" else Path.home() /
    "data-integration"  # default path for Linux
)
default_match = "STM"

console = Console(style="bold white")
fail_style = "bold white on red"
warn_style = "bold white on yellow"
gain_style = "bold white on green"
show_style = "bold purple"


def unable_to_locate(filename: Path) -> None:
    """Print unable to locate file message."""
    console.print(f"UNABLE TO LOCATE {filename}!", style=fail_style)


def open_in_editor(filename: Path) -> None:
    """Open specified file in default text editor."""
    try:
        if sys.platform == "darwin":
Пример #20
0
def test_markup_highlight():
    console = Console(file=io.StringIO(), color_system="truecolor")
    console.print("'[bold]foo[/bold]'")
    assert (console.file.getvalue() ==
            "\x1b[32m'\x1b[0m\x1b[1;32mfoo\x1b[0m\x1b[32m'\x1b[0m\n")
Пример #21
0
def test_print(print_text, result):
    console = Console(record=True)
    console.print(*print_text)
    assert console.export_text(styles=False) == result
Пример #22
0
async def fetch_otu_isolates(taxid: str, name: str, path: pathlib.Path,
                             accessions: list, paths: list,
                             queue: asyncio.Queue):
    """
    Fetch new isolates for a given OTU, creating a directory for each

    :param taxid: The taxon id for a given OTU
    :param name: Name of a given OTU
    :param path: Path to a given OTU in a reference directory
    :param accessions: List of accessions for the given taxon id from local cache
    :param paths: List of all paths to every OTU in a reference
    :param queue: Asyncio queue to put newfound accessions onto for caching purposes
    """

    isolates = await get_isolates(path)

    records, new_accessions = await asyncio.get_event_loop().run_in_executor(
        None, get_records, accessions, taxid)

    isolate_ids, sequence_ids = await get_unique_ids(paths)

    console = Console()

    if records is None:
        console.print(f"[red]✘ {name} ({taxid})")
        console.print(
            "  [red]Found 0 isolates, could not link taxid to nucleotide records\n"
        )
        return

    new_isolates = dict()

    for accession in [
            accession for accession in records.values() if accession.seq
    ]:
        accession_data = await get_qualifiers(accession.features)

        # try to find isolate type and name automatically
        isolate_type = await find_isolate(accession_data)

        if isolate_type is None:
            continue

        isolate_name = accession_data.get(isolate_type)[0]

        # see if isolate directory already exists and create it if needed
        if isolate_name not in isolates:
            new_isolates[isolate_name] = isolate_type

            new_id = await store_isolate(path, isolate_name, isolate_type,
                                         isolate_ids)
            isolate_ids.add(new_id)
            isolates[isolate_name] = new_id

        # create new sequence file

        isolate_path = path / isolates.get(isolate_name)

        new_id = await store_sequence(isolate_path, accession, accession_data,
                                      sequence_ids)
        sequence_ids.add(new_id)

        await queue.put((taxid, new_accessions))

    await log_results(name, taxid, new_isolates, console)
Пример #23
0
def test_markup_switch():
    """Test markup can be disabled."""
    console = Console(file=StringIO(), markup=False)
    console.print("[bold]foo[/bold]")
    assert console.file.getvalue() == "[bold]foo[/bold]\n"
Пример #24
0
def chat_main(client):
    """ (Clubhouse) -> NoneType

    Main function for chat
    """
    max_limit = 20
    channel_speaker_permission = False
    _wait_func = None
    _ping_func = None

    def _request_speaker_permission(client, channel_name, user_id):
        """ (str) -> bool

        Raise hands for permissions
        """
        if not channel_speaker_permission:
            client.audience_reply(channel_name, True, False)
            _wait_func = _wait_speaker_permission(client, channel_name, user_id)
            print("[/] You've raised your hand. Wait for the moderator to give you the permission.")

    @set_interval(30)
    def _ping_keep_alive(client, channel_name):
        """ (str) -> bool

        Continue to ping alive every 30 seconds.
        """
        client.active_ping(channel_name)
        return True

    @set_interval(10)
    def _wait_speaker_permission(client, channel_name, user_id):
        """ (str) -> bool

        Function that runs when you've requested for a voice permission.
        """
        # Get some random users from the channel.
        _channel_info = client.get_channel(channel_name)
        if _channel_info['success']:
            for _user in _channel_info['users']:
                if _user['user_id'] != user_id:
                    user_id = _user['user_id']
                    break
            # Check if the moderator allowed your request.
            res_inv = client.accept_speaker_invite(channel_name, user_id)
            if res_inv['success']:
                print("[-] Now you have a speaker permission.")
                print("    Please re-join this channel to activate a permission.")
                return False
        return True

    while True:
        # Choose which channel to enter.
        # Join the talk on success.
        user_id = client.HEADERS.get("CH-UserID")
        print(client)
        print_channel_list(client, max_limit)
        channel_name = input("[.] Enter channel_name: ")
        channel_info = client.join_channel(channel_name)
        if not channel_info['success']:
            # Check if this channel_name was taken from the link
            channel_info = client.join_channel(channel_name, "link", "e30=")
            if not channel_info['success']:
                print(f"[-] Error while joining the channel ({channel_info['error_message']})")
                continue

        # List currently available users (TOP 20 only.)
        # Also, check for the current user's speaker permission.
        channel_speaker_permission = False
        console = Console()
        table = Table(show_header=True, header_style="bold magenta")
        table.add_column("user_id", style="cyan", justify="right")
        table.add_column("username")
        table.add_column("name")
        table.add_column("is_speaker")
        table.add_column("is_moderator")
        users = channel_info['users']
        i = 0
        for user in users:
            i += 1
            if i > max_limit:
                break
            table.add_row(
                str(user['user_id']),
                str(user['name']),
                str(user['username']),
                str(user['is_speaker']),
                str(user['is_moderator']),
            )
            # Check if the user is the speaker
            if user['user_id'] == int(user_id):
                channel_speaker_permission = bool(user['is_speaker'])
        console.print(table)

        # Check for the voice level.
        if RTC:
            token = channel_info['token']
            RTC.joinChannel(token, channel_name, "", int(user_id))
        else:
            print("[!] Agora SDK is not installed.")
            print("    You may not speak or listen to the conversation.")

        # Activate pinging
        client.active_ping(channel_name)
        _ping_func = _ping_keep_alive(client, channel_name)
        _wait_func = None

        # Add raise_hands key bindings for speaker permission
        # Sorry for the bad quality
        if not channel_speaker_permission:

            if sys.platform == "darwin": # OSX
                _hotkey = "9"
            elif sys.platform == "win32": # Windows
                _hotkey = "ctrl+shift+h"

            print(f"[*] Press [{_hotkey}] to raise your hands for the speaker permission.")
            keyboard.add_hotkey(
                _hotkey,
                _request_speaker_permission,
                args=(client, channel_name, user_id)
            )

        input("[*] Press [Enter] to quit conversation.\n")
        keyboard.unhook_all()

        # Safely leave the channel upon quitting the channel.
        if _ping_func:
            _ping_func.set()
        if _wait_func:
            _wait_func.set()
        if RTC:
            RTC.leaveChannel()
        client.leave_channel(channel_name)
Пример #25
0
def test_emoji_switch():
    """Test emoji can be disabled."""
    console = Console(file=StringIO(), emoji=False)
    console.print(":+1:")
    assert console.file.getvalue() == ":+1:\n"
Пример #26
0
from ._mymodel import MyModel, MyModule

# https://github.com/python-poetry/poetry/pull/2366#issuecomment-652418094
# https://github.com/python-poetry/poetry/issues/144#issuecomment-623927302
try:
    import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
    import importlib_metadata

package_name = "scvi-tools-skeleton"
__version__ = importlib_metadata.version(package_name)

logger = logging.getLogger(__name__)
# set the logging level
logger.setLevel(logging.INFO)

# nice logging outputs
console = Console(force_terminal=True)
if console.is_jupyter is True:
    console.is_jupyter = False
ch = RichHandler(show_path=False, console=console, show_time=False)
formatter = logging.Formatter("mypackage: %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

# this prevents double outputs
logger.propagate = False

__all__ = ["setup_anndata", "MyModel", "MyModule", "MyPyroModel", "MyPyroModule"]
Пример #27
0
    def __str__(self):
        buf = StringIO()
        _console = Console(file=buf, force_jupyter=False)
        _console.print(self)

        return buf.getvalue()
Пример #28
0
 def __init__(self) -> None:
     """Creates a new Logger instance."""
     self._console = Console(markup=False, highlight=False, emoji=False)
     self._debug_logging_enabled = False
Пример #29
0
                append_span(_Span(start, len(text), str(open_tag)))
            else:  # Opening tag
                normalized_tag = Tag(normalize(tag.name), tag.parameters)
                style_stack.append((len(text), normalized_tag))

    text_length = len(text)
    while style_stack:
        start, tag = style_stack.pop()
        append_span(_Span(start, text_length, str(tag)))

    text.spans = sorted(spans)
    return text


if __name__ == "__main__":  # pragma: no cover
    # from rich import print
    from rich.console import Console
    from rich.text import Text

    console = Console(highlight=False)

    # t = Text.from_markup('Hello [link="https://www.willmcgugan.com"]W[b]o[/b]rld[/]!')
    # print(repr(t._spans))

    console.print("foo")
    console.print("Hello [link=https://www.willmcgugan.com]W[b]o[/b]rld[/]!")

    # console.print("[bold]1 [not bold]2[/] 3[/]")

    # console.print("[green]XXX[blue]XXX[/]XXX[/]")
Пример #30
0
def test_render_error():
    console = Console()
    with pytest.raises(errors.NotRenderableError):
        list(console.render([], console.options))