Пример #1
0
def show(
    types: bool = typer.Option(
        False, "--types", help="Show expected field types for configuration"
    )
):
    """
    Show the configuration.

    By default, does not show secrets. If using --verbose, secrets will be shown in plaintext.
    """
    if types:
        console.print(Panel.fit("[bold yellow]Field Types[/bold yellow]"))
        console.print(settings.fields)

    output = {}
    for k, v in settings.dict().items():
        if isinstance(v, SecretBytes):
            if state["verbose"]:
                v = v.get_secret_value().decode()
            else:
                v = v.display()

        output[k] = v

    console.print(Panel.fit(f"[bold red]Config File:[/bold red] {config_path}"))
    console.print(output)
Пример #2
0
def createTable(layer_two, layer_three, layer_four, packet, debug):
    sourceMac       = layer_two['sourceMac']
    destMac          = layer_two['destMac']
    ethernetType     = layer_two['ethernetType']
    sourceIp         = layer_three['sourceIp']
    destIp           = layer_three['destIp']
    protocol         = layer_four['protocol']
    
    print(Panel.fit("Packet [red]{}".format(packet)))

    table = Table(show_header=True, header_style="bold white", box=box.MINIMAL)
    table.add_column("Identifier", style="green", width=20)
    table.add_column("Value",  style="dim", width=20)

    table.add_row('Destination Mac Address', destMac)
    table.add_row("Source Mac Address", sourceMac)
    table.add_row('Ethernet Type', ethernetType)
    table.add_row('Destination IP Address', destIp)
    table.add_row('Source IP Address', sourceIp)
    if protocol is not None:
        table.add_row('Protocol', str(protocol))
    console.print(table)

    if debug is not None: 
        print(Panel.fit(debug))
Пример #3
0
def cli(repofile, dest):

    with open(repofile, 'r') as f:
        repocfg = yaml.safe_load(f)
    cprint(Panel.fit("Repo config"))
    cprint(repocfg)

    reponame = repocfg.get('name', splitext(basename(repofile)))
    repopath = join(dest, reponame)
    if exists(repopath):
        rmtree(repopath)

    makedirs(repopath)

    for d, fs in repocfg['files'].items():
        ad = join(repopath, d)
        if not exists(ad):
            makedirs(ad)

        for f, t in fs.items():
            with open(join(ad, f), 'w') as f:
                f.write(t)

    pm = Pathmaker(repopath if repocfg.get('multi_pkg', False) else dest)

    for t in repocfg['top']:
        cmp = t['cmp']
        pkg = t['pkg'] if 'pkg' in t else reponame

        cprint("Parsing", t)
        dp = DepFileParser('vivado', pm, {}, 0)
        # import ipdb
        # ipdb.set_trace()
        dp.parse(pkg, t['cmp'], t['file'])

        cprint('\n')
        cprint('-' * 80)
        cprint('   Summary   ', t['file'])
        cprint('-' * 80)
        cprint(">>> Commands")
        cprint(dp.commands)
        cprint(">>> Libs")
        cprint(dp.libs)
        cprint(">>> Errors")
        cprint(dp.errors)
        cprint(">>> Lost files")
        cprint(dp.unresolved)

        df = DepFormatter(dp)
        cprint(Panel.fit(df.draw_summary()))

        cprint(
            Panel.fit(df.draw_error_table(),
                      title='[bold red]dep tree errors[/bold red]'))
Пример #4
0
    def _drawComponents(self, aPkgs):
        if not aPkgs:
            return Panel.fit('')

        lString = ''
        for pkg in sorted(aPkgs):
            lString += '📦 %s (%d)\n' % (pkg, len(aPkgs[pkg]))
            lSortCmps = sorted(aPkgs[pkg])
            for cmp in lSortCmps[:-1]:
                lString += u'  ├─ ' + str(cmp) + '\n'
            lString += u'  └─ ' + str(lSortCmps[-1]) + '\n'

        return Panel.fit(lString[:-1])
