Esempio n. 1
0
def render_tables():
    console = Console(
        width=60,
        force_terminal=True,
        file=io.StringIO(),
        legacy_windows=False,
        color_system=None,
    )

    table = Table(title="test table", caption="table caption", expand=True)
    table.add_column("foo", footer=Text("total"), no_wrap=True, overflow="ellipsis")
    table.add_column("bar", justify="center")
    table.add_column("baz", justify="right")

    table.add_row("Averlongwordgoeshere", "banana pancakes", None)

    assert Measurement.get(console, table, 80) == Measurement(41, 48)

    for width in range(10, 60, 5):
        console.print(table, width=width)

    table.expand = False
    console.print(table, justify="left")
    console.print(table, justify="center")
    console.print(table, justify="right")

    assert table.row_count == 1

    table.row_styles = ["red", "yellow"]
    table.add_row("Coffee")
    table.add_row("Coffee", "Chocolate", None, "cinnamon")

    assert table.row_count == 3

    console.print(table)

    table.show_lines = True
    console.print(table)

    table.show_footer = True
    console.print(table)

    table.show_edge = False

    console.print(table)

    table.padding = 1
    console.print(table)

    table.width = 20
    assert Measurement.get(console, table, 80) == Measurement(20, 20)
    console.print(table)

    table.columns[0].no_wrap = True
    table.columns[1].no_wrap = True
    table.columns[2].no_wrap = True

    console.print(table)

    table.padding = 0
    table.width = 60
    table.leading = 1
    console.print(table)

    return console.file.getvalue()
# -*- coding: utf-8 -*-
# =============================================================================
# Author :  Will Grant
# =============================================================================

from rich.console import Console
from rich.table import Column, Table

console = Console()

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row("Dev 20, 2019", "Star Wars: The Rise of Skywalker",
              "$275,000,000", "$375,126,118")
table.add_row(
    "May 25, 2018",
    "[red]Solo[/red]: A Star Wars Story",
    "$275,000,000",
    "$393,151,347",
)
table.add_row(
    "Dec 15, 2017",
    "Star Wars Ep. VIII: The Last Jedi",
    "$262,000,000",
    "[bold]$1,332,539,889[/bold]",
)

console.print(table)
Esempio n. 3
0
                    fdelta_max = Text(
                        f"{max(with_result):.3f} ({delta_max:.1f}%)",
                        style="green")
                else:
                    fdelta_max = Text(
                        f"{max(with_result):.3f} (-{delta_max:.1f}%)",
                        style="red")

                if fmean(with_result) < fmean(without_result):
                    fdelta_mean = Text(
                        f"{fmean(with_result):.3f} ({delta_mean:.1f}%)",
                        style="green")
                else:
                    fdelta_mean = Text(
                        f"{fmean(with_result):.3f} (-{delta_mean:.1f}%)",
                        style="red")

                table.add_row(
                    desc,
                    str(repeat),
                    "{:.3f}".format(min(without_result)),
                    "{:.3f}".format(max(without_result)),
                    "{:.3f}".format(fmean(without_result)),
                    fdelta_min,
                    fdelta_max,
                    fdelta_mean,
                )

    console = Console(width=150)
    console.print(table)
Esempio n. 4
0
# Rich is a Python library for rich text and beautiful formatting in the terminal.
# The Rich API makes it easy to add color and style to terminal output.
# Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code,
# tracebacks, and more — out of the box.

from rich.console import Console
from rich.table import Table

table = Table(title="Pandas Versions")

table.add_column("Released", style="cyan")
table.add_column("Version Number", justify="right", style="magenta")
table.add_column("Description", style="green")

table.add_row("May 29, 2020", "v1.0.4", "Just an update.")
table.add_row("Mar 18, 2020", "v1.0.3", "Just an update.")
table.add_row("Mar 15, 2020", "v1.0.2", "Just an update.")
table.add_row("Feb 05, 2020", "v1.0.1",
              ":thumbs_up: [underline]Big[/] update.")

console = Console()
console.print(table)
Esempio n. 5
0
        table.title = (
            "[not italic]:popcorn:[/] Star Wars Box Office [not italic]:popcorn:[/]"
        )

    with beat(10):
        table.caption = "Made with Rich"

    with beat(10):
        table.caption = "Made with [b]Rich[/b]"

    with beat(10):
        table.caption = "Made with [b magenta not dim]Rich[/]"

    for row in TABLE_DATA:
        with beat(10):
            table.add_row(*row)

    with beat(10):
        table.show_footer = True

    table_width = console.measure(table).maximum

    with beat(10):
        table.columns[2].justify = "right"

    with beat(10):
        table.columns[3].justify = "right"

    with beat(10):
        table.columns[4].justify = "right"
Esempio n. 6
0
    def train(self,
              *,
              epochs: Optional[int] = None,
              device: str = "cpu") -> None:
        model_type = self._config.model_type
        if epochs is None:
            epochs = self._config.epochs
        self._device = device
        self._priors = self._config.priors
        self._epochs = epochs
        self.irt_model = IRT_MODELS[model_type](
            priors=self._config.priors,
            device=device,
            num_items=len(self._dataset.ix_to_item_id),
            num_subjects=len(self._dataset.ix_to_subject_id),
        )
        pyro.clear_param_store()
        self._pyro_model = self.irt_model.get_model()
        self._pyro_guide = self.irt_model.get_guide()
        device = torch.device(device)
        lr = 0.1
        gamma = 0.9999
        scheduler = pyro.optim.ExponentialLR({
            "optimizer": torch.optim.Adam,
            "optim_args": {
                "lr": lr
            },
            "gamma": gamma
        })
        svi = SVI(self._pyro_model,
                  self._pyro_guide,
                  scheduler,
                  loss=Trace_ELBO())
        subjects = torch.tensor(self._dataset.observation_subjects,
                                dtype=torch.long,
                                device=device)
        items = torch.tensor(self._dataset.observation_items,
                             dtype=torch.long,
                             device=device)
        responses = torch.tensor(self._dataset.observations,
                                 dtype=torch.float,
                                 device=device)

        # Don't take a step here, just make sure params are initialized
        # so that initializers can modify the params
        _ = self._pyro_model(subjects, items, responses)
        _ = self._pyro_guide(subjects, items, responses)
        for init in self._initializers:
            init.initialize()
        table = Table()
        table.add_column("Epoch")
        table.add_column("Loss")
        table.add_column("Best Loss")
        table.add_column("New LR")
        loss = float("inf")
        best_loss = loss
        current_lr = lr
        with Live(table) as live:
            live.console.print(f"Training Pyro IRT Model for {epochs} epochs")
            for epoch in range(epochs):
                loss = svi.step(subjects, items, responses)
                if loss < best_loss:
                    best_loss = loss
                    self.best_params = self.export()
                scheduler.step()
                current_lr = current_lr * gamma
                if epoch % 100 == 0:
                    table.add_row(f"{epoch + 1}", "%.4f" % loss,
                                  "%.4f" % best_loss, "%.4f" % current_lr)

            table.add_row(f"{epoch + 1}", "%.4f" % loss, "%.4f" % best_loss,
                          "%.4f" % current_lr)
