def show_asset_state(self, args): item = get_arg(args) if item is not None: if item == 'search': query = get_arg(args, 1) results = Blockchain.Default().SearchAssetState(query) print("Found %s results for %s" % (len(results), query)) for asset in results: bjson = json.dumps(asset.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') return asset = Blockchain.Default().GetAssetState(item) if asset is not None: bjson = json.dumps(asset.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Asset %s not found" % item) else: print("Please specify an asset hash")
def print_timings(self, timings): timings = self.connection.get_last_timings() if timings is None: return r = datetime.humanize_time_delta buf = {} if timings.get('graphql_translation'): buf['GraphQL->EdgeQL'] = r(timings.get('graphql_translation')) if timings.get('parse_eql'): buf['Parse'] = r(timings.get('parse_eql')) if timings.get('compile_eql_to_ir'): buf['EdgeQL->IR'] = r(timings.get('compile_eql_to_ir')) if timings.get('compile_ir_to_sql'): buf['IR->SQL'] = r(timings.get('compile_ir_to_sql')) if timings.get('execution'): buf['Exec'] = r(timings.get('execution')) if buf: tokens = [] for k, v in buf.items(): tokens.append((pt_token.Token.Timing.Key, f'{k}: ')) tokens.append((pt_token.Token.Timing.Value, f'{v} ')) pt_shortcuts.print_tokens(tokens, style=self.style) print()
def show_contract_state(self, args): item = get_arg(args) if item is not None: if item.lower() == 'all': contracts = Blockchain.Default().ShowAllContracts() print("Contracts: %s" % contracts) elif item.lower() == 'search': query = get_arg(args, 1) if query: contracts = Blockchain.Default().SearchContracts(query=query) print("Found %s results for %s" % (len(contracts), query)) for contract in contracts: bjson = json.dumps(contract.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Please specify a search query") else: contract = Blockchain.Default().GetContract(item) if contract is not None: contract.DetermineIsNEP5() jsn = contract.ToJson() bjson = json.dumps(jsn, indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Please specify a contract")
def show_mem(self): process = psutil.Process(os.getpid()) total = process.memory_info().rss totalmb = total / (1024 * 1024) out = "Total: %s MB\n" % totalmb out += "Total buffers: %s\n" % StreamManager.TotalBuffers() print_tokens([(Token.Number, out)], self.token_style)
def show_state(self): height = Blockchain.Default().Height headers = Blockchain.Default().HeaderHeight diff = height - self.start_height now = datetime.datetime.utcnow() difftime = now - self.start_dt mins = difftime / datetime.timedelta(minutes=1) secs = mins * 60 bpm = 0 tps = 0 if diff > 0 and mins > 0: bpm = diff / mins tps = Blockchain.Default().TXProcessed / secs out = "Progress: %s / %s\n" % (height, headers) out += "Block-cache length %s\n" % Blockchain.Default().BlockCacheCount out += "Blocks since program start %s\n" % diff out += "Time elapsed %s mins\n" % mins out += "Blocks per min %s \n" % bpm out += "TPS: %s \n" % tps tokens = [(Token.Number, out)] print_tokens(tokens, self.token_style)
def show_nodes(self): if len(NodeLeader.Instance().Peers) > 0: out = "Total Connected: %s " % len(NodeLeader.Instance().Peers) for peer in NodeLeader.Instance().Peers: out += "Peer %s - IO: %s\n" % (peer.Name(), peer.IOStats()) print_tokens([(Token.Number, out)], self.token_style) else: print("Not connected yet\n")
def main(): style = style_from_dict({ Token.Hello: '#ff0066', Token.World: '#44ff44 italic', }) tokens = [ (Token.Hello, 'Hello '), (Token.World, 'World'), (Token, '\n'), ] print_tokens(tokens, style=style)
def print_color(self, string, end='\n', **kwargs): """Prints a color string using prompt-toolkit color management.""" env = builtins.__xonsh_env__ self.styler.style_name = env.get('XONSH_COLOR_STYLE') if isinstance(string, str): tokens = partial_color_tokenize(string + end) else: # assume this is a list of (Token, str) tuples and just print tokens = string proxy_style = PygmentsStyle(xonsh_style_proxy(self.styler)) print_tokens(tokens, style=proxy_style)
def main(): style = PygmentsStyle.from_defaults(style_dict={ Token.Hello: '#ff0066', Token.World: '#44ff44 italic', }) tokens = [ (Token.Hello, 'Hello '), (Token.World, 'World'), (Token, '\n'), ] print_tokens(tokens, style=style)
def test_with_style(): f = _Capture() style = style_from_dict({ Token.Hello: '#ff0066', Token.World: '#44ff44 italic', }) tokens = [ (Token.Hello, 'Hello '), (Token.World, 'world'), ] print_tokens(tokens, style=style, file=f) assert b'\x1b[0;38;5;197mHello' in f.data assert b'\x1b[0;38;5;83;3mworld' in f.data
def show_account_state(self, args): item = get_arg(args) if item is not None: account = Blockchain.Default().GetAccountState(item, print_all_accounts=True) if account is not None: bjson = json.dumps(account.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Account %s not found" % item) else: print("Please specify an account address")
def dump_summary(retcode, start, end): tokens = [ (Token.NORMAL, "\n" + "=" * 80 + "\n[Return "), (Token.NORMAL if retcode == 0 else Token.ALERM, "%d" % retcode), (Token.NORMAL, "] [Start %s] [End %s] [Elapsed %.3f sec]\n" % ( time.strftime("%H:%M:%S", time.localtime(start)) + ".%d" % int(1000 * (start - int(start))), time.strftime("%H:%M:%S", time.localtime(end)) + ".%d" % int(1000 * (end - int(end))), end - start ) ) ] print_tokens(tokens, style=SUMMARY_STYLE)
def print_colored(text): my_style = style_from_dict(Console.Colors) tokens = [] while True: pos_start, size, token = Console.find_color(text) if pos_start != -1: text = text[pos_start+size:] pos_end, size, token_end = Console.find_color(text); token_end if pos_end != -1: tokens.append((token, text[:pos_end])) else: tokens.append((token, text)) break else: break print_tokens(tokens, style=my_style)
def show_tx(self, args): if len(args): try: txid = UInt256.ParseString(get_arg(args)) tx, height = Blockchain.Default().GetTransaction(txid) if height > -1: jsn = tx.ToJson() jsn['height'] = height jsn['unspents'] = [uns.ToJson(tx.outputs.index(uns)) for uns in Blockchain.Default().GetAllUnspent(txid)] tokens = [(Token.Command, json.dumps(jsn, indent=4))] print_tokens(tokens, self.token_style) print('\n') except Exception as e: print("Could not find transaction from args: %s (%s)" % (e, args)) else: print("Please specify a TX hash")
def describe_note(self, notepath): note = parse_note(notepath) tokens = [] tokens.append((Token.Attribute, '{:>20}'.format('title: '))) tokens.append((Token.Value, note.title + '\n')) tokens.append((Token.Attribute, '{:>20}'.format('date: '))) tokens.append((Token.Value, note.creation_date + '\n')) tokens.append((Token.Attribute, '{:>20}'.format('last modified: '))) tokens.append((Token.Value, note.modification_date + '\n')) tokens.append((Token.Attribute, '{:>20}'.format('tags: '))) tokens.append((Token.Value, ', '.join(note.tags) + '\n')) tokens.append((Token.Attribute, '{:>20}'.format('number of links: '))) tokens.append((Token.Value, str(len(note.links)) + '\n')) tokens.append((Token.Attribute, '{:>20}'.format('filepath: '))) tokens.append((Token.Value, note.filepath + '\n')) tokens.append((Token.Attribute, '{:>20}'.format('identifier: '))) tokens.append((Token.Value, note.identifier + '\n')) print_tokens(tokens, style=self.color_style)
def print_tag_listing(self, sort_by_count=False): tags = self.count_tags() if not tags: return None max_len = max(len(t) for t in tags) # print() if sort_by_count: items = sorted(tags.items(), key=lambda x: x[1]) else: items = sorted(tags.items(), key=lambda x: x[0].lower()) for tag, count in items: tokens = [] # tokens.append((Token.Tag, (' {:<}').format(tag))) tokens.append((Token.Tag, ('{:<' + str(max_len + 2) + '}').format(tag))) tokens.append((Token, '{:<3} '.format(count))) print_tokens(tokens, style=self.color_style) print() print('\ntotal:', len(tags))
def show_block(self, args): item = get_arg(args) txarg = get_arg(args, 1) if item is not None: block = Blockchain.Default().GetBlock(item) if block is not None: bjson = json.dumps(block.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') if txarg and 'tx' in txarg: for tx in block.FullTransactions: print(json.dumps(tx.ToJson(), indent=4)) else: print("Could not locate block %s" % item) else: print("please specify a block")
def show_state(self): height = Blockchain.Default().Height headers = Blockchain.Default().HeaderHeight diff = height - self.start_height now = datetime.datetime.utcnow() difftime = now - self.start_dt mins = difftime / datetime.timedelta(minutes=1) bpm = 0 if diff > 0 and mins > 0: bpm = diff / mins out = 'Progress: %s / %s\n' % (height, headers) out += 'Block Cache length %s\n' % Blockchain.Default().BlockCacheCount out += 'Blocks since program start %s\n' % diff out += 'Time elapsed %s mins\n' % mins out += 'blocks per min %s \n' % bpm # out += "Node Req Part, Max: %s %s\n" % (self.node_leader.BREQPART, self.node_leader.BREQMAX) # out += "DB Cache Lim, Miss Lim %s %s\n" % (Blockchain.Default().CACHELIM, Blockchain.Default().CMISSLIM) tokens = [(Token.Number, out)] print_tokens(tokens, self.token_style)
def do(self, comm): from prompt_toolkit.shortcuts import print_tokens from prompt_toolkit.styles import style_from_dict from pygments.token import Token from time import sleep print " <Ctrl+C> to break SendLoop({}s).".format( str(self.iteration_seconds)) try: while True: comm.send(self.telecommand) print_tokens([ (Token.Msg, self.ITERATION_INDICATOR), ], style=style_from_dict({Token.Msg: 'reverse'})) sleep_step = 0 while sleep_step < self.iteration_seconds: sleep_step += self.SLEEP_STEP sleep(self.SLEEP_STEP) except KeyboardInterrupt: print '' pass
def run(tasks): """ Performs list of tasks. Each task is defined as list: [<telecommand object>, Send|SendReceive, "Wait|NoWait"] When using "Wait" it is necessary to type 'n<ENTER>' to continue running tasks """ import pprint from prompt_toolkit.shortcuts import print_tokens from prompt_toolkit.styles import style_from_dict from pygments.token import Token style = style_from_dict({ Token.Timestamp: '#fdf6e3', Token.CurrentStep: '#b58900', Token.TotalSteps: '#6c71c4', Token.Action: '#dc322f', Token.Telecommand: '#268bd2', }) step_no = 0 for [telecommand, action_type, wait] in tasks: step_no += 1 tokens = [ (Token.String, "["), (Token.Timestamp, datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')), (Token.String, "] "), (Token.String, "Step "), (Token.CurrentStep, str(step_no)), (Token.String, "/"), (Token.TotalSteps, str(len(tasks))), (Token.String, ": "), (Token.Action, action_type.__name__), (Token.String, "("), (Token.Telecommand, pprint.pformat(telecommand)), (Token.String, ")... ") ] print_tokens(tokens, style=style) action_type(telecommand).do(__import__(__name__)) if wait is "NoWait": print_tokens([(Token.String, "Done"), (Token.String, "\n")], style=style) else: print_tokens( [(Token.String, "Wait (type 'n' and press <Enter>)")], style=style) user = "" while user[:1] != "n": user = raw_input()
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) # Blockchain.Default().PersistBlocks() tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, '\'help\' '), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print('\n') while self.go_on: try: result = prompt("neo> ", completer=self.get_completer(), history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style, refresh_interval=3 ) except EOFError: # Control-D pressed: quit return self.quit() except KeyboardInterrupt: # Control-C pressed: do nothing continue try: command, arguments = self.input_parser.parse_input(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'build': self.do_build(arguments) elif command == 'load_run': self.do_load_n_run(arguments) elif command == 'import': self.do_import(arguments) elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': self.do_send(arguments) elif command == 'sign': self.do_sign(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'testinvoke': self.test_invoke_contract(arguments) elif command == 'withdraw_request': self.make_withdraw_request(arguments) elif command == 'withdraw': self.do_withdraw(arguments) elif command == 'notifications': self.do_notifications(arguments) elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'debugstorage': self.handle_debug_storage(arguments) elif command == 'config': self.configure(arguments) elif command is None: print("Please specify a command") else: print("Command %s not found" % command) except Exception as e: print("Could not execute command: %s" % e) traceback.print_stack() traceback.print_exc()
def run(tasks, start_from=1): """ Performs list of tasks. Each task is defined as list: [<arg>, Send|SendReceive|Sleep|Print, WaitMode.Wait|WaitMode.NoWait] For Send <arg> is a telecommand object For SendReceive <arg> is a telecommand object For Sleep <arg> is time in seconds For Print <arg> is text to display When using "Wait" it is necessary to type 'n<ENTER>' to continue running tasks """ style = style_from_dict({ Token.Timestamp: '#fdf6e3', Token.CurrentStep: '#b58900', Token.TotalSteps: '#6c71c4', Token.Action: '#dc322f', Token.Telecommand: '#268bd2', }) ns_wrapper = DictWrapper(ns) monitor_connector.connect() step_no = start_from - 1 try: while step_no < len(tasks) and step_no >= 0: [telecommand, action_type, wait] = tasks[step_no] tokens = [(Token.String, "["), (Token.Timestamp, datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')), (Token.String, "] "), (Token.String, "Step "), (Token.CurrentStep, str(step_no + 1)), (Token.String, "/"), (Token.TotalSteps, str(len(tasks))), (Token.String, ": "), (Token.Action, action_type.__name__), (Token.String, "("), (Token.Telecommand, pprint.pformat(telecommand)), (Token.String, ")... ")] print_tokens(tokens, style=style) def write_end(): sys.stdout.write("[X] ") sys.stdout.flush() timer_WriteProgramPart = Timer(7, write_end) if isinstance(telecommand, tc.WriteProgramPart): timer_WriteProgramPart.start() action_type(telecommand).do(ns_wrapper) if wait is WaitMode.NoWait: print_tokens([(Token.String, "Done"), (Token.String, "\n")], style=style) else: print_tokens([(Token.String, "Wait ")], style=style) while True: user_input = custom_raw_input() timer_WriteProgramPart.cancel() if user_input == 'n': break elif user_input == 'r': step_no -= 1 break elif user_input == 'p': step_no -= 2 break elif user_input[:1] >= '0' and user_input[:1] <= '9': user_step_no = -1 try: user_step_no = int(user_input) except ValueError: pass if user_step_no > -1: step_no = user_step_no - 2 break elif user_input == 'b': send_additional_beacon(style, ns_wrapper) continue elif user_input == 'm': get_and_send_missing_chunks_command( style, ns_wrapper, tasks[step_no][0], monitor_connector) continue elif user_input == 't': add_missings_to_tasklist(style, ns_wrapper, tasks, monitor_connector) continue elif user_input == 'q': return print_tokens([ (Token.Action, "Unknown command '{}'. ".format(user_input)), (Token.String, "Please repeat: "), ], style=style) step_no += 1 except KeyboardInterrupt: print_tokens([(Token.String, "\n"), (Token.Action, "Aborted."), (Token.String, "\n")], style=style) pass
def display_note(self, notepath): os.system('clear') tokens = self.tokenize(notepath) print_tokens(tokens, style=self.color_style)
def print_tokens(self, tokens): self._cli.run_in_terminal(lambda: print_tokens( tokens + [(Token, '\n')], style=self._style, true_color=True))
def printer(): print_tokens(tokens, style=style)
def test_print_tokens(): f = _Capture() print_tokens([(Token, 'hello'), (Token, 'world')], file=f) assert b'hello' in f.data assert b'world' in f.data
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, '\'help\' '), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print('\n') while self.go_on: try: result = prompt( "neo> ", completer=self.get_completer(), history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style, refresh_interval=3) except EOFError: # Control-D pressed: quit return self.quit() except KeyboardInterrupt: # Control-C pressed: do nothing continue try: command, arguments = self.input_parser.parse_input(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'build': self.do_build(arguments) elif command == 'load_run': self.do_load_n_run(arguments) elif command == 'import': self.do_import(arguments) elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': self.do_send(arguments) elif command == 'sign': self.do_sign(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'testinvoke': self.test_invoke_contract(arguments) elif command == 'withdraw_request': self.make_withdraw_request(arguments) elif command == 'withdraw': self.do_withdraw(arguments) elif command == 'notifications': self.do_notifications(arguments) elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'debugstorage': self.handle_debug_storage(arguments) elif command == 'config': self.configure(arguments) elif command is None: print("Please specify a command") else: print("Command %s not found" % command) except Exception as e: print("Could not execute command: %s" % e) traceback.print_stack() traceback.print_exc()
def WARNING_(message): screen_lock.acquire() print_tokens(WARNING, style=style), print(message + '\n') screen_lock.release()
from prompt_toolkit.shortcuts import print_tokens from prompt_toolkit.styles import style_from_dict from pygments.token import Token # Create a stylesheet. style = style_from_dict({ Token.Hello: '#ff0066', Token.World: '#44ff44 italic', }) # Make a list of (Token, text) tuples. tokens = [ (Token.Hello, 'Hello '), (Token.World, 'World'), (Token, '\n'), ] # Print the result. print_tokens(tokens, style=style)
def GETPOST(proxy, command, message, submessage): screen_lock.acquire() print_tokens((message_request(proxy, command, message, submessage)), style=style) screen_lock.release()
def COMMAND_(): print_tokens(COMMAND, style=style) return ": "
def USAGE_(proxy_Source, proxy_destination): screen_lock.acquire() print_tokens((USAGE_SET(proxy_Source, proxy_destination)), style=style) screen_lock.release()
def show_mem(self): total = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss totalmb = total / 1000000 out = "Total: %s MB\n" % totalmb out += "total buffers %s\n" % StreamManager.TotalBuffers() print_tokens([(Token.Number, out)], self.token_style)
def print_subdued(txt, nl=1): print_tokens([(Token.Subdued, txt + ('\n' * nl))], style=style)
def main(): style = style_from_dict({ Token.Title: 'underline', Token.Black: '#ansiblack', Token.White: '#ansiwhite', Token.Red: '#ansired', Token.Green: '#ansigreen', Token.Yellow: '#ansiyellow', Token.Blue: '#ansiblue', Token.Fuchsia: '#ansifuchsia', Token.Turquoise: '#ansiturquoise', Token.LightGray: '#ansilightgray', Token.DarkGray: '#ansidarkgray', Token.DarkRed: '#ansidarkred', Token.DarkGreen: '#ansidarkgreen', Token.Brown: '#ansibrown', Token.DarkBlue: '#ansidarkblue', Token.Purple: '#ansipurple', Token.Teal: '#ansiteal', Token.BgBlack: 'bg:#ansiblack', Token.BgWhite: 'bg:#ansiwhite', Token.BgRed: 'bg:#ansired', Token.BgGreen: 'bg:#ansigreen', Token.BgYellow: 'bg:#ansiyellow', Token.BgBlue: 'bg:#ansiblue', Token.BgFuchsia: 'bg:#ansifuchsia', Token.BgTurquoise: 'bg:#ansiturquoise', Token.BgLightGray: 'bg:#ansilightgray', Token.BgDarkGray: 'bg:#ansidarkgray', Token.BgDarkRed: 'bg:#ansidarkred', Token.BgDarkGreen: 'bg:#ansidarkgreen', Token.BgBrown: 'bg:#ansibrown', Token.BgDarkBlue: 'bg:#ansidarkblue', Token.BgPurple: 'bg:#ansipurple', Token.BgTeal: 'bg:#ansiteal', }) tokens = [ (Token.Title, 'Foreground colors'), (Token, '\n'), (Token.Black, '#ansiblack'), (Token, '\n'), (Token.White, '#ansiwhite'), (Token, '\n'), (Token.Red, '#ansired'), (Token, '\n'), (Token.Green, '#ansigreen'), (Token, '\n'), (Token.Yellow, '#ansiyellow'), (Token, '\n'), (Token.Blue, '#ansiblue'), (Token, '\n'), (Token.Fuchsia, '#ansifuchsia'), (Token, '\n'), (Token.Turquoise, '#ansiturquoise'), (Token, '\n'), (Token.LightGray, '#ansilightgray'), (Token, '\n'), (Token.DarkGray, '#ansidarkgray'), (Token, '\n'), (Token.DarkRed, '#ansidarkred'), (Token, '\n'), (Token.DarkGreen, '#ansidarkgreen'), (Token, '\n'), (Token.Brown, '#ansibrown'), (Token, '\n'), (Token.DarkBlue, '#ansidarkblue'), (Token, '\n'), (Token.Purple, '#ansipurple'), (Token, '\n'), (Token.Teal, '#ansiteal'), (Token, '\n'), (Token.Title, 'Background colors'), (Token, '\n'), (Token.BgBlack, '#ansiblack'), (Token, '\n'), (Token.BgWhite, '#ansiwhite'), (Token, '\n'), (Token.BgRed, '#ansired'), (Token, '\n'), (Token.BgGreen, '#ansigreen'), (Token, '\n'), (Token.BgYellow, '#ansiyellow'), (Token, '\n'), (Token.BgBlue, '#ansiblue'), (Token, '\n'), (Token.BgFuchsia, '#ansifuchsia'), (Token, '\n'), (Token.BgTurquoise, '#ansiturquoise'), (Token, '\n'), (Token.BgLightGray, '#ansilightgray'), (Token, '\n'), (Token.BgDarkGray, '#ansidarkgray'), (Token, '\n'), (Token.BgDarkRed, '#ansidarkred'), (Token, '\n'), (Token.BgDarkGreen, '#ansidarkgreen'), (Token, '\n'), (Token.BgBrown, '#ansibrown'), (Token, '\n'), (Token.BgDarkBlue, '#ansidarkblue'), (Token, '\n'), (Token.BgPurple, '#ansipurple'), (Token, '\n'), (Token.BgTeal, '#ansiteal'), (Token, '\n'), (Token, '\n'), ] print_tokens(tokens, style=style)
def print_accent(txt, nl=1): print_tokens([(Token.Accent, txt + ('\n' * nl))], style=style)
def help(self): tokens = [] for c in self.commands: tokens.append((Token.Command, "%s\n" % c)) print_tokens(tokens, self.token_style)
def print_loud(txt, nl=1): print_tokens([(Token.Loud, txt + ('\n' * nl))], style=style)
def print_file_with_style(filename): file_ending_tokens = {'cpp': Token.Cpp, 'o': Token.Object} file_ending = filename.split('.')[1] print_tokens([(file_ending_tokens.get( file_ending, Token.Default), ' - ' + filename + '\n')], style=style)
def _text_fn(): if text: print_tokens([(Token.Label, text + '\n')], style=style)
from prompt_toolkit.token import Token from prompt_toolkit.shortcuts import print_tokens example_style = style_from_dict({ Token.RPrompt: 'bg:#ff0066 #ffffff', Token.Toolbar: '#ffffff bg:#333333', }) tokens = [ (Token.RPrompt, 'How about writing something long'), (Token.Toolbar, ' Working'), ] def getValues(): return "Something for Testing purpose" def get_rprompt_tokens(cli): return [ (Token.RPrompt, u'How about writing something long'), ] def get_bottom_toolbar_tokens(cli): msg = getValues() return [(Token.Toolbar, msg.encode("UTF_8"))] print_tokens(tokens, style=example_style) """answer = prompt( get_rprompt_tokens=get_rprompt_tokens,get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=example_style)"""
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() while Blockchain.Default().Height < 2: print("Waiting for prompt to sync...") time.sleep(1) tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, '\'help\' '), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print('\n') timebase = time.time() while self.go_on: try: if len(self.mycommands) > 0: timenow = time.time() if timenow - timebase > 2: #wait 2 seconds TODO NeoCompiler.IO - This trick still seems to be necessary in order to wait for sync timebase = timenow result = self.mycommands.pop() else: time.sleep(0.3) # slow refresh continue else: result = prompt( "neo> ", completer=self.get_completer(), history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style, refresh_interval=3) except EOFError: # Control-D pressed: quit return self.quit() except KeyboardInterrupt: # Control-C pressed: do nothing continue try: command, arguments = self.parse_result( result) #TODO NeoCompiler parse_result function if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': time.sleep( 2) # TODO NeoCompiler.io - -consolidate chain self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'build': self.do_build(arguments) elif command == 'load_run': self.do_load_n_run(arguments) elif command == 'import': tx = self.do_import(arguments) # TODO Wait until transaction is on blockchain -- BEGINS if tx is not None: print( "\nDeploy has been completed with relayed TX %s" % tx.Hash.ToString()) print( "\nCheck the progress at the NeoCompiler NeoScan-Privanet.\nIn same few unexpected cases, transactions are not being relayed. Possible due to multiple uses of the same wallet.\n" ) #if tx is not None: # self.wait_for_tx(tx) # TODO Wait until transaction is on blockchain -- ENDS elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': tx = self.do_send(arguments) if tx is not None: if tx is not False: self.wait_for_tx(tx) elif command == 'sign': self.do_sign(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'testinvoke': tx = self.test_invoke_contract(arguments) # TODO Wait until transaction is on blockchain -- BEGINS if tx is not None: print( "\nTestinvoke has been completed with relayed TX %s" % tx.Hash.ToString()) print( "\nCheck the progress at the NeoCompiler NeoScan-Privanet.\nIn same few unexpected cases, transactions are not being relayed. Possible due to multiple uses of the same wallet.\n" ) # Wait until transaction is on blockchain #if tx is not None: # self.wait_for_tx(tx) # TODO Wait until transaction is on blockchain -- ENDS elif command == 'testinvokeonly': self.test_invoke_contract( arguments, True) # TODO NeoCompiler.io invokeonly elif command == 'withdraw_request': self.make_withdraw_request(arguments) elif command == 'withdraw': self.do_withdraw(arguments) elif command == 'notifications': self.do_notifications(arguments) elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'debugstorage': self.handle_debug_storage(arguments) elif command == 'config': self.configure(arguments) elif command is None: print("Please specify a command") else: print("Command %s not found" % command) except Exception as e: print("Could not execute command: %s" % e) traceback.print_stack() traceback.print_exc()
def display_note2(self, notepath): """ Display the content of a note on the terminal. Using a bit of syntax here for highlighting: - if a line begins with "$:" or ends with ":$", the whole line is highlighted - if a line begins with "@:", the line is interpreted as a link to a reference - if a line begins with "http://" or "https://", the whole line is interpreted as a url - if a line begins with "#:", it is interpreted as a tag line - if a line contains text between two occurrences of ":::" (or whatever is defined a highlight_marker), that part is highlighted. If the line has an odd number of ":::", then the last remaining part of the line is highlighted. """ with open(notepath, 'rt') as f: self.link_listing = {} note = parse_note(notepath) # title has been stripped, so we have to add a newline character # below. print_tokens([(Token.Title, note.title + '\n')], style=self.color_style) # # Make the body ends with a newline, if the body is nonempty: # if note.body and note.body[-1] != '\n': # note.body += '\n' lines = note.body.split('\n') line_num = 0 while line_num < len(lines): line = lines[line_num] # Is the line a link to a reference? if line.startswith('@:'): ref = line[2:].strip() index = len(self.link_listing) + 1 # NOTE: an extra newline is inserted below because it was # stripped above print_tokens([(Token.Link, str(index) + ' ' + ref + '\n')], style=self.color_style) self.link_listing.append(os.path.join(self.refs, ref)) line_num += 1 continue # Is the line a link to a webpage? if line.startswith('http://') or line.startswith('https://'): url = line.strip() index = len(self.link_listing) + 1 # NOTE: an extra newline is inserted below because it was # stripped above print_tokens([(Token.Link, str(index) + ' ' + url + '\n')], style=self.color_style) self.link_listing.append(url) line_num += 1 continue # Does the line indicate a highlighted block? for i, marker in enumerate(self.highlight_markers): if line == marker: if i == 0: token_type = Token.HL1 elif i == 1: token_type = Token.HL2 else: # i == 2 token_type = Token.HL3 line_num += 1 while line_num < len(lines) and lines[line_num] != marker: print_tokens([(token_type, lines[line_num] + '\n')], style=self.color_style) line_num += 1 # line_num += 1 continue # If neither of the above hold, the line is a regular line. i = 0 marker_0_width = len(self.highlight_markers[0]) marker_1_width = len(self.highlight_markers[1]) while i < len(line): if line[i:].startswith(self.highlight_markers[0]): j = line[i + marker_0_width:].find(self.highlight_markers[0]) if j > -1: print_tokens([(Token.Blue, line[i + marker_0_width: i + marker_0_width + j])], style=self.color_style) i = i + marker_0_width + j + marker_0_width else: print_tokens([(Token.Blue, line[i + marker_0_width:])], style=self.color_style) break elif line[i:].startswith(self.highlight_markers[1]): j = line[i + marker_1_width:].find(self.highlight_markers[1]) if j > -1: print_tokens([(Token.Yellow, line[i + marker_1_width: i + marker_1_width + j])], style=self.color_style) i = i + marker_1_width + j + marker_1_width else: print_tokens([(Token.Yellow, line[i + marker_1_width:])], style=self.color_style) break else: print_tokens([(Token, line[i])], style=self.color_style) i += 1 # Add the newline that was lost when splitting the body on # \n. line_num += 1 print() if note.tags: print_tokens([(Token.Tag, ', '.join(note.tags) + '\n')], style=self.color_style)
Token.Prompt: '#00ff00', Token.Continuation: '#00ff00', Token.String: '#00ff00' } get_style = lambda _name='native': PygmentsStyle.from_defaults( style_dict=_style, pygments_style_cls=pygments.styles.get_style_by_name(_name)) _o_style = style_from_dict({ Token.OutPrompt: '#9988ff', Token.String: '#ffffff' }) rprint = lambda buff: lambda text:\ print_tokens(zip(itertools.cycle([Token.OutPrompt, Token.String]), ['Out[%d]: ' % buff.return_count, text, '\n\n']), style=_o_style) #cli class RCLI(object): def __init__(self): self.event_loop = create_eventloop() self.cli = None def __enter__(self): self.cli = self._build_cli() if self.cli: return self.cli else: raise ValueError('Need to build CLI instance')
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() self.node_leader = NodeLeader.Instance() tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, "'help' "), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print("\n") while self.go_on: result = prompt("neo> ", completer=self.completer, history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style) command, arguments = self.parse_result(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': self.quit() elif command == 'help': self.help() elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'sc': self.show_spent_coins(arguments) elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'config': self.configure(arguments) elif command == 'pause' or command == 'unpause' or command == 'resume': self.toggle_pause() elif command == None: print('please specify a command') else: print("command %s not found" % command) else: pass
def _helper(msg): tokens = [('fg:' + col, msg)] print_tokens(tokens)
# Create a stylesheet. style = style_from_dict({ Token.Hello: '#ff0066', Token.World: '#44ff44 bold', }) # Make a list of (Token, text) tuples. tokens = [ (Token.Hello, 'Prediksi Keuntungan Toko '), (Token.World, 'BigMart'), (Token, '\n'), ] # Print the result. print("") print_tokens(tokens, style=style) print("\n") for feature in features[0:-1]: isi = category[feature] prompt_number(isi, feature) input_query = [ "python", "runner_cart.py", str(query['Item_Weight']), str(query['Item_Visibility']), str(query['Item_MRP']), str(query['Outlet_Establishment_Year']), ] tokens_done = [
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() while Blockchain.Default().Height < 2: print("Waiting for prompt to sync...") time.sleep(1) tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, "'help' "), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print("\n") timebase = time.time() while self.go_on: try: if len(self.mycommands) > 0: timenow = time.time() if timenow - timebase > 3: #wait 3 seconds timebase = timenow result = self.mycommands.pop() else: time.sleep(0.5) # slow refresh continue #time.sleep(3) else: result = prompt( "neo> ", completer=self.get_completer(), history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style, refresh_interval=3) # Control-D pressed: quit #print("result=",result) #print("mycommands ->", self.mycommands) except EOFError: return self.quit() except KeyboardInterrupt: # Control-C pressed: do nothing continue try: command, arguments = self.parse_result(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': time.sleep(2) # consolidate chain self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'build': self.do_build(arguments) elif command == 'load_run': self.do_load_n_run(arguments) elif command == 'import': tx = self.do_import(arguments) # Wait until transaction is on blockchain if tx is not None: self.wait_for_tx(tx) elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': tx = self.do_send(arguments) if tx is not None: if tx is not 0: self.wait_for_tx(tx) elif command == 'sign': self.do_sign(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': tx = self.show_contract_state(arguments) elif command == 'testinvoke': tx = self.test_invoke_contract(arguments) # Wait until transaction is on blockchain if tx is not None: self.wait_for_tx(tx) elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'debugstorage': self.handle_debug_storage(arguments) elif command == 'config': self.configure(arguments) elif command is None: print('please specify a command') else: print("command %s not found" % command) except Exception as e: print("could not execute command: %s " % e) traceback.print_stack() traceback.print_exc()
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, "'help' "), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print("\n") while self.go_on: if self._gathered_passwords and len( self._gathered_passwords) == self._num_passwords_req: self._gathering_password = False self._gather_password_action() if self._gathering_password: result = prompt("password> ", is_password=True) else: result = prompt( "neo> ", completer=self.completer, history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style) if self._gathering_password: self._gathered_passwords.append(result) else: try: command, arguments = self.parse_result(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'import': self.do_import(arguments) elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': self.do_send(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'invoke': self.invoke_contract(arguments) elif command == 'testinvoke': self.test_invoke_contract(arguments) elif command == 'cancel': self.cancel_operations() elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'config': self.configure(arguments) elif command == None: print('please specify a command') else: print("command %s not found" % command) except Exception as e: print("could not execute command: %s " % e) traceback.print_stack() traceback.print_exc()