Пример #5
0
def print_verbose(
    files_copied: list[str] | str,
    files_deleted: list[str] | str,
    errors_thrown: list[str] | str,
    warnings_given: list[str] | str,
):
    """print information on file copies and errors"""
    print_line: bool = False
    if files_copied:
        files_copied = "\n".join(files_copied)
        rich_print(
            Panel.fit(
                f"[green]{files_copied}",
                title="Files Copied",
                box=box.SQUARE,
            )
        )
        print_line = True
    elif files_deleted:
        files_deleted = "\n".join(files_deleted)
        rich_print(
            Panel.fit(
                f"[dark_orange]{files_deleted}",
                title="Files Deleted",
                box=box.SQUARE,
            )
        )
        print_line = True
    if warnings_given:
        if print_line:
            print()
        warnings_given = "\n".join(warnings_given)
        rich_print(
            Panel.fit(
                f"[orange1]{warnings_given}",
                title="Warnings",
                box=box.SQUARE,
            )
        )
        print_line = True
    if errors_thrown:
        if print_line:
            print()
        errors_thrown = "\n".join(errors_thrown)
        rich_print(
            Panel.fit(
                f"[red]{errors_thrown}",
                title="Errors",
                box=box.SQUARE,
            )
        )
Пример #6
0
def process(query, console):
    """Processes a given query and fetches the results from wikipedia.

    Keyword arguments:
    query -- The query 
    imag -- the imaginary part (default 0.0)
    """
    with Progress() as progress:
        # Querying the search to wikipedia and showing a progress bar for it
        task = progress.add_task("Querying wikipedia for \"" + query + "\"",
                                 total=1)
        ls = wikipedia.search(query)
        progress.advance(task)

    # Displaying a table which shows the 10 results we got from wikipedia
    table = Table(show_header=True, header_style='bold magenta')

    # Show the source of the results
    table.add_column("Source wikipedia")
    for x in range(len(ls)):
        table.add_row("[bold yellow]" + str(x) + "[/bold yellow] " + ls[x])

    # Show the table
    console.print(table)
    while True:
        # Ask the user what entry he wants to show, use q for exit
        key = console.input("[red](press 'q' to exit) >>> [/red]")
        if key == 'q':
            exit(0)
        else:
            try:
                # Throws if the key is not an integer
                val = ord(key)
                if val > 57 or val < 48:
                    return
                # String to int via conversion
                val = val - 48
                page = wikipedia.page(ls[val])

                # Print the results of the page
                console.print(
                    Panel.fit("[bold yellow]" + page.url +
                              "[/bold yellow]\n[bold magenta]" + page.title +
                              "[/bold magenta]",
                              title="url & title"))
                console.print(Panel.fit(page.content, title="content"))
                break
            except:
                console.print(
                    "[bold red]Try again, this time a number please.[/bold red]\n"
                )
Пример #7
0
def cli(ctx, obj, traceback, loglevel, cfg_dir):

    obj.print_traceback = traceback

    grid = Table(title='Shonky NanoRC', show_header=False, show_edge=False)
    grid.add_column()
    grid.add_row(
        "This is an admittedly shonky nanp RC to control DUNE-DAQ applications."
    )
    grid.add_row("  Give it a command and it will do your biddings,")
    grid.add_row("  but trust it and it will betray you!")
    grid.add_row("Use it with care!")

    obj.console.print(Panel.fit(grid))

    if loglevel:
        updateLogLevel(loglevel)

    try:
        rc = NanoRC(obj.console, cfg_dir)
    except Exception as e:
        logging.getLogger("cli").exception("Failed to build NanoRC")
        raise click.Abort()

    def cleanup_rc():
        logging.getLogger("cli").warning(
            "NanoRC context cleanup: Terminating RC before exiting")
        rc.terminate()

    ctx.call_on_close(cleanup_rc)
    obj.rc = rc
Пример #8
0
def launch(ssh_object):
    ssh_cmd = "ssh " + ssh_object["ssh"]
    if "message_rich" in ssh_object:
        rich.console
        console = Console()
        console.print(Panel.fit(ssh_object["message_rich"]))
    os.system(ssh_cmd)
Пример #9
0
def updatetwitchtitle(title):
    # updates stream title on Twitch via nightbot
    titlestring = updatercore("twitch", title)

    #chat.send("!title " + titlestring)

    return console.log(Panel.fit(titlestring, title="Twitch Title"))