Esempio n. 7
0
        ['老年', '否', '否', '一般'],
    ]
    Y = [
        '否', '否', '是', '是', '否', '否', '否', '是', '是', '是', '是', '是', '是', '是',
        '否'
    ]
    id3.fit(X, Y)

    # prune with alpha 0.
    prune(id3.root, X, Y, 0.)

    # show in table
    pred = id3.predict(X)
    table = Table('x', 'y', 'pred')
    for x, y, y_hat in zip(X, Y, pred):
        table.add_row(*map(str, [x, y, y_hat]))
    console.print(table)

    # -------------------------- Example 2 (Large Normalization Param) ------------
    print("Example 2:")
    id3 = ID3(verbose=False)
    X = [
        ['青年', '否', '否', '一般'],
        ['青年', '否', '否', '好'],
        ['青年', '是', '否', '好'],
        ['青年', '是', '是', '一般'],
        ['青年', '否', '否', '一般'],
        ['老年', '否', '否', '一般'],
        ['老年', '否', '否', '好'],
        ['老年', '是', '是', '好'],
        ['老年', '否', '是', '非常好'],
Esempio n. 8
0
def find_mismatched_dashes(plain_output: bool) -> int:
    """
	Entry point for `se find-mismatched-dashes`
	"""

    parser = argparse.ArgumentParser(
        description=
        "Find words with mismatched dashes in a set of XHTML files. For example, `extra-physical` in one file and `extraphysical` in another."
    )
    parser.add_argument(
        "targets",
        metavar="TARGET",
        nargs="+",
        help="an XHTML file, or a directory containing XHTML files")
    args = parser.parse_args()

    console = Console(
        highlight=False, theme=se.RICH_THEME
    )  # Syntax highlighting will do weird things when printing paths
    return_code = 0
    dashed_words: Dict[str, int] = {}  # key: word; value: count
    mismatches: Dict[str, Dict[str, Tuple[int, int]]] = {
    }  # key: base word; value: dict with key: plain word; value: (base count, plain count)
    target_filenames = se.get_target_filenames(args.targets, ".xhtml")
    files_xhtml = []

    # Read files and cache for later
    for filename in target_filenames:
        try:
            with open(filename, "r", encoding="utf-8") as file:
                xhtml = file.read()
                dom = se.easy_xml.EasyXmlTree(xhtml)

                # Save any `alt` and `title` attributes because we may be interested in their contents
                for node in dom.xpath("//*[@alt or @title]"):
                    for _, value in node.attrs.items():
                        xhtml = xhtml + f" {value} "

                # Strip tags
                xhtml = regex.sub(r"<[^>]+?>", " ", xhtml)

                files_xhtml.append(xhtml)

        except FileNotFoundError:
            se.print_error(
                f"Couldn’t open file: [path][link=file://{filename}]{filename}[/][/].",
                plain_output=plain_output)
            return_code = se.InvalidInputException.code

    # Create a list of dashed words
    for xhtml in files_xhtml:
        # This regex excludes words with three dashes like `bric-a-brac`, because removing dashes
        # may erroneously match regular words. Don't match `’` to prevent matches like `life’s-end` -> `s-end`
        for word in regex.findall(r"(?<![\-’])\b\w+\-\w+\b(?![\-’])", xhtml):
            lower_word = word.lower()

            if lower_word in dashed_words:
                dashed_words[lower_word] = dashed_words[lower_word] + 1
            else:
                dashed_words[lower_word] = 1

    # Now iterate over the list and search files for undashed versions of the words
    if dashed_words:
        for xhtml in files_xhtml:
            for dashed_word, count in dashed_words.items():
                plain_word = dashed_word.replace("-", "")

                matches = regex.findall(fr"\b{plain_word}\b",
                                        xhtml,
                                        flags=regex.IGNORECASE)

                if matches:
                    if dashed_word in mismatches:
                        if plain_word in mismatches[dashed_word]:
                            mismatches[dashed_word][plain_word] = (
                                count, mismatches[dashed_word][plain_word][1] +
                                len(matches))
                        else:
                            mismatches[dashed_word][plain_word] = (
                                count, len(matches))

                    else:
                        mismatches[dashed_word] = {}
                        mismatches[dashed_word][plain_word] = (count,
                                                               len(matches))

    # Sort and prepare the output
    lines = []

    for dashed_word, child in mismatches.items():
        for plain_word, counts in child.items():
            lines.append((dashed_word, counts[0], plain_word, counts[1]))

    lines.sort()

    if lines:
        if plain_output:
            for dashed_word, dashed_word_count, plain_word, plain_word_count in lines:
                console.print(
                    f"{dashed_word} ({dashed_word_count})\t{plain_word} ({plain_word_count})"
                )

        else:
            table = Table(show_header=False,
                          show_lines=True,
                          box=box.HORIZONTALS)
            table.add_column("Dashed word")
            table.add_column("Count", style="dim", no_wrap=True)
            table.add_column("Plain word")
            table.add_column("Count", style="dim", no_wrap=True)

            for dashed_word, dashed_word_count, plain_word, plain_word_count in lines:
                table.add_row(
                    f"[link=https://www.merriam-webster.com/dictionary/{urllib.parse.quote(dashed_word)}]{dashed_word}[/]",
                    f"({dashed_word_count})",
                    f"[link=https://www.merriam-webster.com/dictionary/{urllib.parse.quote(plain_word)}]{plain_word}[/]",
                    f"({plain_word_count})")

            console.print(table)

    return return_code
Esempio n. 9
0
def display_files(
    pcs_files: List[PcsFile],
    remotepath: Optional[str],
    sifters: List[Sifter] = [],
    highlight: bool = False,
    show_size: bool = False,
    show_date: bool = False,
    show_md5: bool = False,
    show_absolute_path: bool = False,
    show_dl_link: bool = False,
    show_hash_link: bool = False,
    hash_link_protocol: str = PcsRapidUploadInfo.default_hash_link_protocol(),
    csv: bool = False,
):
    if not pcs_files:
        return

    table = Table(box=SIMPLE, padding=0, show_edge=False)
    table.add_column()
    headers = []  # for csv
    headers.append("\t")
    if show_size:
        header = "Size"
        table.add_column(header, justify="right")
        headers.append(header)
    if show_date:
        header = "Modified Time"
        table.add_column(header, justify="center")
        headers.append(header)
    if show_md5:
        header = "md5"
        table.add_column(header, justify="left")
        headers.append(header)
    header = "Path"
    table.add_column(header, justify="left", overflow="fold")
    headers.append(header)
    if show_dl_link:
        header = "Download Link"
        table.add_column(header, justify="left", overflow="fold")
        headers.append(header)
    if show_hash_link:
        header = "Hash Link"
        table.add_column(header, justify="left", overflow="fold")
        headers.append(header)

    rows = []  # for csv

    max_size_str_len = max([len(str(pcs_file.size)) for pcs_file in pcs_files])
    for pcs_file in pcs_files:
        row: List[Union[str, Text]] = []

        if csv:
            row.append("-")
        else:
            tp = Text("-", style="bold red")
            row.append(tp)

        if show_size:
            size = human_size(pcs_file.size) if pcs_file.size else ""
            if csv:
                row.append(f"{size} {pcs_file.size}")
            else:
                row.append(f"{size} {pcs_file.size: >{max_size_str_len}}")
        if show_date:
            date = format_date(
                pcs_file.local_mtime) if pcs_file.local_mtime else ""
            row.append(date)
        if show_md5:
            md5 = pcs_file.md5 or ""
            row.append(md5)

        path = pcs_file.path if show_absolute_path else Path(
            pcs_file.path).name
        background = Text()
        if pcs_file.is_dir:
            if csv:
                row[0] = "d"
            else:
                tp._text = ["d"]
                background.style = "blue"

        if highlight and sifters:
            pats: List[Union[Pattern, str]] = list(
                filter(None, [
                    sifter.pattern() for sifter in sifters if sifter.include()
                ]))
            highlighter = Highlighter(pats, "yellow")
            _path = highlighter(path)
        else:
            _path = Text(path)

        if csv:
            row.append(path)
        else:
            row.append(background + _path)

        if show_dl_link:
            row.append(pcs_file.dl_link or "")

        rpinfo = pcs_file.rapid_upload_info
        if show_hash_link:
            link = ""
            if rpinfo:
                link = rpinfo.cs3l()
            row.append(link)

        if csv:
            rows.append(row)
        else:
            table.add_row(*row)

    if csv:
        _print(remotepath)
        _print("\t".join(headers))
        for row in rows:
            _print("\t".join(row))  # type: ignore
    else:
        console = Console()
        if remotepath:
            title = Text(remotepath, style="italic green")
            console.print(title)
        console.print(table)
Esempio n. 10
0
console = Console()

console.print('gathering data...', justify='center')

while True:

    # populated by beets_stats.sh
    stats = Path('/Users/stvnrlly/dev/dotfiles/data/stats').read_text().splitlines()
    flac_stats = Path('/Users/stvnrlly/dev/dotfiles/data/flac_stats').read_text().splitlines()
    mp3_stats = Path('/Users/stvnrlly/dev/dotfiles/data/mp3_stats').read_text().splitlines()
    missing = Path('/Users/stvnrlly/dev/dotfiles/data/missing').read_text().splitlines()

    non_format = int(stats[4].split(':')[1].strip()) - (int(flac_stats[4].split(':')[1].strip()) + int(mp3_stats[4].split(':')[1].strip()))

    console.clear()

    table = Table(box=box.SIMPLE)
    table2 = Table(box=box.SIMPLE)

    # print(stats)
    table.add_row('Total albums', stats[4].split(':')[1].strip(), stats[2].split(':')[1].strip())
    table.add_row('FLAC albums', flac_stats[4].split(':')[1].strip(), flac_stats[2].split(':')[1].strip())
    table.add_row('MP3 albums', mp3_stats[4].split(':')[1].strip(), mp3_stats[2].split(':')[1].strip())
    table2.add_row('Incomplete albums', str(len(missing)))
    table2.add_row('Other formats', str(non_format))

    # window.select_pane(2)
    console.print(table, justify='center')
    console.print(table2, justify='center')

    time.sleep(120)
Esempio n. 11
0
    def summary(
        self,
        x: tp.Optional[tp.Any] = None,
        depth: int = 2,
        tablefmt: str = "fancy_grid",
        return_repr: bool = False,
        initialize: bool = False,
        eval_shape: bool = True,
        **tablulate_kwargs,
    ) -> tp.Optional[str]:
        """
        Prints a summary of the network.
        Arguments:
            x: A sample of inputs to the network.
            depth: The level number of nested level which will be showed.
                Information about summaries from modules deeper than `depth`
                will be aggregated together.
            tablefmt: A string representing the style of the table generated by
                `tabulate`. See
                [python-tabulate](https://github.com/astanin/python-tabulate)
                for more options.
            tablulate_kwargs: Additional keyword arguments passed to `tabulate`.
                See [python-tabulate](https://github.com/astanin/python-tabulate)
                for more options.
        """

        if x is None:
            x = {}

        entries: tp.List[types.SummaryTableEntry]
        states = self.states.copy() if self.run_eagerly else self.states

        method = (self.call_summary_step
                  if self.run_eagerly else self.call_summary_step_jit)

        if eval_shape:
            entries = jax.eval_shape(self.call_summary_step, x, states)
        else:
            entries = method(x, states)

        total_entry = entries[-1]
        entries = entries[:-1]

        depth_groups: tp.Dict[
            str, tp.List[types.SummaryTableEntry]] = toolz.groupby(
                lambda entry: "/".join(entry.path.split("/")[:depth]), entries)

        entries = [
            utils.get_grouped_entry(entry, depth_groups) for entry in entries
            if entry.path in depth_groups
        ]

        main_table = Table(
            show_header=True,
            show_lines=True,
            show_footer=True,
            # box=rich.box.HORIZONTALS,
        )

        main_table.add_column("Layer")
        main_table.add_column("Outputs Shape")
        main_table.add_column("Trainable\nParameters")
        main_table.add_column("Non-trainable\nParameters")

        rows: tp.List[tp.List[str]] = []

        rows.append(["Inputs", utils.format_output(x), "", ""])

        for entry in entries:
            rows.append([
                f"{entry.path}{{pad}}  " + (f"[dim]{entry.module_type_name}[/]"
                                            if entry.module_type_name else ""),
                utils.format_output(entry.output_value),
                f"[green]{entry.trainable_params_count:,}[/]{{pad}}    {utils.format_size(entry.trainable_params_size)}"
                if entry.trainable_params_count > 0 else "",
                f"[green]{entry.non_trainable_params_count:,}[/]{{pad}}    {utils.format_size(entry.non_trainable_params_size)}"
                if entry.non_trainable_params_count > 0 else "",
            ])

        # global summaries
        params_count = total_entry.trainable_params_count
        params_size = total_entry.trainable_params_size
        states_count = total_entry.non_trainable_params_count
        states_size = total_entry.non_trainable_params_size
        total_count = params_count + states_count
        total_size = params_size + states_size

        rows.append([
            "",
            "Total",
            (f"[green]{params_count:,}[/]{{pad}}    {utils.format_size(params_size)}"
             if params_count > 0 else ""),
            (f"[green]{states_count:,}[/]{{pad}}    {utils.format_size(states_size)}"
             if states_count > 0 else ""),
        ])

        # add padding
        for col in range(4):
            max_length = max(
                len(line.split("{pad}")[0]) for row in rows
                for line in row[col].split("\n"))

            for row in rows:
                row[col] = "\n".join(
                    line.format(
                        pad=" " *
                        (max_length - len(line.rstrip().split("{pad}")[0])))
                    for line in row[col].rstrip().split("\n"))

        for row in rows[:-1]:
            main_table.add_row(*row)

        main_table.columns[1].footer = Text.from_markup(rows[-1][1],
                                                        justify="right")
        main_table.columns[2].footer = rows[-1][2]
        main_table.columns[3].footer = rows[-1][3]
        main_table.caption_style = "bold"
        main_table.caption = (
            "\nTotal Parameters: " +
            f"[green]{total_count:,}[/]   {utils.format_size(total_size)}"
            if total_count > 0 else "")

        summary = "\n" + utils.get_table_repr(main_table)

        print(summary)

        if return_repr:
            return summary
Esempio n. 12
0
def search_book(search_string):
    """
    Search books from search_string and print the book list
    """
    start = time.time()
    console = Console()

    with console.status("[bold green]Working on tasks...") as status:
        res = requests.get("https://b-ok.asia/s/?q=" + search_string)
        soup = BeautifulSoup(res.text, 'html.parser')
        items = soup.findAll('table', {'class': 'resItemTable'})
        data = []

        for item in items:
            id = item.tr.td.div['data-book_id']
            link = item.tr.td.a['href']
            head = item.tr.findAll('td', recursive=False)[1].table

            name = head.tr.td.h3.a.getText()
            publisher = head.tr.td.div.a.getText()
            authors = []
            authors_div = head.tr.td.findAll('div', recursive=False)

            if len(authors_div) > 1:
                authors = [i.getText() for i in authors_div[1].findAll('a')]

            t = head.findAll('tr', recursive = False)[1]\
                    .td\
                    .findAll('div', recursive = False)[1]\
                    .findAll('div', recursive = False)
            details = list(
                map(
                    lambda x:
                    [fr.getText() for fr in x.findAll('div', recursive=False)],
                    t))

            year = details[0][1]
            language = details[1][1]
            file_size = details[2][1]

            data.append({
                "id": id,
                "name": name,
                "publisher": publisher,
                "authors": authors,
                "year": year,
                "language": language,
                "file": file_size,
                "link": link
            })

    table = Table(title="Book Searching",
                  show_header=True,
                  header_style="bold bright_red")

    table.add_column("[cyan]STT[/cyan]", justify="center", style="cyan")
    table.add_column("[yellow]Name[/yellow]", style="yellow")
    table.add_column("[green]Publisher[/green]", justify="left", style="green")
    table.add_column("[magenta]Authors[/magenta]",
                     justify="left",
                     style="magenta")
    table.add_column("[blue]Year[/blue]", justify="right", style="blue")
    table.add_column("[green_yellow]Language[/green_yellow]",
                     justify="center",
                     style="green_yellow")
    table.add_column("[turquoise4]File[/turquoise4]",
                     justify="left",
                     style="turquoise4")

    stt = 1
    for d in data:
        table.add_row(str(stt), d['name'] + '\n', d['publisher'],
                      ",\n".join(d['authors']), d['year'], d['language'],
                      d['file'])
        stt += 1

    console.print(table)
    print("Time: {:.3f}s\n".format(time.time() - start))

    print_usage_1()
    option = console.input("[bright_blue]>>> [/bright_blue]")

    while option not in ("/back", "/b"):
        if option in ("/quit", "/q"):
            console.print("[bright_red]Exit[/bright_red]")
            exit(0)
        if option in ("/help", "/h"):
            print_usage_1()
        elif len(option.split(' ')) == 2:
            optionplt = option.split()
            if optionplt[0] in ("/detail", "/dt") and\
               optionplt[1].isnumeric() and\
               1 <= int(optionplt[1]) <= len(data):
                go_to_details(data[int(optionplt[1]) - 1])
            else:
                console.print("[bright_red]Invalid Input[/bright_red]")
        else:
            console.print("[bright_red]Invalid Input[/bright_red]")
        option = console.input("[bright_blue]>>> [/bright_blue]")
Esempio n. 13
0
def speed_test(
    use_cache: bool = typer.Option(False, "--use-cache", "-u"),
    test_count: int = typer.Option(default=5),
    start: int = typer.Option(
        100,
        "--start",
        "-s",
        help="What power should the MP search begin with?",
    ),
    end: int = typer.Option(
        120,
        "--end",
        "-e",
        help="What power should the MP search end with?",
    ),
):
    console = Console()
    test_results = {"start": start, "end": end, "old": [], "new": []}
    with open("tmp/speed-test-cache.json") as f:
        cache = json.load(f)

    # Don't use the cache if it doesn't match the requested parameters
    if cache["start"] != start or cache["end"] != end:
        use_cache = False
        console.print(
            f"Cache doesn't match requested parameters. Not using cache.")

    if use_cache:
        test_results["old"] = cache["old"]
        test_results["old_dict"] = cache["old_dict"]
    else:
        console.print("Processing old explorer...")
        for _ in range(test_count):
            explorer_o = Explorer()
            explorer_o.explore(start, end)
            seconds = explorer_o.run_time
            test_results["old"].append(seconds)
        test_results["old_dict"] = explorer_o.collection.to_dict()

    console.print("Processing speedy explorer...")
    for _ in range(test_count):
        explorer_n = SpeedyExplorer()
        explorer_n.explore(start, end)
        seconds = explorer_n.run_time
        test_results["new"].append(seconds)
    test_results["new_dict"] = explorer_n.collection.to_dict()

    with open("tmp/speed-test-cache.json", "w") as f:
        json.dump(test_results, f, indent=4)

    ##
    # Ensure that refactoring didn't cause numbers to be missed
    assert test_results["new_dict"] == test_results["old_dict"], DeepDiff(
        test_results["old_dict"], test_results["new_dict"])

    ##
    # Calculate and display results
    table = Table(show_footer=False)
    table.add_column("Test")
    table.add_column("Original")
    table.add_column("Speedy")

    for i, (test_o,
            test_n) in enumerate(zip(test_results["old"],
                                     test_results["new"])):
        table.add_row(str(i), str(test_o), str(test_n))

    avg_o = round(sum(test_results["old"]) / len(test_results["old"]), 2)
    avg_n = round(sum(test_results["new"]) / len(test_results["new"]), 2)
    table.add_row("Average", str(avg_o), str(avg_n))

    console.print(f"Start: {start}")
    console.print(f"End: {end}")
    console.print(table)
    console.print(f"Average speed increase: {avg_o/avg_n}x", style="green")
Esempio n. 14
0
def print_credits():
    table = Table(show_header=True)
    table.add_column("Author", style="yellow")
    table.add_column("Contact", style="yellow")
    table.add_row("Teja Swaroop", "[email protected] ")
    console.print(table)
Esempio n. 15
0
def diff_meta(config, meta1, meta2):
    '''
    This function processes two meta data files without validating either.
    It will compare meta1 as base compared to meta2 then present the results in a table.
    The code is kind of gross but I'm not inclined to fix it.
    '''
    # Build Base Vars
    m1_num = meta1[2:].zfill(2)
    m2_num = meta2[2:].zfill(2)

    if meta1.startswith('rp'):
        m1_path = config['rp_paths'] + '/rp' + m1_num + '.meta'
    elif meta1.startswith('ss'):
        m1_path = config['ss_paths'] + '/ss' + m1_num + '.meta'

    if meta2.startswith('rp'):
        m2_path = config['rp_paths'] + '/rp' + m2_num + '.meta'
    elif meta2.startswith('ss'):
        m2_path = config['ss_paths'] + '/ss' + m2_num + '.meta'

    # Return if Missing
    if not os.path.exists(m1_path):
        return paf.prError(meta1.upper() + ' Was NOT Found!')

    if not os.path.exists(m2_path):
        return paf.prError(meta2.upper() + ' Was NOT Found!')

    # Read Meta Data
    m1 = meta.read(config, m1_path)
    m2 = meta.read(config, m2_path)
    compare = meta.compare_meta(config, m1, m2)

    # Build Info For Table
    c1 = [
        'Installed Packages: ' + m1['pkgs_installed'], 'Date: ' + m1['date'],
        'Time: ' + m1['time'], 'Pacback Version: ' + m1['version'],
        'User Label: ' + m1['label']
    ]

    if m1['stype'] == 'Full':
        c1.append('Packages Cached: ' + m1['pkgs_cached'])
        c1.append('Cache Size: ' + m1['cache_size'])

    if m1['dir_list']:
        c1.append('')
        c1.append('File Count: ' + m1['file_count'])
        c1.append('Raw File Size: ' + m1['file_raw_size'])
        c1.append('Compressed Size: ' + m1['tar_size'])
        c1.append('')
        c1.append('Directory List')
        c1.append('--------------')
        for d in m1['dir_list']:
            c1.append(d)

    c2 = list(compare['c_pkgs'])
    if not c2:
        c2.append('NONE')

    c3 = list(compare['a_pkgs'])
    if not c3:
        c3.append('NONE')

    c4 = list(compare['r_pkgs'])
    if not c4:
        c4.append('NONE')

    c5 = [
        'Installed Packages: ' + m2['pkgs_installed'], 'Date: ' + m2['date'],
        'Time: ' + m2['time'], 'Pacback Version: ' + m2['version'],
        'User Label: ' + m2['label']
    ]

    if m2['stype'] == 'Full':
        c5.append('Packages Cached: ' + m2['pkgs_cached'])
        c5.append('Cache Size: ' + m2['cache_size'])

    if m2['dir_list']:
        c5.append('')
        c5.append('File Count: ' + m2['file_count'])
        c5.append('Raw File Size: ' + m2['file_raw_size'])
        c5.append('Compressed Size: ' + m2['tar_size'])
        c5.append('')
        c5.append('Directory List')
        c5.append('--------------')
        for d in m2['dir_list']:
            c5.append(d)

    # Build Table
    t = Table(title=m1['type'] + ' #' + m1_num + ' --------> ' + m2['type'] +
              ' #' + m2_num)
    t.add_column(meta1.upper() + ' Meta Info',
                 justify='left',
                 style='bold white',
                 no_wrap=True)
    t.add_column('Changed Since Creation',
                 justify='center',
                 style='yellow',
                 no_wrap=True)
    t.add_column('Added Since Creation',
                 justify='center',
                 style='green',
                 no_wrap=True)
    t.add_column('Removed Since Creation',
                 justify='center',
                 style='red',
                 no_wrap=True)
    t.add_column(meta2.upper() + ' Meta Info',
                 justify='right',
                 style='bold white',
                 no_wrap=True)

    # This Builds The Table Output Line by Line
    counter = 0
    for x in range(0, max(len(l) for l in [c1, c2, c3, c4, c5])):
        try:
            a = str(c5[counter])
        except Exception:
            a = ''

        try:
            b = str(c2[counter])
        except Exception:
            b = ''

        try:
            c = str(c3[counter])
        except Exception:
            c = ''

        try:
            d = str(c4[counter])
        except Exception:
            d = ''

        try:
            e = str(c5[counter])
        except Exception:
            e = ''

        t.add_row(a, b, c, d, e)
        counter += 1

    console = Console()
    console.print(t)
Esempio n. 16
0
def cricpy():
    c = Cricbuzz()
    f = Figlet(font='slant')
    console = Console()

    print(f.renderText('CRICPY'))
    while 1:
        matches = c.livescore()
        print_scores(matches)
        choice = input()
        if choice == 'q':
            os.system('clear')
            exit()
        elif choice == 'r':
            continue
        else:
            while 1:
                os.system('clear')
                matches = c.livescore()
                match = matches[int(choice) - 1]
                single_score_table = Table(show_header=False,
                                           show_lines=True,
                                           expand=True)
                single_score_table.add_column()
                single_score_table.add_row(get_score_row(match))
                console.print(single_score_table)
                commentary = c.commentary(match['id'])

                if len(commentary['batsman']):
                    batsmens = commentary['batsman']
                    current_batsmen_table = Table("Batsman",
                                                  "R",
                                                  "B",
                                                  "4s",
                                                  "6s",
                                                  "SR",
                                                  expand=True)
                    for batsmen in batsmens:
                        current_batsmen_table = get_batsmen_row(
                            batsmen, current_batsmen_table)
                    console.print(current_batsmen_table)
                    current_bowler_table = Table("Bowler",
                                                 "O",
                                                 "M",
                                                 "R",
                                                 "W",
                                                 "ER",
                                                 expand=True)
                    bowler = commentary['bowler'][0]
                    current_bowler_table = get_bowler_row(
                        bowler, current_bowler_table)
                    console.print(current_bowler_table)

                commentary = commentary['comm']
                commentary_table = Table(show_header=False,
                                         padding=(1, 0, 0, 0),
                                         expand=True)
                for comment in commentary:
                    commentary_table = get_commentary_row(
                        comment, commentary_table)
                commentary_table.add_row('s:scorecard,b:back,r:refresh,q:quit')
                console.print(commentary_table)

                ch = input()
                if ch == 'r':
                    continue
                elif ch == 'b':
                    break
                elif ch == 'q':
                    os.system('clear')
                    exit()
                elif ch == 's':
                    scorecard = c.scorecard(match['id'])
                    inning = scorecard[0]
                    while 1:
                        os.system('clear')
                        batsmens = inning['batcard']

                        batsmen_table = Table("Batsman",
                                              "Dismissal",
                                              "R",
                                              "B",
                                              "4s",
                                              "6s",
                                              "SR",
                                              expand=True)
                        for batsmen in batsmens:
                            batsmen_table = get_batsmen_row(
                                batsmen, batsmen_table)
                        console.print(batsmen_table)

                        bowler_table = Table("Bowler",
                                             "O",
                                             "M",
                                             "R",
                                             "W",
                                             "ER",
                                             expand=True)
                        bowlers = inning['bowlcard']
                        for bowl in bowlers:
                            bowler_table = get_bowler_row(bowl, bowler_table)
                        console.print(bowler_table)

                        fall_wickets_table = Table("Fall of Wickets",
                                                   "Score",
                                                   "Over",
                                                   expand=True)
                        fall_wickets = inning['fall_wickets']
                        for fall_wicket in fall_wickets:
                            name = fall_wicket['name']
                            wicket = fall_wicket['wkt_num']
                            score = fall_wicket['score']
                            overs = fall_wicket['overs']
                            score = score + '-' + wicket
                            fall_wickets_table.add_row(name, score, overs)
                        console.print(fall_wickets_table)
                        print(
                            'inning number:inning scorecard,b:back,r:refresh,q:quit'
                        )

                        chh = input()
                        if chh == 'b':
                            break
                        elif chh == 'r':
                            continue
                        elif chh == 'q':
                            os.system('clear')
                            exit()
                        else:
                            try:
                                inning = scorecard[int(chh) - 1]
                            except:
                                print("wrong innings")
                            continue
Esempio n. 17
0
class CustomProgress(Progress):
    class CompletedColumn(ProgressColumn):
        def render(self, task):
            """Calculate common unit for completed and total."""
            download_status = f"{int(task.completed)}/{int(task.total)} btc"
            return Text(download_status, style="progress.download")

    class TransferSpeedColumn(ProgressColumn):
        """Renders human readable transfer speed."""

        def render(self, task):
            """Show data transfer speed."""
            speed = task.speed
            if speed is None:
                return Text("?", style="progress.data.speed")
            speed = f"{speed:,.{2}f}"
            return Text(f"{speed} btc/s", style="progress.data.speed")

    def __init__(self, *args, use_info_table: bool = True, **kwargs):
        super(CustomProgress, self).__init__(*args, **kwargs)

        self.info_table = Table(show_footer=False)
        self.info_table.add_column("Phase")

        self.test_style = "black on white"
        self.train_style = "white on black"
        self.use_info_table = use_info_table

    def add_info_table_cols(self, new_cols):
        """
        Add cols from ordered dict if not present in info_table
        """

        cols = set([x.header for x in self.info_table.columns])
        missing = set(new_cols) - cols
        if len(missing) == 0:
            return

        # iterate on new_cols since they are in order
        for c in new_cols:
            if c in missing:
                self.info_table.add_column(c)

    def update_info_table(self, aux: Dict[str, float], phase: str):
        """
        Update the info_table with the latest results
        :param aux:
        :param phase: either 'train' or 'test'
        """

        self.add_info_table_cols(aux.keys())
        epoch = aux.pop("epoch")
        aux = OrderedDict((k, f"{v:4.3f}") for k, v in aux.items())
        if phase == "train":
            st = self.train_style
        else:
            st = self.test_style
        self.info_table.add_row(phase, str(epoch), *list(aux.values()), style=st)

    def get_renderables(self) -> Iterable[RenderableType]:
        """Display progress together with info table"""

        # this method is called once before the init, so check if the attribute is present
        if hasattr(self, "use_info_table"):
            use_table = self.use_info_table
            info_table = self.info_table
        else:
            use_table = False
            info_table = Table()

        if use_table:
            task_table = self.make_tasks_table(self.tasks)
            rendable = Columns((info_table, task_table), align="left", expand=True)
        else:
            rendable = self.make_tasks_table(self.tasks)

        yield rendable
Esempio n. 18
0
def print_users(channel_info, user_id, client):
    users = channel_info['users']

    number_of_users = len(users)

    print(
        Fore.GREEN +
        "______________________________Joining Channel_______________________________\n"
    )
    # print(channel_info)
    print("Channel: -> ")
    print("ChannelID: ", channel_info['channel_id'], " ChannelName: ",
          channel_info['channel'])
    print("Topic: ", channel_info['topic'])
    print(Fore.CYAN)
    print("Club: -> ")
    print("ClubID: ", channel_info['club_id'], " ChannelInfo: ",
          channel_info['club_name'])
    print("\nNumber of Users: ", number_of_users)
    print(
        "____________________________________________________________________________"
    )
    print(Fore.RED)

    # 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("#", style="cyan", justify="right")
    table.add_column("user_id")
    table.add_column("username")
    table.add_column("name")
    table.add_column("is_speaker")
    table.add_column("is_moderator")
    table.add_column("description")

    i = 1
    for user in users:
        is_speaker = user['is_speaker']
        if not is_speaker:
            is_speaker = "-"
        is_moderator = user['is_moderator']
        if not is_moderator:
            is_moderator = "-"

        desc = "-----"
        if user['is_speaker']:
            desc = client.get_profile(user['user_id'])['user_profile']['bio']
        if i % 2 == 0:
            table.add_row(
                '[white]' + str(i),
                '[white]' + str(user['user_id']),
                '[white]' + str(user['name']),
                '[white]' + str(user['username']),
                '[white]' + str(is_speaker),
                '[white]' + str(is_moderator),
                '[white]' + str(desc),
            )
        else:
            table.add_row(
                '[orange1]' + str(i),
                '[orange1]' + str(user['user_id']),
                '[orange1]' + str(user['name']),
                '[orange1]' + str(user['username']),
                '[orange1]' + str(is_speaker),
                '[orange1]' + str(is_moderator),
                '[orange1]' + str(desc),
            )
        i += 1
        # Check if the user is the speaker
        if user['user_id'] == int(user_id):
            channel_speaker_permission = bool(user['is_speaker'])

        if i > 25:
            break
    console.print(table)
Esempio n. 19
0
    table = Table(
        title="Star Wars Movies",
        caption="Rich example table",
        caption_justify="right",
    )

    table.add_column("Released",
                     header_style="bright_cyan",
                     style="cyan",
                     no_wrap=True)
    table.add_column("Title", style="magenta")
    table.add_column("Box Office", justify="right", style="green")

    table.add_row(
        "Dec 20, 2019",
        "Star Wars: The Rise of Skywalker",
        "$952,110,690",
    )
    table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
    table.add_row(
        "Dec 15, 2017",
        "Star Wars Ep. V111: The Last Jedi",
        "$1,332,539,889",
        style="on black",
        end_section=True,
    )
    table.add_row(
        "Dec 16, 2016",
        "Rogue One: A Star Wars Story",
        "$1,332,439,889",
    )
Esempio n. 20
0
    Style(color="magenta"),
    "iso8601.timezone":
    Style(color="yellow"),
}

