def example(context, container=None): ''' Discover API members that have a code example. ''' from static_frame.core.display_color import HexColor from doc.source.conf import get_jinja_contexts contexts = get_jinja_contexts() defined = contexts['examples_defined'] signatures = set() # discover all signatures; if it is defined, print in a darker color for name, cls, frame in contexts['interface'].values(): for signature, row in frame.iter_tuple_items(axis=1): target = f'{name}-{row.signature_no_args}' signatures.add(target) # accumulate all signatures if container and name != container: continue if target in defined: print(HexColor.format_terminal(0x505050, target)) else: print(target) for line in sorted(defined - signatures): print(HexColor.format_terminal(0x00ccff, line))
def __str__(self) -> str: if self.value[0]: v = '✓' # make a check mark else: v = '?' if self.value[1]: return HexColor.format_terminal('darkgreen', str(v)) return HexColor.format_terminal('darkorange', str(v))
def test_hex_color_format_a(self) -> None: msg = HexColor.format_terminal('#4b006e', 'test') self.assertEqual(msg, '\x1b[38;5;53mtest\x1b[0m') msg = HexColor.format_terminal(0xaaaaaa, 'test') self.assertEqual(msg, '\x1b[38;5;248mtest\x1b[0m') msg = HexColor.format_terminal('0xaaaaaa', 'test') self.assertEqual(msg, '\x1b[38;5;248mtest\x1b[0m') msg = HexColor.format_terminal('#040273', 'test') self.assertEqual(msg, '\x1b[38;5;4mtest\x1b[0m')
def format(key: tp.Tuple[tp.Any, str], v: object) -> str: nonlocal name_root_last nonlocal name_root_count if isinstance(v, float): if np.isnan(v): return '' return str(round(v, 4)) if isinstance(v, (bool, np.bool_)): if v: return HexColor.format_terminal('green', str(v)) return HexColor.format_terminal('orange', str(v)) return str(v)
def test_display_value_color_a(self) -> None: f1 = ff.parse('s(10,3)|i(I,str)') s2 = f1.assign[1].apply(lambda s: s.iter_element().apply( lambda e: HexColor.format_terminal('green' if e > 0 else 'blue', str(e)))) post = s2.display()
class Animator: PROMPT = HexColor.format_terminal('lightgrey', '>>> ') CHAR_INTERVAL = 0.04 #0.07 CHAR_JITTER = [x * .01 for x in range(6)] + [0.08, .12] @classmethod def print_char(cls, char: str) -> None: print(char, end='') sys.stdout.flush() time.sleep(cls.CHAR_INTERVAL + random.choice(cls.CHAR_JITTER)) @classmethod def pause(cls, interval: float) -> None: print(cls.PROMPT, end='') sys.stdout.flush() time.sleep(interval) print() # newline sys.stdout.flush() @classmethod def main(cls, func: tp.Callable[[], LineIter]) -> None: for line in func(): if line is PAUSE_SHORT: cls.pause(0.5) continue if line is PAUSE_LONG: cls.pause(2) continue if line is PAUSE_FINAL: cls.pause(5) continue assert isinstance(line, (Comment, str)) print(cls.PROMPT, end='') for char in line: cls.print_char(char) cls.print_char('\n') # get new line if isinstance(line, Comment): continue try: post = eval(line) if post is not None: print(post) except SyntaxError: exec(line) except MemoryError as e: traceback.print_exc(limit=-3)
def format(key: tp.Tuple[tp.Any, str], v: object) -> str: nonlocal name_root_last nonlocal name_root_count if isinstance(v, float): if np.isnan(v): return '' return str(round(v, 4)) if isinstance(v, (bool, np.bool_)): if v: return HexColor.format_terminal('green', str(v)) return HexColor.format_terminal('orange', str(v)) if isinstance(v, str): if key[1] == 'explanation': return HexColor.format_terminal('gray', v) if key[1] == 'name': name_root = v.split('.')[0] if name_root != name_root_last: name_root_last = name_root name_root_count += 1 if name_root_count % 2: return HexColor.format_terminal('lavender', v) return HexColor.format_terminal('lightslategrey', v) return str(v)
def type_color_markup(type_label: str, type_category: DisplayTypeCategory, config: DisplayConfig) -> str: ''' Return a format string for applying color to a type based on type category and config. ''' color = getattr(config, type_category.CONFIG_ATTR) if config.display_format in _DISPLAY_FORMAT_HTML: return HexColor.format_html(color, FORMAT_EMPTY) if config.display_format in _DISPLAY_FORMAT_TERMINAL: if terminal_ansi(): return HexColor.format_terminal(color, FORMAT_EMPTY) # if not a compatible terminal, return label unaltered return FORMAT_EMPTY raise NotImplementedError('no handling for display format:', config.display_format)
def type_color_markup( type_label: str, type_category: DisplayTypeCategory, config: DisplayConfig ): ''' Return type label with markup for color. ''' color = getattr(config, type_category.CONFIG_ATTR) if config.display_format in _DISPLAY_FORMAT_HTML: return HexColor.format_html(color, type_label) elif config.display_format in _DISPLAY_FORMAT_TERMINAL: if terminal_ansi(): return HexColor.format_terminal(color, type_label) # if not a compatible terminal, return label unaltered return type_label raise NotImplementedError('no handling for display format:', config.display_format)
def type_color_markup(type_category: tp.Type[DisplayTypeCategory], config: DisplayConfig) -> str: ''' Return a format string for applying color to a type based on type category and config. Returns: A templated string with a "text" field for formatting. ''' color = getattr(config, type_category.CONFIG_ATTR) if config.display_format in _DISPLAY_FORMAT_HTML: return HexColor.format_html(color, FORMAT_EMPTY) if config.display_format in _DISPLAY_FORMAT_TERMINAL and terminal_ansi( ): return HexColor.format_terminal(color, FORMAT_EMPTY) #pragma: no cover # if not a compatible terminal, return label unaltered return FORMAT_EMPTY
columns_dtype_group=columns_dtype_group) return st.one_of((st_frame, st_frame_go)) if __name__ == '__main__': import fnmatch from argparse import ArgumentParser from static_frame.core.display_color import HexColor parser = ArgumentParser() parser.add_argument('-n', '--name', default=None) parser.add_argument('-c', '--count', default=2, type=int) options = parser.parse_args() local_items = tuple(locals().items()) for v in (v for k, v in local_items if callable(v) and k.startswith('get')): if options.name: if not fnmatch.fnmatch(v.__name__, options.name): continue print(HexColor.format_terminal('grey', '.' * 50)) print(HexColor.format_terminal('hotpink', str(v.__name__))) for x in range(options.count): print(HexColor.format_terminal('grey', '.' * 50)) example = v().example() print(repr(example))
def __iter__(self) -> tp.Iterator[str]: return HexColor.format_terminal(self.color, self.message).__iter__()
class Animator: PROMPT = HexColor.format_terminal('lightgrey', '>>> ') CHAR_INTERVAL = 0.03 #0.07 CHAR_JITTER = [x * .01 for x in range(6)] + [0.10, .12] @classmethod def print_char(cls, char: str) -> None: print(char, end='') sys.stdout.flush() # time.sleep(cls.CHAR_INTERVAL + random.choice(cls.CHAR_JITTER)) @classmethod def pause(cls, interval: float) -> None: print(cls.PROMPT, end='') sys.stdout.flush() time.sleep(interval) print() # newline sys.stdout.flush() @classmethod def main(cls, func: tp.Callable[[], LineIter]) -> None: import static_frame as sf import numpy as np from string import ascii_lowercase for line in func(): if line is PAUSE_SHORT: cls.pause(1) continue if line is PAUSE_LONG: cls.pause(2.5) continue if line is PAUSE_FINAL: cls.pause(5) continue assert isinstance(line, (Comment, str)) print(cls.PROMPT, end='') for char in line: cls.print_char(char) cls.print_char('\n') # get new line if isinstance(line, Comment): continue # NOTE: exec puts variables in this scope; pass globals and locals eval, exec g = globals() g['sf'] = sf g['np'] = np g['ascii_lowercase'] = ascii_lowercase l = locals() try: post = eval(line, g, l) if post is not None: print(post) except SyntaxError: exec(line, g, l) except MemoryError as e: traceback.print_exc(limit=-3)
try: # This lets us play nicely with IPython: from builtins import __IPYTHON__ #type: ignore from IPython import embed from IPython import get_ipython except ImportError: is_ipython = False else: is_ipython = __IPYTHON__ if __name__ == '__main__': if is_ipython: ipython = get_ipython() print() # Spacer. for command in commands: ipython.auto_rewrite_input(command) print() # Spacer. embed(user_ns=imports, colors='neutral') else: banner_head = f'Python {version} on {platform}\n' banner_body = '\n'.join(f'>>> {command}' for command in commands) interact(banner=(banner_head + HexColor.format_terminal(0x505050, banner_body)), local=imports, exitmsg='')