Пример #10
0
def upcomingupdate(schedulelist):
    # updates the schedule text
    #? This might be slightly faster as a while loop seeing as all the math is already being done on 'i.'
    i = 1
    playlist = """"""
    for title in schedulelist:
        titlestring = ""
        namestring = ""
        numstring = ""
        artiststring = ""

        if title["title"]:
            if config['upcoming']['number'] == "yes":
                numstring = str(i) + config['upcoming']['afternumber'].strip(
                    '"')

            titlestring = numstring + updatercore("upcoming", title) + '\n'
            playlist += titlestring
        else:
            pass

        i += 1

        if i > int(config['upcoming']['count']):
            obsinstance.call(
                requests.SetTextGDIPlusProperties("upnext", text=playlist))
            return console.log(Panel.fit(playlist, title="Up Next"))

        #console.log("Updated Up Next item " + str(i))
    pass
Пример #11
0
def assemble_panels(data):
    global console
    panel_list = [
        Panel.fit(get_panel(dataset)) for dataset in grouper(
            sorted(data.items(), key=lambda x: x[0]), max_height(), ("", {}))
    ]
    return Columns(panel_list)
Пример #12
0
    def render(self, displays, bootstrap=True):
        b = self.board
        # Recover state
        for display in displays:
            self.round += 1
            if not display: continue
            status = display.get('status', None)
            if not status: status = []
            for pos in status:
                x = pos['row']
                y = pos['col']
                val = pos['val']
                b[x][y] = val
                if val == 9: self.mineleft -= 1

        message = 'Round: %d\nMines total: %d\nMines left: %d' % (
            self.round, self.minecount, self.mineleft)
        if displays:
            d = displays[-1]
            if not d: d = {}
            if 'msg' in d:
                if d['msg'] == 'INVALIDMOVE':
                    message += '\nInvalid move!'
                elif d['msg'] == 'FINISH':
                    message += '\nFinish!'
        t = Table.grid()
        for x in range(self.height):
            t.add_row(*(self.draw[b[x][y]] for y in range(self.width)))
        tt = Table.grid(padding=(0, 4))
        tt.add_row(t, message)
        print(Panel.fit(tt, box=box.SQUARE))
Пример #13
0
def runInMenu(stDict):
    ssh_cmd = "ssh " + stDict["ssh"]
    if "message_rich" in stDict:
        rich.console
        console = Console()
        console.print(Panel.fit(stDict["message_rich"]))
    os.system(ssh_cmd)
Пример #14
0
    def unexpected_exception(self) -> None:
        """
        Call this in an "except" clause to log an unexpected exception.
        """

        t, v, tb = sys.exc_info()
        if t is None or v is None or tb is None:
            # We're not currently handling an exception, so somebody probably
            # called this function where they shouldn't.
            self.error("Something unexpected happened")
            self.error_contd("")
            for line in traceback.format_stack():
                self.error_contd(line[:-1])  # Without the newline
            self.error_contd("")
        else:
            self.error("An unexpected exception occurred")
            self.error_contd("")
            self.error_contd(traceback.format_exc())

        # Our print function doesn't take types other than strings, but the
        # underlying rich.print function does. This call is a special case
        # anyways, and we're calling it internally, so this should be fine.
        self.print(
            Panel.fit("""
Please copy your program output and send it to the PFERD maintainers, either
directly or as a GitHub issue: https://github.com/Garmelon/PFERD/issues/new
        """.strip()))  # type: ignore
Пример #15
0
    def render(self, displays, bootstrap=True):
        b = self.board
        # Recover state
        for display in displays:
            self.round += 1
            if not display: display = {}
            change = []
            if 'x' not in display: continue
            if 'x' in display:
                x = display['x']
                y = display['y']
                if x == -1: continue
                color = 2 - self.round % 2
                b[x][y] = color
                self.count[color] += 1
                for dx, dy in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1),
                               (1, -1), (1, 0), (1, 1)):
                    t = []
                    nx = x + dx
                    ny = y + dy
                    while self._in_board(nx, ny) and b[nx][ny] == 3 - color:
                        t.append((nx, ny))
                        nx += dx
                        ny += dy
                    if not (self._in_board(nx, ny) and b[nx][ny] == color):
                        continue
                    change.extend(t)
                for nx, ny in change:
                    b[nx][ny] = color
                self.count[color] += len(change)
                self.count[3 - color] -= len(change)

        message = 'Round: %d\n%s: %d\n%s: %d\nNext: %s' % (
            self.round, self.stones[1], self.count[1], self.stones[2],
            self.count[2], self.stones[1 + self.round % 2])
        style_cur = lambda s: Text(s, style='red')
        style_change = lambda s: Text(s, style='yellow')
        style_normal = lambda s: s
        styles = [[style_normal for i in range(8)] for j in range(8)]
        if displays:
            d = displays[-1]
            if not d: d = {}
            x = d.get('x', -1)
            y = d.get('y', -1)
            if x == -1 and self.round:
                message += '\n%s skipped!' % self.stones[2 - self.round % 2]
            else:
                styles[x][y] = style_cur
            if 'winner' in d:
                message += '\n%s wins!' % self.stones[d['winner'] + 1]
            for x, y in change:
                styles[x][y] = style_change
        t = Table.grid(padding=(0, 1))
        t.add_row('', *map(chr, range(65, 65 + 8)))
        for j in range(8):
            t.add_row(str(1 + j),
                      *[styles[i][j](self.stones[b[i][j]]) for i in range(8)])
        tt = Table.grid(padding=(0, 4))
        tt.add_row(t, message)
        print(Panel.fit(tt, box=box.SQUARE))