if __name__ == "__main__":  # pragma: no cover
    import argparse
    import io

    from rich.console import Console
    from rich.table import Table
    from rich.text import Text

    parser = argparse.ArgumentParser()
    parser.add_argument("--html",
                        action="store_true",
                        help="Export as HTML table")
    args = parser.parse_args()
    html: bool = args.html
    console = Console(record=True, width=70,
                      file=io.StringIO()) if html else Console()

    table = Table("Name", "Styling")

    for style_name, style in DEFAULT_STYLES.items():
        table.add_row(Text(style_name, style=style), str(style))

    console.print(table)
    if html:
        print(console.export_html(inline_styles=True))
Esempio n. 21
0
if len(fboTable) == 0:
    sys.exit("No fuel sources found near " + airportCode + ".")

# sort FBOs by distance from airport
fboTable.sort(key=db.sortKeyMinDist)

print("")
console.print(Markdown("### " + fuelType + " PRICES @ " + airportCode))
localFuelTable = Table(show_header=True, box=box.SIMPLE)
localFuelTable.add_column("Self")
localFuelTable.add_column("Full")
localFuelTable.add_column("FBO")
for fbo in fboTable:
    if fbo['airport'] == airportCode or fbo['dist'] == 0:
        localFuelTable.add_row(fbo['self'],fbo['full'],fbo['fbo_name'])
