def format_code(self, index, cell, config): """Format the code block. Print both the source and output.""" panels = [] panels.append(self.format_index(index, source_type="input")) code = Syntax(self.get_source_text(cell), lexer_name="python") if config.no_cell_border: panels.append("\n") panels.append(code) panels.append("\n") else: panels.append(Panel(code)) if not config.exclude_output_cells: for output in cell.get("outputs"): panels.append(self.format_index(index, source_type="output")) output_text, lexer_name = self.get_output_text(output) if can_render_in_terminal(lexer_name): code = Syntax(output_text, lexer_name=lexer_name) if config.no_cell_border: panels.append("\n") panels.append(code) panels.append("\n") else: panels.append(Panel(code)) else: panels.append( Panel( f"[bold red] Not rendering {lexer_name} [/bold red]" )) return panels
def __rich_console__(self, *args, **kwargs): parts = [] parts.append(r':arrow_up:') parts.append(self.resource.__rich__()) parts.append(r'[grey53]\[{h}][/]'.format(h=self.revision.id)) if self.property_version: parts.append(r'[grey53]v{version}[/]'.format(version=self.property_version.propertyVersion)) if self.revision.short_message: parts.append(r'[bright_white]"{subject_line}"[/]'.format(subject_line=self.revision.short_message)) author = self.revision.author_name if author: parts.append("[grey53]{}[/]".format(author)) if (self.rule_tree and self.rule_tree.has_errors) or (self.hostnames and self.hostnames.has_errors): parts.append(":boom:") yield " ".join(parts) if self.error is not None: from rich.panel import Panel from rich.syntax import Syntax import yaml error_yaml = yaml.safe_dump(self.error.args[0]) yield '{}\n{}'.format(type(self.error).__name__, Syntax(error_yaml, "yaml").highlight(error_yaml)) if self.hostnames and self.hostnames.has_errors: from rich.panel import Panel from rich.syntax import Syntax import yaml yield Panel(Syntax(yaml.safe_dump(self.hostnames.errors), "yaml"), title="Validation Errors") if self.rule_tree and self.rule_tree.has_errors: from rich.panel import Panel from rich.syntax import Syntax import yaml yield Panel(Syntax(yaml.safe_dump(self.rule_tree.errors), "yaml"), title="Validation Errors")
def test_syntax_guess_lexer(): assert Syntax.guess_lexer("banana.py") == "python" assert Syntax.guess_lexer("banana.py", "import this") == "python" assert Syntax.guess_lexer("banana.html", "<a href='#'>hello</a>") == "html" assert Syntax.guess_lexer("banana.html", "<%= @foo %>") == "rhtml" assert Syntax.guess_lexer("banana.html", "{{something|filter:3}}") == "html+django"
def test_get_number_styles(): syntax = Syntax(CODE, "python", theme="monokai", line_numbers=True) console = Console(color_system="windows") assert syntax._get_number_styles(console=console) == ( Style.parse("on #272822"), Style.parse("dim on #272822"), Style.parse("not dim on #272822"), )
def _patch_code_block(self, console, options): code = str(self.text).rstrip() if self.lexer_name == "default": self.lexer_name = "python" if theme == "light": syntax = Syntax(code, self.lexer_name, theme="tango") else: syntax = Syntax(code, self.lexer_name, theme="brunante") yield syntax
def _patch_code_block(self, console, options): # noqa code = str(self.text).rstrip() if self.lexer_name == "default": self.lexer_name = "python" if style == "light" or style == "tango": syntax = Syntax(code, self.lexer_name, theme="tango", word_wrap=True) else: syntax = Syntax(code, self.lexer_name, theme=style, word_wrap=True) yield syntax
def new_parse_known_args(self, *args, **kwargs): args, extras = self._original_parse_known_args(*args, **kwargs) get_action_value = lambda name: getattr( args, "{}_{}".format(action_prefix, name)) # load saved hyperparameter instance load_value = get_action_value("load") if "load" in inject_actions and load_value is not None: hp_load(load_value, hp_mgr, serial_format) # set hyperparameters set from command lines old_values = hp_mgr.get_values() for k in self.__hpargparse_value_names_been_set(): v = old_values[k] assert hasattr(args, k) t = getattr(args, k) if isinstance(t, StringAsDefault): t = str(t) hp_mgr.set_value(k, t) save_value = get_action_value("save") if "save" in inject_actions and save_value is not None: hp_save(save_value, hp_mgr, serial_format) hp_list_value = get_action_value("list") if "list" in inject_actions and hp_list_value is not None: if hp_list_value == "yaml": syntax = Syntax( yaml.dump(hp_mgr.get_values()).replace("\n\n", "\n"), "yaml", theme="monokai", ) console = Console() console.print(syntax) elif hp_list_value == "json": syntax = Syntax(json.dumps(hp_mgr.get_values()), "json", theme="monokai") console = Console() console.print(syntax) else: assert hp_list_value == "detail", hp_list_value hp_list(hp_mgr) sys.exit(0) hp_detail_value = get_action_value("detail") if "detail" in inject_actions and hp_detail_value: hp_list(hp_mgr) sys.exit(0) if inject_actions and get_action_value("exit"): sys.exit(0) return args, extras
def test(args): # parse model-index.yml model_index_file = MMCLS_ROOT / 'model-index.yml' model_index = load(str(model_index_file)) model_index.build_models_with_collections() models = OrderedDict({model.name: model for model in model_index.models}) script_name = osp.join('tools', 'test.py') port = args.port commands = [] if args.models: patterns = [re.compile(pattern) for pattern in args.models] filter_models = {} for k, v in models.items(): if any([re.match(pattern, k) for pattern in patterns]): filter_models[k] = v if len(filter_models) == 0: print('No model found, please specify models in:') print('\n'.join(models.keys())) return models = filter_models preview_script = '' for model_info in models.values(): if model_info.results is None: continue script_path = create_test_job_batch(commands, model_info, args, port, script_name) preview_script = script_path or preview_script port += 1 command_str = '\n'.join(commands) preview = Table() preview.add_column(str(preview_script)) preview.add_column('Shell command preview') preview.add_row( Syntax.from_path(preview_script, background_color='default', line_numbers=True, word_wrap=True), Syntax(command_str, 'bash', background_color='default', line_numbers=True, word_wrap=True)) console.print(preview) if args.run: os.system(command_str) else: console.print('Please set "--run" to start the job')
def hp_list(mgr): """Print hyperparameter settings to stdout """ syntax = Syntax( "All hyperparameters:\n" + " {}".format(sorted(mgr.get_values().keys())), "python", theme="monokai", ) console = Console() console.print(syntax) # construct a table console = Console() table = Table( title="Details", title_style=Style(color="bright_cyan", bgcolor="grey15", bold=True), style=Style(bgcolor="grey15"), header_style="bold magenta", box=box.DOUBLE, border_style="bright_cyan", show_lines=True, ) table.add_column("name", style="green_yellow") table.add_column("type", style="light_steel_blue") table.add_column("value", style="light_cyan1") table.add_column("details") for k, d in sorted(mgr.db.group_by("name").items()): details = [] for i, oc in enumerate( d.select(L.exist_attr("filename")).sorted( L.order_by("filename"))): # make context detail details.append({ "name": "occurrence[{}]".format(i), "detail": SourceHelper.format_given_filepath_and_lineno( oc.filename, oc.lineno), }) # combine details detail_str = make_detail_str(details) oc = d.sorted(L.value_priority)[0] detail_syntax = Syntax(detail_str, "python", theme="monokai") table.add_row( k, str(type(oc.value).__name__), str(make_value_illu(oc.value)), detail_syntax, ) console.print(table)
def test_highlight_background_color(): syntax = Syntax( CODE, lexer_name="python", line_numbers=True, line_range=(2, 10), theme="foo", code_width=60, word_wrap=True, background_color="red", ) assert syntax.highlight(CODE).style == Style.parse("on red")
def test_syntax_highlight_ranges(): syntax = Syntax( CODE, lexer="python", line_numbers=True, word_wrap=False, ) stylized_ranges = [ _SyntaxHighlightRange( # overline the 2nd char of the 1st line: start=(1, 1), end=(1, 2), style=Style(overline=True), ), _SyntaxHighlightRange( start=(1, len("def loop_")), end=(1, len("def loop_first_last")), style=Style(underline=True), ), _SyntaxHighlightRange( start=(1, len("def loop_first")), end=(3, len(" iter_values = iter")), style=Style(bold=True), ), _SyntaxHighlightRange( start=(9, len(" for ")), end=(9, len(" for value in")), style=Style(strike=True), ), _SyntaxHighlightRange( start=(6, len(" except ")), end=(6, len(" except StopIteration")), style=Style(reverse=True), ), _SyntaxHighlightRange( start=(10, len(" yield first,")), # `column_index` is out of range: should be clamped to the line length: end=(10, 300), style=Style(bold=True), ), # For this one the end `line_number` is out of range, so it should have no impact: _SyntaxHighlightRange( start=(1, 1), end=(30, 2), style=Style(bold=True), ), ] for range_ in stylized_ranges: syntax.stylize_range(range_.style, range_.start, range_.end) rendered_syntax = render(syntax, True) print(repr(rendered_syntax)) expected = '\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 1 \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34md\x1b[0m\x1b[53;38;2;102;217;239;48;2;39;40;34me\x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mf\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;166;226;46;48;2;39;40;34mloop_\x1b[0m\x1b[4;38;2;166;226;46;48;2;39;40;34mfirst\x1b[0m\x1b[1;4;38;2;166;226;46;48;2;39;40;34m_last\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m:\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mIterable\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mT\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m]\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m)\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;249;38;114;48;2;39;40;34m-\x1b[0m\x1b[1;38;2;249;38;114;48;2;39;40;34m>\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mIterable\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mTuple\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m[\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mbool\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mbool\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mT\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m]\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m]\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m:\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 2 \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;230;219;116;48;2;39;40;34m"""Iterate and generate a tuple with a flag for first and last value."""\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 3 \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;249;38;114;48;2;39;40;34m=\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34miter\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalues\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 4 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mtry\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 5 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;249;38;114;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mnext\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m(\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m)\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 6 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mexcept\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[7;38;2;166;226;46;48;2;39;40;34mStopIteration\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 7 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mreturn\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 8 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;249;38;114;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m 9 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mfor\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[9;38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\x1b[9;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[9;38;2;249;38;114;48;2;39;40;34min\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34miter_values\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m:\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m10 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[1;38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m11 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;249;38;114;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mFalse\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m12 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;249;38;114;48;2;39;40;34m=\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mvalue\x1b[0m\n\x1b[1;38;2;227;227;221;48;2;39;40;34m \x1b[0m\x1b[38;2;101;102;96;48;2;39;40;34m13 \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34myield\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mfirst\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;102;217;239;48;2;39;40;34mTrue\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m,\x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34m \x1b[0m\x1b[38;2;248;248;242;48;2;39;40;34mprevious_value\x1b[0m\n' assert rendered_syntax == expected
def __call__(self, obj, *args, **kwargs): # pragma: no cover backend = JupyterMixIn().backend if not backend: return self.func(obj, *args, **kwargs) else: print( f"[{orange_dark}]Cannot run function [bold {salmon}]{self.func.__name__}[/ bold {salmon}] in a jupyter notebook", f"[{orange_dark}]Try setting the correct backend before creating your scene:\n", Syntax("from vedo import embedWindow", lexer_name="python"), Syntax("embedWindow(None)", lexer_name="python"), ) return None
def test_get_line_color_none(): style = PygmentsSyntaxTheme("default") style._background_style = Style(bgcolor=None) syntax = Syntax( CODE, lexer_name="python", line_numbers=True, line_range=(2, 10), theme=style, code_width=60, word_wrap=True, background_color="red", ) assert syntax._get_line_numbers_color() == Color.default()
def train(args): models_cfg = load(str(Path(__file__).parent / 'bench_train.yml')) models_cfg.build_models_with_collections() models = {model.name: model for model in models_cfg.models} script_name = osp.join('tools', 'train.py') port = args.port commands = [] if args.models: patterns = [re.compile(pattern) for pattern in args.models] filter_models = {} for k, v in models.items(): if any([re.match(pattern, k) for pattern in patterns]): filter_models[k] = v if len(filter_models) == 0: print('No model found, please specify models in:') print('\n'.join(models.keys())) return models = filter_models for model_info in models.values(): months = model_info.data.get('Months', range(1, 13)) if datetime.now().month in months: script_path = create_train_job_batch(commands, model_info, args, port, script_name) port += 1 command_str = '\n'.join(commands) preview = Table() preview.add_column(str(script_path)) preview.add_column('Shell command preview') preview.add_row( Syntax.from_path(script_path, background_color='default', line_numbers=True, word_wrap=True), Syntax(command_str, 'bash', background_color='default', line_numbers=True, word_wrap=True)) console.print(preview) if args.run: os.system(command_str) else: console.print('Please set "--run" to start the job')
def __rich__(self) -> Columns: if self.cell_type == CellType.CODE: counter = self.exec_count or " " if settings.display_cell_index: panel_title = f"Index: {self.cell_index}" else: panel_title = None rendered_cell = Columns([ f"\nIn [{counter}]:", Panel( Syntax(self._source_excerpt, "python", background_color="default"), width=int(rich.get_console().size[0] * 0.85), title=panel_title, ), ]) else: rendered_cell = Columns([ " ", Padding(NotebookMarkdown(self._source_excerpt), (1, 0, 1, 8)), ]) return rendered_cell
def write(func, writer, except_, style): # noqa: D301 # \b disables autowrap """`hypothesis write` writes property-based tests for you! Type annotations are helpful but not required for our advanced introspection and templating logic. Try running the examples below to see how it works: \b hypothesis write gzip hypothesis write numpy.matmul hypothesis write re.compile --except re.error hypothesis write --equivalent ast.literal_eval eval hypothesis write --roundtrip json.dumps json.loads hypothesis write --style=unittest --idempotent sorted hypothesis write --binary-op operator.add """ # NOTE: if you want to call this function from Python, look instead at the # ``hypothesis.extra.ghostwriter`` module. Click-decorated functions have # a different calling convention, and raise SystemExit instead of returning. kwargs = {"except_": except_ or (), "style": style} if writer is None: writer = "magic" elif writer == "idempotent" and len(func) > 1: raise click.UsageError( "Test functions for idempotence one at a time.") elif writer == "roundtrip" and len(func) == 1: writer = "idempotent" elif "equivalent" in writer and len(func) == 1: writer = "fuzz" if writer == "errors-equivalent": writer = "equivalent" kwargs["allow_same_errors"] = True try: from hypothesis.extra import ghostwriter except ImportError: sys.stderr.write(MESSAGE.format("black")) sys.exit(1) code = getattr(ghostwriter, writer)(*func, **kwargs) try: from rich.console import Console from rich.syntax import Syntax from hypothesis.utils.terminal import guess_background_color except ImportError: print(code) else: try: theme = "default" if guess_background_color( ) == "light" else "monokai" code = Syntax(code, "python", background_color="default", theme=theme) Console().print(code, soft_wrap=True) except Exception: print("# Error while syntax-highlighting code", file=sys.stderr) print(code)
def display_parsing_table(self, raw=False): begin = r"\begin{array}{|" begin += r"|".join(["c"] * (len(self.terminals) + 1)) begin += r"|}" + '\n' end = r"\end{array}" # create the header header = "\t\hline \n" + "\t" + r"\text{terminal}" for terminal in self.terminals: header += "\t&" header += terminal header += r'\\ \hline' + "\n" cells = "" for nonterminal in self.rules.keys(): line = "\t" + nonterminal for terminal in self.terminals: line += " \t&" if terminal in self.parsing_table[nonterminal]: line += self.display_rule( left=nonterminal, rule=self.parsing_table[nonterminal][terminal], new_line=False, array_environment=False) # line += r"\\ \hline" + '\n' line += r"\\ " + '\n' cells += line cells += r"\hline" + "\n" content = begin + header + cells + end display(Math(content)) if raw: syntax = Syntax(content, "latex") Console().print(syntax)
def _add_code(self, obj, language="python", theme=None, **kwargs): """ Add a Syntax entry to the table """ if theme is None: theme = self._syntax_theme self.tb.add_row(Syntax(obj, lexer=language, theme=theme, **kwargs))
def render(self, notebook): # first draw a blank canvas for the image to sit on top of, and then # register the image to be drawn later. # notebook.draw_plot_later(self, max(3, 5 - (start - k))) return Syntax(" \n" * (self.n_lines - 3), "python", background_color="default")
def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False ) self.syntax = Syntax( code=snippets.PYTHON_SNIPPET, lexer="python", word_wrap=True )
def rules_to_highlighted_string(rules: List[Rule]): yb = YaraBuilder() for rule in rules: if rule.name not in yb.yara_rules.keys(): rule.add_to_yarabuilder(yb) # As there is no yara lexer available in pygments, we're usign python here. return Syntax(yb.build_rules(), "python", background_color="default")
def output_file(filepath, title='', subtitle=''): syntax = Syntax.from_path(filepath, line_numbers=True, word_wrap=True, theme='monokai') panel = Panel(syntax, title=title, subtitle=subtitle) console.print(panel)
def output_syntax(content, lexer='python', line_numbers=True, theme='monokai'): syntax = Syntax(content, lexer=lexer, line_numbers=line_numbers, word_wrap=True, theme=theme) console.print(syntax)
def cli( file: Tuple[io.TextIOWrapper], imports: bool = True, rich: bool = False, line_numbers: bool = False, ) -> None: if len(file) > 1: raise click.BadArgumentUsage( "Multiple files supplied, run with one at a time") if len(file) == 0: if sys.stdin.isatty(): raise click.UsageError( "Either provide the path to the file or pipe a file to dict-typer" ) else: stream = sys.stdin.read().strip() else: stream = file[0].read().strip() try: parsed: Dict = json.loads(stream) except json.decoder.JSONDecodeError as e: raise click.UsageError(f"JSON serialisation error \n\n{e}") output = get_type_definitions(parsed, show_imports=imports) if rich: syntax = Syntax(output, "python", theme="monokai", line_numbers=line_numbers) console = Console() console.print(syntax) else: click.echo(output)
def print_config(config: DictConfig, resolve: bool = True) -> None: content = OmegaConf.to_yaml(config, resolve=resolve) rich.print(Panel( Syntax( content, "yaml", background_color='default', line_numbers=True, code_width=80), title='Config', expand=False))
def _format_output(args, code): if not args['color']: return code lexer = None # try to find a lexer using the StackOverflow tags # or the query arguments for keyword in args['query'].split() + args['tags']: try: lexer = get_lexer_by_name(keyword).name break except ClassNotFound: pass # no lexer found above, use the guesser if not lexer: try: lexer = guess_lexer(code).name except ClassNotFound: return code syntax = Syntax(code, lexer, background_color="default", line_numbers=False) console = Console(record=True) with console.capture() as capture: console.print(syntax) return capture.get()
def generate_patch(args): if len(args): cmd = args[0] else: cmd = "show" ref_dir = patching.create_reference_dir(build_context) patch_contents = patching.create_patch(os.path.join(ref_dir, "work"), build_context.config.work_dir) if patch_contents is None: console.print("[red]No difference found![/red]") else: console.print("\n") console.print(Rule("Diff Contents", end="\n\n")) console.print(Syntax(patch_contents, "diff")) console.print(Rule("", end="\n")) if cmd == "save" and patch_contents: if len(args) >= 2: fn = args[1] if not fn.endswith(".patch"): fn += ".patch" out_fn = Path(build_context.meta_path).parent / fn with open(out_fn, "w") as fo: fo.write(patch_contents) console.print(f"[green]Patch saved under: {out_fn}") else: console.print("[red]Please give a patch name as third argument")
def print_config( config: DictConfig, fields: Sequence[str] = ( "data", "models", ), resolve: bool = True, ) -> None: """Prints content of DictConfig using Rich library and its tree structure. Args: config (DictConfig): Config. fields (Sequence[str], optional): Determines which main fields from config will be printed and in what order. resolve (bool, optional): Whether to resolve reference fields of DictConfig. """ style = "dim" tree = Tree(f":gear: CONFIG", style=style, guide_style=style) for field in fields: branch = tree.add(field, style=style, guide_style=style) config_section = config.get(field) branch_content = str(config_section) if isinstance(config_section, DictConfig): branch_content = OmegaConf.to_yaml(config_section, resolve=resolve) branch.add(Syntax(branch_content, "yaml")) printr(tree)
def exception_handler(engine): """It is a context manager which can handle exceptions and deal with them.""" try: yield except KeyboardInterrupt: spooky_season = [":skull:", ":vampire:", ":zombie:", ":jack-o-lantern:"] console.print(random.choice(spooky_season)) except botocore.exceptions.BotoCoreError as e: console.log("BotoCoreError: ", e) except ParseException as e: console.log("Engine: ParseException") syntax = Syntax( engine.pformat_exc(e), "sql", theme="monokai", line_numbers=True, word_wrap=True, ) console.print(Panel(syntax, title="Engine Details", expand=False)) except EngineRuntimeError as e: console.log(e) except SyntaxError as e: console.log(e) except Exception: console.print_exception()
def _show_code(self, code, start_lineno, curr_lineno=set()): highlight_lines = {curr_lineno} if self.enable_rich: syntax = Syntax(code, "python", line_numbers=True, start_line=start_lineno, highlight_lines=highlight_lines) self.console.print(syntax) else: self.message(code)