Пример #16
0
 def render(self, displays, bootstrap = True):
     b = self.board
     x = y = -1
     # Recover state
     for display in displays:
         self.round += 1
         if not display: continue
         if 'x' not in display: continue
         x = display['x']
         y = display['y']
         color = 2 - self.round % 2
         self.board[x][y] = color
     
     message = 'Round: %d' % self.round
     if displays and displays[-1]:
         winner = displays[-1].get('winner', None)
     elif self.round == 9:
         winner = ''
     else:
         winner = None
     if winner is not None:
         if isinstance(winner, int):
             message += '\n%s wins!' % self.stones[winner + 1]
         else:
             message += '\nA tie!'
     else:
         message += '\nNext: %s' % self.stones[self.round % 2 + 1]
     t = Table.grid(padding = (0, 1))
     t.add_row('', *map(chr, range(65, 65 + 3)))
     for j in range(3):
         t.add_row(str(1 + j), *[Text(self.stones[b[i][j]], style = 'red') if i == x and j == y else self.stones[b[i][j]] for i in range(3)])
     tt = Table.grid(padding = (0, 4))
     tt.add_row(t, message)
     print(Panel.fit(tt, box = box.SQUARE))
Пример #17
0
def pre_run_check():

    pkgs_exist = {name: is_tool(name) for name in PACKAGES}
    if False in pkgs_exist.values():
        console.print("\n[red bold] FAILED PRE-RUN CHECKS!!\n")

        table = Table(box=box.SIMPLE,
                      header_style="bold cyan",
                      collapse_padding=True)

        table.add_column("package", justify="right")
        table.add_column("found?", justify="left")
        for name, exists in pkgs_exist.items():
            if exists:
                found = "[green] yes"
            else:
                found = "[red] no"
            table.add_row(name, found)

        console.print(Panel.fit(
            table,
            title="Dependencies",
        ))

        console.print(
            "It's recommended to install pycashier within a conda environment."
        )
        console.print(
            "See README on github for details: [link]https://github.com/brocklab/pycashier[/link]"
        )
        sys.exit(1)
Пример #18
0
def show_toolbox_apps(toolbox: ToolBox) -> Dict[str, list[str]]:
    apps = toolbox.apps()

    columns = {"available": [], "unavailable": []}

    for app, path in apps.items():
        if any(map(lambda x: app.lower().startswith(x.lower()), working)):
            columns["available"].append(app)
        else:
            columns["unavailable"].append(app)

    panel = Text()

    for i, available in enumerate(columns["available"], start=1):
        left = (f"{i}. ", "bold gray")
        right = (f"{available}\n", "green")

        panel.append(Text.assemble(left, right))

    for unavailable in columns["unavailable"]:
        panel.append(Text(f"   {unavailable}\n", style="red"))

    console.print(Align.center(Panel.fit(panel, title="Available IDEs")))

    return columns
Пример #19
0
 def caution(line: str, title: str = 'Caution!', align='left', padding=0):
     """提示,注意事项的log"""
     _console.log(Panel.fit(
         line,
         title=f'[bold cyan]{title}[/bold cyan]',
         border_style='cyan',
         padding=padding,
     ), justify=align)
Пример #20
0
 def error(line: str, title: str = 'Error!', align='left', padding=0):
     """提示错误的log"""
     _console.log(Panel.fit(
         line,
         title=f'[bold red]{title}[/bold red]',
         border_style='red',
         padding=padding,
     ), justify=align)