console.print(localFuelTable)

print("")
console.print(Markdown("### " + fuelType + " PRICES NEARBY"))
fuelTable = Table(show_header=True, box=box.SIMPLE)
fuelTable.add_column("ID")
fuelTable.add_column("Self")
fuelTable.add_column("Full")
fuelTable.add_column("Distance")
fuelTable.add_column("Direction")
fuelTable.add_column("FBO")
for fbo in fboTable:
    if fbo['airport'] != airportCode and fbo['dist'] <= maxDist:
        fuelTable.add_row(fbo['airport'],fbo['self'],fbo['full'],str(fbo['dist']) + " nm",fbo['direction'],fbo['fbo_name'])
console.print(fuelTable)
Esempio n. 22
0
        raise NameError("Inserted file not valid")

    # Set number of processes as number of pcaps
    n_process = set_n_process(pcap_app, args.process)
    table = Table(show_header=True,
                  header_style="bold magenta",
                  box=box.HORIZONTALS,
                  show_footer=True)
    table.add_column(
        "Pcap(s) to elaborate:",
        justify="center",
        footer=
        f"[bold magenta]N. worker:[/] [cornflower_blue bold]{n_process}[/], [bold magenta]PID main:[/bold magenta] [cornflower_blue bold]{os.getpid()}[/]"
    )
    for i in pcap_app:
        table.add_row(i, style="cornflower_blue bold")
    console.print(table)

    # For each .pcap in the folders, do the process
    manager = multiprocessing.Manager()
    result_list = manager.list()
    # creation of general log
    if args.general_log:
        if os.path.isdir(directory_p):
            path_general_log = os.path.join(directory_p, args.output_gl)
        else:
            path_general_log = os.path.join(os.path.dirname(directory_p),
                                            args.output_gl)
        if not os.path.isdir(path_general_log):
            os.makedirs(path_general_log)
    else:
