def play(self, _ev=None): log.info('currently playing: %s', self.current_station) media = self.instance.media_new(self.current_station['url']) self.wm.playing = HTML('<u>Playing</u>: ' + self.current_station['name']) self.app.layout = self.wm.layout self.keep_window() self.player.set_media(media) self.player.play()
def _get_token(self): auth_url = self.app.oauth_client.auth_url try: webbrowser.open(auth_url) self.waiting_layout.children.append( Window(FormattedTextControl(HTML( 'Looks like that worked. Sweet!\n' 'Please follow the instructions in your browser.' )), align=WindowAlign.CENTER, wrap_lines=True) ) except webbrowser.Error: self.waiting_layout.children.append( Window(FormattedTextControl(HTML( 'Yikes, that didn\'t work. Please manually paste this URL into your browser:\n' + auth_url )), align=WindowAlign.CENTER, wrap_lines=False) ) self.update() code = self.app.oauth_client.wait_for_code() self.waiting_layout.children = [ Window(FormattedTextControl(HTML( '\n\n\n\n\nFinishing the last bits...' )), align=WindowAlign.CENTER, wrap_lines=False) ] self.update() token = self.app.oauth_client.get_token(code) token.save('cache/token.json') self.app.token = token self.app.user = token.get_user() time.sleep(2) self.waiting_layout.children = [ Window(FormattedTextControl(HTML( '\n\n\n\n\n<b>Done!</b>\n\n' f'Signed in as <b>{self.app.user.username}#{self.app.user.discriminator}</b>.\n\n' )), align=WindowAlign.CENTER, wrap_lines=False) ] self.update() time.sleep(2) self.app.set_menu(MainMenu)
def run(self): try: self.__open_brain() except Exception as ex: print(HTML(f"<style fg='ansired'>Unable to open brain: {ex}</style>")) command = "" while command != "/q": try: command = self.__prompt().strip() if command.startswith("/"): self.__execute(command) else: self.__execute("/activate-thought " + command) except CommandException as ex: print(HTML(f"<style fg='ansired'>{ex.message}</style>")) print(ex.__traceback__) except Exception as ex: print(HTML(f"<style fg='ansired'>{ex}</style>"))
def options_to_html( options: Sequence[Tuple[RadioListType, AnyFormattedText]], ) -> Sequence[Tuple[RadioListType, AnyFormattedText]]: formatted_options: List[Tuple[RadioListType, AnyFormattedText]] = [] for option in options: option_text = HTML(cast(str, option[1])) formatted_options.append((option[0], option_text)) return formatted_options
def bottom_toolbar(): if swapped[0]: on = 'on=true' else: on = 'on=false' return HTML( 'Press <style bg="#222222" fg="#ff8888">[control-t]</style> ' 'to swap between dark/light colors. ' '<style bg="ansiblack" fg="ansiwhite">[%s]</style>') % on
def format( self, progress_bar: "ProgressBar", progress: "ProgressBarCounter[object]", width: int, ) -> AnyFormattedText: text = _format_timedelta(progress.time_elapsed).rjust(width) return HTML("<time-elapsed>{time_elapsed}</time-elapsed>").format( time_elapsed=text)
def format( self, progress_bar: "ProgressBar", progress: "ProgressBarCounter[object]", width: int, ) -> AnyFormattedText: value = progress.items_completed / progress.time_elapsed.total_seconds( ) return HTML(self.template.format(iterations_per_second=value))
def run(session): accounts = session.query(Account).all() columns = [Column('Account', 'l', 30), Column('Currency', 'l', 8), Column('Balance', 'r', 20)] balances = [get_account_balance(session, a) for a in accounts] usd = session.query(Currency).filter(Currency.code == 'USD').one() total_balance = Money(sum(balance.usd_amount() for balance in balances), usd) data = [[a.name, a.currency.code, balance] for a, balance in zip(accounts, balances)] data.append([HTML('<b>Total</b>'), usd.code, total_balance]) draw_table(columns, data)
def test_basic_html(): html = HTML("<i>hello</i>") assert to_formatted_text(html) == [("class:i", "hello")] html = HTML("<i><b>hello</b></i>") assert to_formatted_text(html) == [("class:i,b", "hello")] html = HTML("<i><b>hello</b>world<strong>test</strong></i>after") assert to_formatted_text(html) == [ ("class:i,b", "hello"), ("class:i", "world"), ("class:i,strong", "test"), ("", "after"), ] # It's important that `to_formatted_text` returns a `FormattedText` # instance. Otherwise, `print_formatted_text` won't recognise it and will # print a list literal instead. assert isinstance(to_formatted_text(html), FormattedText)
def help(): print_formatted_text( HTML( "\nLIST OF COMMANDS:\n" "<red>exit</red>\t\t\tquits the program\n" "<red>list</red>\t\t\tlists the 10 most recent games played\n" "<red>info(game_num)</red>\t\tdisplays game info\n" "<red>view(game_num)</red>\t\tdisplays the game moves in slideshow format\n" "<red>analyse(game_num)</red>\tdisplays game moves along with engine suggestions\n\tCtrl-A: Prev. Move | Ctrl-D: Next Move | Ctrl-Q: Exit" ))
def test_basic_html(): html = HTML('<i>hello</i>') assert to_formatted_text(html) == [('class:i', 'hello')] html = HTML('<i><b>hello</b></i>') assert to_formatted_text(html) == [('class:i,b', 'hello')] html = HTML('<i><b>hello</b>world<strong>test</strong></i>after') assert to_formatted_text(html) == [ ('class:i,b', 'hello'), ('class:i', 'world'), ('class:i,strong', 'test'), ('', 'after'), ] # It's important that `to_formatted_text` returns a `FormattedText` # instance. Otherwise, `print_formatted_text` won't recognise it and will # print a list literal instead. assert isinstance(to_formatted_text(html), FormattedText)
def format( self, progress_bar: "ProgressBar", progress: "ProgressBarCounter[object]", width: int, ) -> AnyFormattedText: index = int(time.time() * 3) % len(self.characters) return HTML("<spinning-wheel>{0}</spinning-wheel>").format( self.characters[index])
def create_pager_prompt( style: BaseStyle, title: AnyFormattedText = "" ) -> PromptSession[PagerResult]: """ Create a "continue" prompt for paginated output. """ bindings = KeyBindings() @bindings.add("enter") @bindings.add("down") def next_line(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.NEXT_LINE) @bindings.add("space") def next_page(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.NEXT_PAGE) @bindings.add("a") def print_all(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.PRINT_ALL) @bindings.add("q") @bindings.add("c-c") @bindings.add("c-d") @bindings.add("escape", eager=True) def no(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.ABORT) @bindings.add("<any>") def _(event: KeyPressEvent) -> None: "Disallow inserting other text." pass style session: PromptSession[PagerResult] = PromptSession( merge_formatted_text( [ title, HTML( "<status-toolbar>" "<more> -- MORE -- </more> " "<key>[Enter]</key> Scroll " "<key>[Space]</key> Next page " "<key>[a]</key> Print all " "<key>[q]</key> Quit " "</status-toolbar>: " ), ] ), key_bindings=bindings, erase_when_done=True, style=style, ) return session
def row(cmt, num, ins, de): message = cmt.message.split('\n')[0] # 添加分支和tag信息 try: for ref in repo.remote().refs: if cmt == ref.commit: message = f'<b><style bg="ansired" fg="ansiwhite">[️{ref.name}]</style></b>' + message except NoSectionError: # 处理未关联remote分支的场景 pass for tag in repo.tags: if cmt == tag.commit: message = f'<b><style bg="ansiyellow" fg="ansiblack">[️Tag:{tag.name}]</style></b>' + message for head in repo.heads: if cmt == head.commit: message = f'<b><style bg="ansigreen" fg="ansiblack">[️{head.name}]</style></b>' + message if cmt == repo.head.commit: message = '<b><style bg="ansiblue" fg="ansiblack">[HEAD]</style></b>' + message try: message = HTML(message) except xml.parsers.expat.ExpatError: # messge中包含特殊字符时 pass return VSplit([ Window(content=FormattedTextControl(f'{num}'), width=5), Window(width=1, char="|"), Window(content=FormattedTextControl(cmt.hexsha[:7]), width=9), Window(width=1, char="|"), Window(content=FormattedTextControl(cmt.committer.name), width=20), Window(width=1, char="|"), Window(content=FormattedTextControl( cmt.committed_datetime.strftime('%Y-%m-%d %H:%M:%S')), width=21), Window(width=1, char="|"), Label(HTML(f'<b><style fg="ansigreen">+{ins}</style></b>'), width=5), Label(HTML(f'<b><style fg="ansired">-{de}</style></b>'), width=5), Window(width=1, char="|"), Label(message) ])
def test_html_interpolation(): # %-style interpolation. value = HTML("<b>%s</b>") % "hello" assert to_formatted_text(value) == [("class:b", "hello")] value = HTML("<b>%s</b>") % ("hello", ) assert to_formatted_text(value) == [("class:b", "hello")] value = HTML("<b>%s</b><u>%s</u>") % ("hello", "world") assert to_formatted_text(value) == [("class:b", "hello"), ("class:u", "world")] # Format function. value = HTML("<b>{0}</b><u>{1}</u>").format("hello", "world") assert to_formatted_text(value) == [("class:b", "hello"), ("class:u", "world")] value = HTML("<b>{a}</b><u>{b}</u>").format(a="hello", b="world") assert to_formatted_text(value) == [("class:b", "hello"), ("class:u", "world")]
def rprompt(self): brain = self.__api.brains.active if not brain: return "" if not brain.active_thought: return "" if brain.active_thought.has_component("taxonomy"): category = brain.active_thought.taxonomy.category or "" tags = ", ".join(sorted(brain.active_thought.taxonomy.tags)) return HTML(f"<style bg='#ff0066'>{category}</style> <style bg='#6600ff'>{tags}</style>") return ""
def commit_type(): result = radiolist_dialog( title=HTML(f'Choose a commit type: (Press {ansired("Enter")} to confirm, {ansired("Ctrl+C")} to cancel.)'), values=[ (emoji.Commit.FEATURE.value, HTML(f'<style bg="orange" fg="black">{emoji.Commit.FEATURE.value}[feature]: 新功能</style>')), (emoji.Commit.BUGFIX.value, HTML(f'<style bg="green" fg="black">{emoji.Commit.BUGFIX.value}[bugfix]: 修复问题</style>')), (emoji.Commit.REFACTOR.value, HTML(f'<style bg="red" fg="black">{emoji.Commit.REFACTOR.value}[refactor]: 重构</style>')), (emoji.Commit.CHORE.value, HTML(f'<style bg="blue" fg="black">{emoji.Commit.CHORE.value}[chore]: 工具依赖变动</style>')), (emoji.Commit.DOCUMENT.value, HTML(f'<style bg="gray" fg="white">{emoji.Commit.DOCUMENT.value}[document]: 文档或注释</style>')), (emoji.Commit.STYLE.value, HTML(f'<style bg="gray" fg="white">{emoji.Commit.STYLE.value}[style]: 格式</style>')), (emoji.Commit.TEST.value, HTML(f'<style bg="gray" fg="white">{emoji.Commit.TEST.value}[test]: 添加测试</style>')) ]) return result
def test_html_interpolation(): # %-style interpolation. value = HTML('<b>%s</b>') % 'hello' assert to_formatted_text(value) == [('class:b', 'hello')] value = HTML('<b>%s</b>') % ('hello', ) assert to_formatted_text(value) == [('class:b', 'hello')] value = HTML('<b>%s</b><u>%s</u>') % ('hello', 'world') assert to_formatted_text(value) == [('class:b', 'hello'), ('class:u', 'world')] # Format function. value = HTML('<b>{0}</b><u>{1}</u>').format('hello', 'world') assert to_formatted_text(value) == [('class:b', 'hello'), ('class:u', 'world')] value = HTML('<b>{a}</b><u>{b}</u>').format(a='hello', b='world') assert to_formatted_text(value) == [('class:b', 'hello'), ('class:u', 'world')]
def display_analysis_screen(event, game_list, game_number, moves, move_place, analysis_archive): chess_text = set_analysis_chess_text(game_list, game_number, moves, move_place, analysis_archive) event.app.layout.container.children[2].content.text = HTML(chess_text) set_analysis_history_text(event, game_list, game_number, move_place, analysis_archive) event.app.renderer._last_size: Optional[Size] = None event.app.renderer.output.flush()
def format( self, progress_bar: "Progress", progress: "PlayerModel", width: int, ) -> AnyFormattedText: if not isinstance(progress, PlayerModel): return '' player: PlayerModel = progress return HTML("<video-file>{text}</video-file>").format( text=self.get_render_text(player))
def apply_transformation(self, ti): try: fragments = to_formatted_text( HTML(fragment_list_to_text(ti.fragments))) except Exception as ex: # xml.parsers.expat.ExpatError # not well-formed (invalid token): line 1, column 138 logger.error('FormatText: {} {}'.format(type(ex), str(ex))) #return Transformation([('', ' ')]) return Transformation([]) return Transformation(fragments)
def example_2(): """ Using HTML for the formatting. """ answer = prompt(HTML('<username>john</username><at>@</at>' '<host>localhost</host>' '<colon>:</colon>' '<path>/user/john</path>' '<style bg="#00aa00" fg="#ffffff">#</style> '), style=style) print('You said: %s' % answer)
async def show_notification(self, message: str, timeout: int): """ Shows notification in the reserved space for `timeout` and then hides :param message: Message to display :param timeout: Timeout """ self.notification_text = HTML( f'<style bg="white" color="black">[ {message} ]</style>') await asyncio.sleep(timeout) self.notification_text = None
def format(self, progress_bar: 'ProgressBar', progress: 'ProgressBarCounter', width: int) -> AnyFormattedText: time_left = progress.time_left if time_left is not None: formatted_time_left = _format_timedelta(time_left) else: formatted_time_left = self.unknown return HTML( self.template).format(time_left=formatted_time_left.rjust(width))
def select_keys_directory(network): # Prompt the user for a directory that contains keys he generated already for the selected # network valid_keys_directory = False entered_directory = None input_canceled = False while not valid_keys_directory: not_valid_msg = '' if entered_directory is not None: not_valid_msg = (''' <style bg="red" fg="black">Your last input was <b>not a valid keys directory</b>. Please make sure to enter a valid keys directory.</style>''') entered_directory = input_dialog(title='Keys directory', text=(HTML(f''' Please enter the directory in which we can find the keys you generated. It should include all the files that the eth2.0-deposit-cli tool created including: - deposit_data(...).json - keystore-(...).json When creating your keys offline or elsewhere, make sure you select the correct network: {network.capitalize()} * Press the tab key to switch between the controls below{not_valid_msg} '''))).run() if not entered_directory: input_canceled = True break tilde_index = entered_directory.find('~') if tilde_index != -1: entered_directory = entered_directory.replace( '~', str(Path.home()), 1) entered_directory = Path(entered_directory) if not entered_directory.is_dir(): continue generated_keys = search_for_generated_keys(entered_directory) if (generated_keys['deposit_data_path'] is not None and len(generated_keys['keystore_paths']) > 0): valid_keys_directory = True if input_canceled: return '' return entered_directory
async def update_spots(application): """ Coroutine that updates spots """ lasthash = "" try: while True: r = requests.get( 'http://www.dxsummit.fi/DxSpots.aspx?count=50&include_modes=PHONE') cleantext = BeautifulSoup(r.text, "lxml").get_text() currenthash = hashlib.md5(cleantext.encode('utf-8')).hexdigest() clusterdata = [] i = 0 for line in cleantext.splitlines(): line = line[:73] + ':' + line[73:] #line = line[:76] + line[84:] cleanline = ' '.join(line.split()) splitstring = cleanline.split(sep=" ", maxsplit=3) clusterdata.append( (hashlib.md5(line.encode('utf-8')).hexdigest() + " " + splitstring[1]+" "+splitstring[2], " " + line)) data = cleanline.split(sep=" ", maxsplit=3) if ((auto_tune.checked is True) and (i == 0) and (data[2] != globalvars['lastcall'])): globalvars['lastcall'] = data[2] frequency.content=FormattedTextControl(HTML('<b fg="#884444">Freq.:</b> ' + (data[1] + " Khz").rjust(15))) dx.content=FormattedTextControl(HTML('<b fg="#884444">Call:</b> ' + data[2].rjust(12))) if qrz.checked is True: redis.rpush('qrzLookupQueue',data[2]) i+=1 radios.values = clusterdata if currenthash != lasthash: application.invalidate() await asyncio.sleep(15) else: await asyncio.sleep(30) except asyncio.CancelledError: #TODO safe config here ? print()
def _rmove(group, deltas, refresh_period=0.1, bar_options=None): start_states = group.get_states() start_positions = group.get_pos() final_positions = [p + d for p, d in zip(start_positions, deltas)] motion = Motion( group, start_states, start_positions, start_positions, final_positions ) def motion_loop(gen): for states, positions in gen_rate_limiter(gen, refresh_period): prog_bar.update(states, positions) def on_ok(): nonlocal title title = HTML("<done>Finished!</done>") def on_error(error): nonlocal title group.start_stop() kb = isinstance(error, KeyboardInterrupt) if kb: msg = "<ctrlc>Stopping... </ctrlc>" else: msg = "<error>Motion error: {!r}<error>. ".format(error) msg += "Waiting for motors to stop..." title = HTML(msg) motion_loop(gen_motion(group)) title = HTML(msg + "[<done>DONE</done>]") def always_end_with(): prog_bar.update(group.get_states(), group.get_pos()) title = HTML("<preparing>Preparing...</preparing>") bar_options = bar_options or {} bar_options.setdefault("title", lambda: title) prog_bar = MotionProgressBar(motion, bar_options=bar_options) power = ensure_power(group) handler = MotionHandler(on_ok, on_error, always_end_with) with prog_bar, power, handler: title = HTML("<moving>Moving...</moving>") motion_loop(gen_rmove(group, deltas))
def get_info_app(app: Flask): left_part = HTML("<left-part>" " <import_name>%s</import_name> " "<path>%s</path>" "</left-part>") % (app.import_name, app.root_path) right_part = HTML("<right-part> " " <env>%s</env> " " <time>%s</time> " "</right-part>") % (os.environ["ZEMFROG_ENV"], datetime.datetime.now().isoformat()) used_width = sum([ fragment_list_width(to_formatted_text(left_part)), fragment_list_width(to_formatted_text(right_part)), ]) total_width = get_app().output.get_size().columns padding_size = total_width - used_width padding = HTML("<padding>%s</padding>") % (" " * padding_size, ) return left_part, padding, right_part, "\n"
def format(self, progress_bar, progress, width): label = self._add_suffix(progress.label) cwidth = get_cwidth(label) if cwidth > width: # It doesn't fit -> scroll task name. max_scroll = cwidth - width current_scroll = int(time.time() * 3 % max_scroll) label = label[current_scroll:] # It does fit. return HTML(self.template).format(label=label)
def test_with_style(): """ Text `print_formatted_text` with `HTML` wrapped in `to_formatted_text`. """ f = _Capture() html = HTML('<ansigreen>hello</ansigreen> <b>world</b>') formatted_text = to_formatted_text(html, style='class:myhtml') pt_print(formatted_text, file=f) assert f.data == \ b'\x1b[0m\x1b[?7h\x1b[0;32mhello\x1b[0m \x1b[0;1mworld\x1b[0m\r\n\x1b[0m'