Пример #21
0
 def done(line: str, title: str = 'Completed!', align='left', padding=0):
     """提示完成的log"""
     _console.log(Panel.fit(
         line,
         title=f'[green bold]{title}[/green bold]',
         border_style='green',
         padding=padding,
     ), justify=align)
Пример #22
0
 def build_raw_response(self):
     return Panel.fit(
         f"[bold]{self.response.request.method}[/] {self.response.status_code}\n"
         f"[underline]{self.response.request.url}[/]\n"
         f"{parse_headers(self.response.headers, join=': ')}\n\n"
         f"{self.response.text if self.response.is_stream_consumed else '<Stream content>'}\n",
         title="Bad response",
     )
Пример #23
0
 def connect_to_devices(self, testbed):
     """Connect to all the devices"""
     print(
         Panel.fit(
             Text.from_markup(
                 "Hang on tight - we are about to go on a [bold blue]Magic[/bold blue] [bold yellow]Carpet[/bold yellow] ride!\n\n[purple].-.\n[.-''-.,\n|  //`~\)\n(<|[/][blue]0[/][purple]|>[/][blue]0[/][purple])\n;\  _/ \\_ _\,\n__\|'._/_  \ '='-,\n/\ \    || )_///_\>>\n(  '._ T |\ | _/),-'\n'.   '._.-' /'/ |\n| '._   _.'`-.._/\n,\ / '-' |/\n[_/\-----j\n_.--.__[_.--'_\__\n/         `--'    '---._\n/ '---.  -'. .'  _.--   '.\n\_      '--.___ _;.-o     /\n'.__ ___/______.__8----'\nc-'----'[/]\n\n",
                 justify="center")))
     testbed.connect()
Пример #24
0
def command_finish(*args, **kwargs):
    if state["timeStart"]:
        elapsedTime = time.time() - state["timeStart"]
        console.print(
            Panel.fit(
                f":stopwatch:  Execution time: [bold yellow]{elapsedTime}"),
            style="bold green",
        )
Пример #25
0
 def start(line:str,title:str='Start!',align='left',padding=0):
     """提示开始的log"""
     console.log(Panel.fit(
         line,
         title=f'[green bold]{title}[/green bold]',
         border_style='green',
         padding=padding,
     ),justify=align)
Пример #26
0
 def nice_print(keyword, since_date, til_date, max_tweets):
     print(
         Panel.fit(
             f'Palavra Chave: {keyword} \n'
             f'De {since_date} até {til_date}\n'
             f'Tweets Buscados: {max_tweets}',
             title="[bold blue] Parâmetros da Busca[/bold blue]",
             border_style='magenta'))
Пример #27
0
def bye():
    console.print(Panel.fit(
        '''    [bold red]Thank YOU [/bold red][bold]for using  youtube downloader 
        If you enjoy it, feel free to leave a [/bold][bold red]Star[/bold red]
        [italic bold yellow]https://github.com/ahmedasad236/YouTube-Downloader[/italic bold yellow]
        [italic cyan]Feedback and contribution is welcome as well :smiley:![/italic cyan]
            ''',
        title="Bye!"),
                  justify="center")
Пример #28
0
 def __rich_console__(self, console: Console,
                      options: ConsoleOptions) -> RenderResult:
     yield Columns([
         Panel.fit(
             Backend(backend.used, backend.available),
             box=box.SQUARE,
             title=emojify_device(backend.device),
         ) for backend in self.backends.values()
     ], )
Пример #29
0
def section(title: str) -> Iterator[list]:
    column_list = []
    yield column_list
    if column_list:
        columns = '\n'.join(column_list)
        console.print(
            Panel.fit(columns,
                      title=title,
                      border_style='dim',
                      title_align='center'))
Пример #30
0
def draw_card():
    """抽卡片"""
    global current_card
    l = len(desktop_cards)
    i = random.randint(0, l-1)
    current_card = desktop_cards[i]
    desktop_cards.remove(current_card)  # 从桌面移除该负数卡片
    """显示抽中的卡片"""
    console.print("玩家 [yellow]%s[/yellow] 正在抽卡片……" % current_player["name"], Panel.fit(
        str(current_card["value"]), title="抽出的卡片", style="yellow on red"))