Esempio n. 23
0
def get_report(args):
    with open("bought.csv", "r") as f, open("report.csv", "w") as file_writer:
        bought_report = csv.reader(f)
        new_csv_file = csv.writer(file_writer)

        table_bought = Table(show_header=True, header_style="bold", show_lines=False)
        table_sold = Table(show_header=True, header_style="bold", show_lines=False)
        table_revenue = Table(show_header=True, header_style="bold", show_lines=False)
        table_profit = Table(show_header=True, header_style="bold", show_lines=False)
        console = Console()

        table_bought.add_column("ID")
        table_bought.add_column("Date")
        table_bought.add_column("Product")
        table_bought.add_column("Buy Price")
        table_bought.add_column("Amount")
        table_bought.add_column("Expiration Date")

        table_sold.add_column("ID")
        table_sold.add_column("Sell Date")
        table_sold.add_column("Product")
        table_sold.add_column("Amount")
        table_sold.add_column("Sell Price")
        table_sold.add_column("Profit")

        table_revenue.add_column("Revenue")

        table_profit.add_column("Profit")

        # GET INVENTORY TODAY
        if args.subcommand == "inventory" and args.time == "today":
            for line in bought_report:
                if args.file == "true":
                    new_csv_file.writerow(line)
                elif args.pdf == "true":
                    try:
                        export_to_pdf()
                    except:
                        None
                else:
                    table_bought.add_row(
                        line[0], line[1], line[2], line[3], line[4], line[5]
                    )
            console.print(table_bought)

        # GET INVENTORY YESTERDAY
        if args.subcommand == "inventory" and args.time == "yesterday":
            for line in bought_report:
                if (datetime.strptime(line[1], "%d-%m-%Y")) < datetime.strptime(
                    dates.display_yesterday, "%d-%m-%Y"
                ):
                    if args.file == "true":
                        new_csv_file.writerow(line)
                    else:
                        table_bought.add_row(
                            line[0], line[1], line[2], line[3], line[4], line[5]
                        )
            console.print(table_bought)

        # GET INVENTORY FROM LAST WEEK
        if args.subcommand == "inventory" and args.time == "lastweek":
            display_last_week = datetime.strftime(dates.last_week, "%d-%m-%Y")

            for line in bought_report:
                if (
                    datetime.strptime(display_last_week, "%d-%m-%Y")
                    < datetime.strptime(line[1], "%d-%m-%Y")
                    < datetime.strptime(dates.display_today, "%d-%m-%Y")
                ):
                    if args.file == "true":
                        new_csv_file.writerow(line)
                    else:
                        table_bought.add_row(
                            line[0], line[1], line[2], line[3], line[4], line[5]
                        )
            console.print(table_bought)

        # GET INVENTORY ON SPECIFIC DATES
        if args.subcommand == "inventory" and args.time == "date":
            display_date = datetime.strptime(args.date, "%d-%m-%Y")

            for line in bought_report:
                if (datetime.strptime(line[1], "%d-%m-%Y")) <= display_date:
                    if args.file == "true":
                        new_csv_file.writerow(line)
                    else:
                        table_bought.add_row(
                            line[0], line[1], line[2], line[3], line[4], line[5]
                        )
            console.print(table_bought)

        # GET REPORT WITH EXPIRATION DATES
        if args.subcommand == "exdates" and args.time == "today":
            for line in bought_report:
                if (datetime.strptime(line[5], "%d-%m-%Y")) <= datetime.strptime(
                    dates.display_yesterday, "%d-%m-%Y"
                ):
                    if args.file == "true":
                        new_csv_file.writerow(line)
                    else:
                        table_bought.add_row(
                            line[0], line[1], line[2], line[3], line[4], line[5]
                        )
            console.print(table_bought)

        # GET REPORT WITH EXPIRATION DATES ON SPECIFIC DATES
        if args.subcommand == "exdates" and args.time == "date":
            display_date = datetime.strptime(args.date, "%d-%m-%Y")
            for line in bought_report:
                if (datetime.strptime(line[5], "%d-%m-%Y")) <= display_date:
                    if args.file == "true":
                        new_csv_file.writerow(line)
                    else:
                        table_bought.add_row(
                            line[0], line[1], line[2], line[3], line[4], line[5]
                        )
            console.print(table_bought)

    with open("sold.csv", "r") as sold_file:
        sold_report = csv.reader(sold_file)

        # # GET REPORT WITH SOLD PRODUCTS
        if args.subcommand == "sold":
            for line in sold_report:
                if (datetime.strptime(line[1], "%d-%m-%Y")) <= dates.display_today:

                    if args.file == "true":
                        new_csv_file.writerow(line)
                    else:
                        table_sold.add_row(
                            line[0], line[1], line[2], line[3], line[4], line[5]
                        )
                console.print(table_sold)


        # GET REPORT WITH REVENUE
        if args.subcommand == "revenue" and args.time == "today":
            sum_revenue = 0
            for line in sold_report:
                if (datetime.strptime(line[1], "%d-%m-%Y")) == dates.display_today:

                    total_revenue_per_product = float(line[3]) * float(line[4])
                    sum_revenue += total_revenue_per_product
                    if args.file == "true":
                        new_csv_file.writerow(sum_revenue)
                    else:
                        None
                else:
                    table_revenue.add_row(str(sum_revenue))
            console.print(table_revenue)

        # GET REPORT WITH REVENUE ON SPECIFIC DATES
        if args.subcommand == "revenue" and args.time == "date":
            display_date = datetime.strptime(args.date, "%d-%m-%Y")
            sum_revenue = 0
            for line in sold_report:
                if (datetime.strptime(line[1], "%d-%m-%Y")) <= display_date:
                    total_revenue_per_product = float(line[3]) * float(line[4])
                    sum_revenue += total_revenue_per_product
                    if args.file == "true":
                        new_csv_file.writerow(sum_revenue)
                    else:
                        None
                else:
                    table_revenue.add_row(str(sum_revenue))
            console.print(table_revenue)

        # GET REPORT WITH PROFIT
        if args.subcommand == "profit" and args.time == "today":
            sum_profit = 0
            for line in sold_report:
                sum_profit += float(line[5])
                if args.file == "true":
                    new_csv_file.writerow(sum_profit)
                else:
                    None
            else:
                table_profit.add_row(str(sum_profit))
            console.print(table_profit)

        # GET REPORT WITH PROFIT ON SPECIFIC DATES
        if args.subcommand == "profit" and args.time == "date":
            display_date = datetime.strptime(args.date, "%d-%m-%Y")
            sum_profit = 0
            for line in sold_report:
                if (datetime.strptime(line[1], "%d-%m-%Y")) <= display_date:
                    sum_profit += float(line[5])
                    if args.file == "true":
                        new_csv_file.writerow(sum_profit)
                    else:
                        None
                else:
                    table_profit.add_row(str(sum_profit))
            console.print(table_profit)
