def test_rule_error(): console = Console(width=16, file=io.StringIO(), legacy_windows=False, _environ={}) with pytest.raises(ValueError): console.rule("foo", align="foo")
def ReplInit(): # # Install the pretty printer that rich provides to replace the existing # printer. # pretty.install(indent_guides=True, expand_all=True) console = Console() console.rule('Matter REPL') console.print(''' [bold blue] Welcome to the Matter Python REPL! For help, please type [/][bold green]matterhelp()[/][bold blue] To get more information on a particular object/class, you can pass that into [bold green]matterhelp()[/][bold blue] as well. ''') console.rule() coloredlogs.install(level='DEBUG') chip.logging.RedirectToPythonLogging() # logging.getLogger().setLevel(logging.DEBUG) logging.getLogger().setLevel(logging.WARN)
def agreement(self, title, address, password): console = Console() console.rule("[bold red]IMPORTANT NOTICE", style = "red") console.print(" [bold blue]General Information") console.print("") console.print(" • Following this experiment, an email with subject title '%s' will be sent to '%s'" % (title, address)) console.print(" • In order to protect your privacy, [underline]at no point during this experiment will your password be recorded, nor will it be printed to the console.") console.print(" • The results logged will be sent via a secure connection over port 587") console.print(" • Results will be saved to 'experiments/%s/results.json'" % title) console.print(" ") console.print(" [bold blue]You must enable less secure app access") console.print(" ") console.print(" • Enable less secure app access [link]https://myaccount.google.com/lesssecureapps") console.print(" ") console.print(" [bold blue]If you have 2-step verification enabled, you must either disable it or create an app-specific password for less secure apps") console.print(" ") console.print(" • Create an app password [link]https://support.google.com/mail/answer/185833") console.print(" • Disable 2-step verification [link]https://myaccount.google.com/signinoptions/two-step-verification") console.print(" ") console.print(" Read the above notice. Then, press any key to proceed[blink]...") console.rule(style = "red") input(' ') if password is None: return getpass(" Enter email password to continue: ") else: return password
def run(): console = Console() console.rule("Cartographer") auth_session = kroger.authorize(console) with console.status("Setting up...") as status: status.update("Loading spreadsheet...") items = sheets.get_items(console) status.update("Loading model...") tokenizer, model = heuristics.load_tokenizer_and_model() console.log("Loaded model.") status.update("Picking groceries...") selected_items = {} for i, (item, count, description) in enumerate(items): status.update(f"Picking groceries [green]({i}/{len(items)})...") search_results = kroger.product_search(item, auth_session) selected = heuristics.select_item( item, search_results.json()["data"], description, tokenizer, model, console, ) selected_items[selected["upc"]] = count status.update("Adding to cart...") kroger.add_to_cart(selected_items, auth_session) console.log("Done!")
def summary(display_error): console = Console() console.rule() dirs = DIRS run_result: dict[str, Result] = {} with console.status("Running mypy against all koan files ...", spinner="moon"): for directory in dirs: for py_file in sorted(Path(directory).rglob("*.py")): name = str(py_file) res = run_mypy(name) if res.exit_code == 0: emoji_text = ":thumbsup:" else: emoji_text = ":thumbsdown:" console.print( f"[bold] Ran mypy in koan file: {name} {emoji_text}") run_result[name] = res display_summary(console, run_result) if display_error: for file_name, result in run_result.items(): display_result(console, file_name, result, display="error") console.rule()
def run_one(path): console = Console() console.rule("") console.print(f"Running mypy on koan file {path}") res = run_mypy(path) display_result(console, path, res, display="all") console.rule()
def list(): console = Console() console.rule() for directory in DIRS: for py_file in sorted(Path(directory).rglob("*.py")): console.print(py_file) console.rule()
def test_rule_cjk(): console = Console(width=16, file=io.StringIO(), force_terminal=True, color_system=None) console.rule("欢迎!") expected = "──── 欢迎! ────\n" assert console.file.getvalue() == expected
class VersionManager: def __init__(self): self.console = Console() self.location = Location() self.utils = Utils() self.home = str(Path.home()) self.version_manager_loc = "sh $HOME/.config/zsh-config/groups/Version-Manager/" def pyenv(self): self.console.print() self.console.print("Installing [bold red]pyenv[/]...") os.system(self.version_manager_loc + "pyenv.sh") def rbenv(self): self.console.print() self.console.print("Installing [bold red]rbenv[/]...") os.system(self.version_manager_loc + "rbenv.sh") def sdkman(self): self.console.print() self.console.print("Installing [bold red]SDK Man[/]...") os.system(self.version_manager_loc + "sdkman.sh") def gvm(self): self.console.print() self.console.print("Installing [bold red]gvm[/]...") os.system(self.version_manager_loc + "gvm.sh") def run(self): tasks = { 0: "All", 1: "pyenv", 2: "rbenv", 3: "sdkman", 4: "gvm", } self.console.rule("Install package from?") self.utils.tasks_print(tasks) choice = self.console.input("What is your [bold red]choice[/]? :smiley: ") self.console.print(f'You entered {choice}') choice = int(choice) if choice == 0: self.pyenv() self.rbenv() self.sdkman() elif choice == 1: self.pyenv() elif choice == 2: self.rbenv() elif choice == 3: self.sdkman() elif choice == 4: self.gvm()
def make_spinner(): """Make Spinner component with a mocked response table.""" console = Console() response = make_table() with console.status('Getting data...'): work() console.rule("[bold red]API Response") console.print(response)
def test_rule_align(): console = Console(width=16, file=io.StringIO(), legacy_windows=False) console.rule("foo") console.rule("foo", align="left") console.rule("foo", align="center") console.rule("foo", align="right") console.rule() result = console.file.getvalue() print(repr(result)) expected = "───── foo ──────\nfoo ────────────\n───── foo ──────\n──────────── foo\n────────────────\n" assert result == expected
def test_rule_cjk(): console = Console( width=16, file=io.StringIO(), force_terminal=True, color_system=None, legacy_windows=False, _environ={}, ) console.rule("欢迎!") expected = "──── 欢迎! ────\n" assert console.file.getvalue() == expected
def test_rule(): console = Console( width=16, file=io.StringIO(), force_terminal=True, legacy_windows=False ) console.print(Rule()) console.print(Rule("foo")) console.rule(Text("foo", style="bold")) console.rule("foobarbazeggfoobarbazegg") expected = "\x1b[92m────────────────\x1b[0m\n" expected += "\x1b[92m───── \x1b[0mfoo\x1b[92m ──────\x1b[0m\n" expected += "\x1b[92m───── \x1b[0m\x1b[1mfoo\x1b[0m\x1b[92m ──────\x1b[0m\n" expected += "\x1b[92m─ \x1b[0mfoobarbazeg…\x1b[92m ─\x1b[0m\n" result = console.file.getvalue() assert result == expected
def test_characters(): console = Console( width=16, file=io.StringIO(), force_terminal=True, color_system=None, legacy_windows=False, ) console.rule(characters="+*") console.rule("foo", characters="+*") console.print(Rule(characters=".,")) expected = "+*+*+*+*+*+*+*+*\n" expected += "+*+*+ foo +*+*+*\n" expected += ".,.,.,.,.,.,.,.,\n" assert console.file.getvalue() == expected
def test_rule(): console = Console(width=16, file=io.StringIO(), force_terminal=True) console.rule() console.rule("foo") console.rule(Text("foo", style="bold")) console.rule("foobarbazeggfoobarbazegg") expected = "\x1b[38;5;10m────────────────\x1b[0m\n\x1b[38;5;10m───── \x1b[0mfoo\x1b[38;5;10m ──────\x1b[0m\n\x1b[38;5;10m───── \x1b[0m\x1b[1mfoo\x1b[0m\x1b[38;5;10m ──────\x1b[0m\n\x1b[38;5;10m─ \x1b[0mfoobarbazegg\x1b[38;5;10m ─\x1b[0m\n" assert console.file.getvalue() == expected
def display_result(console: Console, file_name: str, result: Result, display="all"): if display in ("all", "error") and result.exit_code != 0: console.rule(f"[bold] mypy errors in koan file {file_name}") if result.result: console.print(result.result) if result.error: console.print(result.error) console.rule("End") if display in ("all", ) and result.exit_code == 0: console.print(f"No errors in koan file {file_name} :thumbsup: ")
def print_calendar(year): """Print a calendar for a given year.""" today = datetime.today() year = int(year) cal = calendar.Calendar() today_tuple = today.day, today.month, today.year tables = [] for month in range(1, 13): table = Table( title=f"{calendar.month_name[month]} {year}", style="green", box=box.SIMPLE_HEAVY, padding=0, ) for week_day in cal.iterweekdays(): table.add_column("{:.3}".format(calendar.day_name[week_day]), justify="right") month_days = cal.monthdayscalendar(year, month) for weekdays in month_days: days = [] for index, day in enumerate(weekdays): day_label = Text(str(day or ""), style="magenta") if index in (5, 6): day_label.stylize("blue") if day and (day, month, year) == today_tuple: day_label.stylize("white on dark_red") days.append(day_label) table.add_row(*days) tables.append(Align.center(table)) console = Console() columns = Columns(tables, padding=1, expand=True) console.rule(str(year)) console.print() console.print(columns) console.rule(str(year))
class Patch: def __init__(self): self.console = Console() self.location = Location() self.utils = Utils() self.prefix_cmd = "sh $HOME/" + self.location.PATCH_LOCATION def youcompleteme(self): self.console.print() self.console.print("Patching [bold red]YouCompleteMe[/]...") cmd = self.prefix_cmd + "YouCompleteMe.sh" os.system(cmd) def nerdfont(self): self.console.print() self.console.print("Patching [bold red]Nerd Font[/]...") cmd = self.prefix_cmd + "nerd-font.sh" os.system(cmd) def run(self): tasks = { 0: "All", 1: "YouCompleteMe", 2: "Nerd Font" } self.console.rule("Patch package from?") self.utils.tasks_print(tasks) choice = self.console.input("What is your [bold red]choice[/]? :smiley: ") self.console.print(f'You entered {choice}') choice = int(choice) if choice == 0: self.youcompleteme() self.nerdfont() elif choice == 1: self.youcompleteme() elif choice == 2: self.nerdfont()
def make_progress_display(n: int): """ Create Progress Display component. Parameters ---------- n : int Number of interactions. """ console = Console() beers = [] for _ in range(n): beers.append(beer_specification()) for n in track(range(n), description="Creating products..."): sleep(n + 3) console.rule("[bold red]Products Created") table = make_beer_table(beers) console.print(table)
def handle(self): # self.request is the TCP socket connected to the client print("{}".format(self.client_address[0])) self.wfile.write("\r\nWelcome to Vincent's telnet service!\r\n---\r\n".encode(encoding="ascii")) self.wfile.write("Choose terminal mode:\r\n".encode(encoding="ascii")) self.wfile.write("0 => UTF-8\r\n".encode(encoding="ascii")) self.wfile.write("1 => ASCII\r\n".encode(encoding="ascii")) resp = self.request.recv(1024).strip() encoding = "utf8" box_type = box.ROUNDED if(resp != '' and int(resp) == 1): encoding = "ascii" box_type = box.ASCII self.wfile.write("Enabled ASCII mode\r\n\r\n".encode(encoding="ascii")) else: self.wfile.write("Enabled UTF-8 mode\r\n\r\n".encode(encoding="ascii")) # TextIOWrapper converts 'string' to 'byte' (aka encode) wfilet = io.TextIOWrapper(self.wfile, encoding=encoding, newline="\r\n") # Rich console init using socketserver wrapped self.wfile console = Console(file=wfilet, force_terminal=True, color_system="256", no_color=False, width=80) # Rich terminal display code starts here ### console.rule("[bold red]This is a demo") table = Table(show_header=False, expand=True, box=box_type) table.add_column("", justify="center") table.add_column("", justify="center") table.add_column("", justify="center") table.add_row("[i green]This a table", "with [white on blue]nice text inside", "Even link works [u blue]http://ibm.com", ) console.print(table) console.print("\n[b green]Have a nice day~\n") #console.print("Enter to leave...\n") self.data = self.request.recv(1024).strip()
def validate(console: Console, args: argparse.Namespace) -> int: """Check if all files are valid""" retcode = 0 for file in args.files: try: if not args.quiet: console.rule(f"[blue]Validating file {file}") cset = model_auto(open_auto(file)) if args.version and cset.schema_version != args.version: raise ValueError( f"Schema version {cset.schema_version} does not match the required version {args.version}" ) except Exception as ex: if not args.quiet: console.print(str(ex)) retcode = 1 if args.failfast: break else: if not args.quiet: console.print("[green]All OK :heavy_check_mark:") return retcode
def list_countries(): """Country list menu.""" console = Console() console.print(MARKDOWN) mapper = { 1: "Brazil", 2: "Germany", 3: "Belgium", 4: "United Kingdom", 5: "Netherlands", } option = IntPrompt.ask("Enter your choice", choices=["1", "2", "3", "4", "5"], show_choices=False) with console.status(f"Getting {mapper[option]} brands..."): sleep(2) console.rule(f"{mapper[option]} Brands") options(option)
def _print_failed_jobs(client: Client, jobs): """Prints failed jobs and associated tasks for a failed package.""" if not jobs: return console = Console() console.rule("Failed jobs") item: transfer_service_api.request_response_pb2.Job for item in jobs: if item.status != item.STATUS_FAILED: continue table = Table(expand=True, show_header=True, header_style="bold magenta") table.add_column("Job") table.add_column("Identifier") table.add_column("Link") table.add_row( f"[bold]{item.name}[/]\n[dim](part of {item.group})[/]", item.id, item.link_id, ) console.print(table) try: resp = client.list_tasks(item.id) except Exception: console.print("Tasks could not be loaded.") continue task: transfer_service_api.request_response_pb2.Task for task in resp.tasks: content = f"""[bold]Task {task.id}[/] Module [bold]{task.execution}[/] (with arguments: [dim]{task.arguments}[/]) --- stdout {task.stdout} --- stderr [red]{task.stderr}[/] """ console.print(Panel(content))
def render(): console = Console(file=io.StringIO(), width=100, legacy_windows=False) panel = Panel.fit("foo", box=box.SQUARE) columns = Columns([panel] * 4) columns.expand = True console.rule("no align") console.print(columns) columns.align = "left" console.rule("left align") console.print(columns) columns.align = "center" console.rule("center align") console.print(columns) columns.align = "right" console.rule("right align") console.print(columns) return console.file.getvalue()
start_index = 0 tasks = embedding_order if args.run_preselection: if "preselection.py" in os.listdir(emb_folder): tasks = ["preselection.py"] start_index = 0 else: console.print("preselection.py not found in embedding folder") raise FileNotFoundError else: if not args.run_all: starttask = enquiries.choose("Pick tasks to start with", embedding_order) start_index = embedding_order.index(starttask) tasks = embedding_order[start_index:] console.rule("Starting to run embedding") console.log("Running {}".format(tasks)) if not os.path.exists(workdir): os.makedirs(workdir) for i, filename in enumerate(tasks): # we have to change the number of events directly in the script, # and therefore parse the selection config, replacing the events line modified_input = False if i == 0: with open(os.path.join(emb_folder, filename), "r") as f: lines = f.readlines() with open(os.path.join(workdir, filename), "w") as f: for line in lines: if ("fileNames = cms.untracked.vstring(" in line and modified_input is False): f.write(
my_controller = controller.LinearController( motor=controller.stepper.StepperMotor( total_steps=200, dir_pin=20, step_pin=13, en_pin=23, mode_pins=(14, 15, 18), mode=controller.stepper.ONE_THIRTYTWO, gear_ratio=5.18), screw_pitch=5, up_endstop_pin=25, down_endstop_pin=8) my_loadcell = loadcell.LoadCell(dat_pin=5, clk_pin=6) console.rule('[bold red]UNIVERSAL TESTING MACHINE') result = 0 while result is not None: result = inquirer.select(message='Select a menu voice:', choices=[{ 'name': 'Load Cell Calibration', 'value': 'loadcell_calibration' }, { 'name': 'Manual Control', 'value': 'manual' }, { 'name': 'Monotonic Test', 'value': 'monotonic' }, {
def Downloading(): #trivial function for printing print("downloading...") def bye(): console.print(Panel.fit(''' [bold red]Thank YOU [/bold red][bold]for using youtube downloader If you enjoy it, feel free to leave a [/bold][bold red]Star[/bold red] [italic bold yellow]https://github.com/ahmedasad236/YouTube-Downloader[/italic bold yellow] [italic cyan]Feedback and contribution is welcome as well :smiley:![/italic cyan] ''', title="Bye!"), justify="center") def handler(signal_received, frame): # Handle any cleanup here print('\n[bold]SIGINT or CTRL-C detected. [red]Exiting gracefully[/red][/bold]') bye() sys.exit(0) console.rule("Welcome to Youtube Downloader") questions = [ { 'type': 'input', 'name': 'username', 'message': 'Enter YouTube Video Url:', } ] questions_2 = [ { 'type': 'list', 'name': 'size', 'message': 'What do you want?', 'choices': ["Go to Downloader", "Exit"] } ]
if __name__ == "__main__": # pragma: no cover from rich.console import Console from rich.syntax import Syntax from rich.text import Text code = """from rich.console import Console console = Console() text = Text.from_markup("Hello, [bold magenta]World[/]!") console.print(text)""" text = Text.from_markup("Hello, [bold magenta]World[/]!") console = Console() console.rule("rich.Segment") console.print( "A Segment is the last step in the Rich render process before generating text with ANSI codes." ) console.print("\nConsider the following code:\n") console.print(Syntax(code, "python", line_numbers=True)) console.print() console.print( "When you call [b]print()[/b], Rich [i]renders[/i] the object in to the the following:\n" ) fragments = list(console.render(text)) console.print(fragments) console.print() console.print( "The Segments are then processed to produce the following output:\n" )
new_text = text.blank_copy("\n").join(new_lines) return new_text if __name__ == "__main__": # pragma: no cover from rich.console import Console text = Text( """\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n""" ) text.highlight_words(["Lorem"], "bold") text.highlight_words(["ipsum"], "italic") console = Console() console.rule("justify='left'") console.print(text, style="red") console.print() console.rule("justify='center'") console.print(text, style="green", justify="center") console.print() console.rule("justify='right'") console.print(text, style="blue", justify="right") console.print() console.rule("justify='full'") console.print(text, style="magenta", justify="full") console.print()
action='store_true', default=False) parser.add_argument('-a', '--all', help='download all files', action='store_true', default=False) parser.add_argument('-f', '--filter', help='display only new files', action='store_true', default=False) parser.add_argument('-n', '--new', help='display announcement of the course', action='store_true', default=False) args = parser.parse_args() # Disable warnings because SSL urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) username, password = get_cardinalities() if authenticate_user(username, password): console.rule("[+] Authorized", style='bold green') else: console.rule( "[!] you are not authorized. review your credentials", style='bold red') os.remove(".env") sys.exit(1) session = requests.Session() home_page = session.get(HOST, verify=False, auth=HttpNtlmAuth(username, password)) home_page_soup = bs(home_page.text, 'html.parser') course_links = get_avaliable_courses(home_page_soup) courses_name = get_course_names(home_page_soup) make_courses_dir(courses_name)