Esempio n. 24
0
def show_atlases(show_local_path=False):
    """Prints a formatted table with the name and version of local (downloaded)
    and online (available) atlases. To do so, dowload info on
    the latest atlas version and compares it with what it's stored
    locally.

    Arguments
    ---------
    show_local_path : bool
        If true, local path of the atlases are in the table with the rest
        (optional, default=False).

    """

    available_atlases = get_all_atlases_lastversions()

    # Get local atlases:
    atlases = get_atlases_lastversions()

    # Get atlases not yet downloaded:
    for atlas in available_atlases.keys():

        if atlas not in atlases.keys():
            atlases[str(atlas)] = dict(
                downloaded=False,
                local="",
                version="",
                latest_version=str(available_atlases[atlas]),
                updated=None,
            )

    # Print table:
    table = Table(
        show_header=True,
        header_style="bold green",
        show_lines=True,
        expand=False,
        box=None,
    )

    table.add_column("Name", no_wrap=True, width=32)
    table.add_column("Downloaded", justify="center")
    table.add_column("Updated", justify="center")
    table.add_column("Local version", justify="center")
    table.add_column("Latest version", justify="center")
    if show_local_path:
        table.add_column("Local path")

    for n, (atlas, info) in enumerate(atlases.items()):
        if info["downloaded"]:
            downloaded = "[green]:heavy_check_mark:[/green]"

            if info["version"] == info["latest_version"]:
                updated = "[green]:heavy_check_mark:[/green]"
            else:
                updated = "[red dim]x"

        else:
            downloaded = ""
            updated = ""

        row = [
            "[bold]" + atlas,
            downloaded,
            updated,
            "[#c4c4c4]" +
            info["version"] if "-" not in info["version"] else "",
            "[#c4c4c4]" + info["latest_version"],
        ]

        if show_local_path:
            row.append(info["local"])

        table.add_row(*row)
    rprint(Panel.fit(
        table,
        width=88,
        title="Brainglobe Atlases",
    ))
Esempio n. 25
0
def make_cases_table(recs: List[CaseRecord]) -> Table:
    """
    This function creates the Rich.Table that contains the cases information.

    Parameters
    ----------
    recs: List[CaseRecord]
        The list of case records in model-object form.

    Returns
    -------
    The rendered Table of case information.
    """
    n_cases = len(recs)
    table = Table(
        title=Text(
            f"Cases ({n_cases})" if n_cases > 1 else "Case",
            style="bright_white",
            justify="left",
        ),
        show_header=True,
        header_style="bold magenta",
        show_lines=True,
    )

    table.add_column("Case #")
    table.add_column("Urgency")
    table.add_column("Status")
    table.add_column("Impact")
    table.add_column("Date(s)")
    table.add_column("Location", width=12, overflow="fold")
    table.add_column("Start Time")
    table.add_column("End Time")
    table.add_column("Reason")

    pdates = attrgetter("primary_date", "primary_date_2", "primary_date_3")

    for row_obj in recs:

        if row_obj.status != consts.CaseStatusOptions.closed:
            row_obj.urgency = colorize_urgency(row_obj.urgency)  # noqa
            row_obj.impact = colorize_impact(row_obj.impact)
            row_obj.status = colorize_status(row_obj.status)

        rec_pdates = sorted(pd for pd in pdates(row_obj) if pd)
        md = maya.parse(rec_pdates[0])
        dstr = "\n".join(map(str, rec_pdates)) + f"\n({md.slang_time()})"

        table.add_row(
            row_obj.case_num,
            row_obj.urgency,
            row_obj.status,
            row_obj.impact,
            dstr,
            row_obj.location,
            str(row_obj.from_time),
            str(row_obj.to_time),
            row_obj.reason,
        )

    return table
Esempio n. 26
0
def store():
    """Function for creating the store UI"""
    # Determines price of each type of item
    p = vars.amount_spent_on_miscellaneous
    b = vars.amount_spent_on_bullets
    c = vars.amount_spent_on_clothing
    f = vars.amount_spent_on_food
    o = vars.amount_spent_on_animals
    # Creates store UI using table library
    table = Table(show_header=True, header_style="bold magenta")
    table.add_column("Goods")
    table.add_column("Spent", justify="right")
    # Creates "oxen" portion of the table
    table.add_row("1. Oxen", f"[green]${o}[/green]")
    # Creates "food" portion of the table
    table.add_row(
        "2. Food",
        f"[green]${f}[/green]",
    )
    # Creates "clothing" portion of the table
    table.add_row(
        "3. Clothing",
        f"[green]${c}[/green]",
    )
    # Creates "ammunition" portion of the table
    table.add_row(
        "4. Ammunition",
        f"[green]${b}[/green]",
    )
    # Creates "parts" portion of the table
    table.add_row(
        "5. Misc. (Medicine, Wagon parts etc.)",
        f"[green]${p}[/green]",
    )
    # Creates the total spent portion of the table
    table.add_row("\nTotal", f"\n[green]${o+f+c+b+p}[/green]")
    console.print(table)

    while True:
        # Displays and handles store options and which option the player 
        # selects
        try:
            print(
                "Which item would you like to buy?\n\n[cyan italic]\
Type 'leave' to exit the store[/cyan italic]"
            )
            selection = input("\n-->")
            if selection == "1":
                console.clear()
                oxen()
            elif selection == "2":
                console.clear()
                food()
                break
            elif selection == "3":
                console.clear()
                clothes()
                break
            elif selection == "4":
                console.clear()
                bullets()
                break
            elif selection == "5":
                console.clear()
                parts()
                break
            elif selection == "exit":
                console.clear()
                exit()
            elif selection == "leave":
                # Determines if the player has enough oxen to play the game
                if vars.amount_spent_on_animals < 1:
                    print(
                        "[cyan italic] Don't forget,\
 you'll need oxen to pull your wagon![/cyan italic]"
                    )
                    input("Press Enter to Continue...")
                    console.clear()
                    store()
                elif vars.amount_spent_on_animals > 1:
                    console.clear()
                    print(
                        "[cyan italic]Well then, you are ready to start.\
 Good luck! You have a long and difficult\
 journey ahead of you...[/cyan italic]"
                    )
                input("Press Enter to Continue...")
                console.clear()
                walking_trail()
                break
        except ValueError:
            print("\n[red]Invalid Selection[/red]\n")
            input("\nPress Enter to Continue")
            continue
Esempio n. 27
0
"""
Demonstrates how to render a table.
"""

from rich.console import Console
from rich.table import Table

table = Table(title="Star Wars Movies")

table.add_column("Released", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
table.add_column("Box Office", justify="right", style="green")

table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker",
              "$952,110,690")
table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi",
              "$1,332,539,889")
table.add_row("Dec 16, 2016", "Rouge One: A Star Wars Story", "$1,332,439,889")

console = Console()
console.print(table, justify="center")
Esempio n. 28
0
def print_info(config, selction):
    '''
    This function processes a meta data file without validating it,
    then compares the file to now and presents the results in a table.
    This acts as a 'dry run' of sorts not only showing info in the meta data
    file but also showing what would be changed if actually restored.
    The code is kind of gross but I'm not inclined to fix it.
    '''
    # Build Base Vars
    m_num = selction[2:].zfill(2)

    if selction.startswith('rp'):
        m_path = config['rp_paths'] + '/rp' + m_num + '.meta'
    elif selction.startswith('ss'):
        m_path = config['ss_paths'] + '/ss' + m_num + '.meta'

    # Return if Missing
    if not os.path.exists(m_path):
        return paf.prError(selction.upper() + ' Was NOT Found!')

    # Load Meta and Compare
    m = meta.read(config, m_path)
    compare = meta.compare_now(config, m)

    # Build Data For Table
    c1 = [
        'Installed Packages: ' + m['pkgs_installed'], 'Date: ' + m['date'],
        'Time: ' + m['time'], 'Pacback Version: ' + m['version'],
        'User Label: ' + m['label']
    ]

    if m['stype'] == 'Full':
        c1.append('Packages Cached: ' + m['pkgs_cached'])
        c1.append('Cache Size: ' + m['cache_size'])

    if m['dir_list']:
        c1.append('')
        c1.append('File Count: ' + m['file_count'])
        c1.append('Raw File Size: ' + m['file_raw_size'])
        c1.append('Compressed Size: ' + m['tar_size'])
        c1.append('')
        c1.append('Directory List')
        c1.append('--------------')
        for d in m['dir_list']:
            c1.append(d)

    c2 = list(compare['c_pkgs'])
    if not c2:
        c2.append('NONE')

    c3 = list(compare['a_pkgs'])
    if not c3:
        c3.append('NONE')

    c4 = list(compare['r_pkgs'])
    if not c4:
        c4.append('NONE')

    # Build Table
    t = Table(title=m['type'] + ' #' + m_num)
    t.add_column('Meta Info', justify='left', style='bold white', no_wrap=True)
    t.add_column('Changed Since Creation',
                 justify='center',
                 style='yellow',
                 no_wrap=True)
    t.add_column('Added Since Creation',
                 justify='center',
                 style='green',
                 no_wrap=True)
    t.add_column('Removed Since Creation',
                 justify='center',
                 style='red',
                 no_wrap=True)

    # This Builds The Table Output Line by Line
    counter = 0
    for x in range(0, max(len(l) for l in [c1, c2, c3, c4])):
        try:
            a = str(c1[counter])
        except Exception:
            a = ''

        try:
            b = str(c2[counter])
        except Exception:
            b = ''

        try:
            c = str(c3[counter])
        except Exception:
            c = ''

        try:
            d = str(c4[counter])
        except Exception:
            d = ''

        t.add_row(a, b, c, d)
        counter += 1

    console = Console()
    console.print(t)
Esempio n. 29
0
def make_test_card() -> Table:
    """Get a renderable that demonstrates a number of features."""
    table = Table.grid(padding=1, pad_edge=True)
    table.title = "Rich features"
    table.add_column("Feature",
                     no_wrap=True,
                     justify="center",
                     style="bold red")
    table.add_column("Demonstration")

    color_table = Table(
        box=None,
        expand=False,
        show_header=False,
        show_edge=False,
        pad_edge=False,
    )
    color_table.add_row(
        # "[bold yellow]256[/] colors or [bold green]16.7 million[/] colors [blue](if supported by your terminal)[/].",
        ("✓ [bold green]4-bit color[/]\n"
         "✓ [bold blue]8-bit color[/]\n"
         "✓ [bold magenta]Truecolor (16.7 million)[/]\n"
         "✓ [bold yellow]Dumb terminals[/]\n"
         "✓ [bold cyan]Automatic color conversion"),
        ColorBox(),
    )

    table.add_row("Colors", color_table)

    table.add_row(
        "Styles",
        "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].",
    )

    lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus."
    lorem_table = Table.grid(padding=1, collapse_padding=True)
    lorem_table.pad_edge = False
    lorem_table.add_row(
        Text(lorem, justify="left", style="green"),
        Text(lorem, justify="center", style="yellow"),
        Text(lorem, justify="right", style="blue"),
        Text(lorem, justify="full", style="red"),
    )
    table.add_row(
        "Text",
        RenderGroup(
            Text.from_markup(
                """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n"""
            ),
            lorem_table,
        ),
    )

    def comparison(renderable1, renderable2) -> Table:
        table = Table(show_header=False, pad_edge=False, box=None, expand=True)
        table.add_column("1", ratio=1)
        table.add_column("2", ratio=1)
        table.add_row(renderable1, renderable2)
        return table

    table.add_row(
        "Asian\nlanguage\nsupport",
        ":flag_for_china:  该库支持中文,日文和韩文文本!\n:flag_for_japan:  ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea:  이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다",
    )

    markup_example = (
        "[bold magenta]Rich[/] supports a simple [i]bbcode[/i] like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! "
        ":+1: :apple: :ant: :bear: :baguette_bread: :bus: ")
    table.add_row("Markup", markup_example)

    example_table = Table(
        show_edge=False,
        show_header=True,
        expand=False,
        row_styles=["none", "dim"],
        box=box.SIMPLE,
    )
    example_table.add_column("[green]Date", style="green", no_wrap=True)
    example_table.add_column("[blue]Title", style="blue")
    example_table.add_column(
        "[cyan]Production Budget",
        style="cyan",
        justify="right",
        no_wrap=True,
    )
    example_table.add_column(
        "[magenta]Box Office",
        style="magenta",
        justify="right",
        no_wrap=True,
    )
    example_table.add_row(
        "Dec 20, 2019",
        "Star Wars: The Rise of Skywalker",
        "$275,000,000",
        "$375,126,118",
    )
    example_table.add_row(
        "May 25, 2018",
        "[b]Solo[/]: A Star Wars Story",
        "$275,000,000",
        "$393,151,347",
    )
    example_table.add_row(
        "Dec 15, 2017",
        "Star Wars Ep. VIII: The Last Jedi",
        "$262,000,000",
        "[bold]$1,332,539,889[/bold]",
    )
    example_table.add_row(
        "May 19, 1999",
        "Star Wars Ep. [b]I[/b]: [i]The phantom Menace",
        "$115,000,000",
        "$1,027,044,677",
    )

    table.add_row("Tables", example_table)

    code = '''\
def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
    """Iterate and generate a tuple with a flag for last value."""
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    for value in iter_values:
        yield False, previous_value
        previous_value = value
    yield True, previous_value'''

    pretty_data = {
        "foo": [
            3.1427,
            (
                "Paul Atriedies",
                "Vladimir Harkonnen",
                "Thufir Haway",
            ),
        ],
        "atomic": (False, True, None),
    }
    table.add_row(
        "Syntax\nhighlighting\n&\npretty\nprinting",
        comparison(
            Syntax(code, "python3", line_numbers=True, indent_guides=True),
            Pretty(pretty_data, indent_guides=True),
        ),
    )

    markdown_example = """\
# Markdown

Supports much of the *markdown*, __syntax__!

- Headers
- Basic formatting: **bold**, *italic*, `code`
- Block quotes
- Lists, and more...
    """
    table.add_row(
        "Markdown",
        comparison("[cyan]" + markdown_example, Markdown(markdown_example)))

    table.add_row(
        "+more!",
        """Progress bars, columns, styled logging handler, tracebacks, etc...""",
    )
    return table
Esempio n. 30
0
async def brick_session(uuid, timeout=15):
    b = PFxBrickBLE(uuid=uuid)
    await b.open(timeout=timeout)
    icd = await b.get_icd_rev()
    await b.get_status()

    if b.status == 0x00:
        name = await b.get_name()
    else:
        name = "Service Mode"
    table = Table(show_header=True, header_style="bold blue")
    bid = "[light_slate_blue]%s [bold cyan]%s" % (b.product_id, b.product_desc)
    table.add_column(bid, width=72)
    table.add_row("Bluetooth UUID        : [bold orange3]%s" % (uuid))
    table.add_row("Serial Number         : [bold cyan]%s" % (b.serial_no))
    table.add_row("ICD Version           : [bold green]%s" % (icd))
    table.add_row(
        "Firmware Version      : [bold green]%s [reset]build [bold green]%s" %
        (b.firmware_ver, b.firmware_build))
    table.add_row("Status                : 0x%02X %s" %
                  (b.status, get_status_str(b.status)))
    if b.error:
        table.add_row("Errors                : [red]0x%02X %s" %
                      (b.error, get_error_str(b.error)))
    else:
        table.add_row("Errors                : [green]0x%02X %s" %
                      (b.error, get_error_str(b.error)))
    table.add_row("Name                  : [bold yellow]%s" % (name))
    r = await b.get_rssi()
    table.add_row("RSSI                  : %s dBm" % (r))
    console.print(table)
    await b.close()