def do_loop(self): history = InMemoryHistory() gh_completer_client = WordCompleter([ 'execute', 'put', 'checkissues', 'viewissue', 'rtm', 'clear', 'viewhooks' ], ignore_case=True, match_middle=True) gh_completer_server = WordCompleter(['clear', 'viewhooks'], ignore_case=True, match_middle=True) while True: result = None if self.role_server: try: result = prompt( completer=gh_completer_server, style=ServerStyle, vi_mode=True, enable_history_search=True, reserve_space_for_menu=4, complete_while_typing=True, display_completions_in_columns=True, wrap_lines=True, get_prompt_tokens=self._get_prompt_tokens, get_rprompt_tokens=self._get_rprompt_tokens, get_bottom_toolbar_tokens=self. _get_bottom_toolbar_tokens, enable_system_bindings=True, get_title=self._get_title, history=history, auto_suggest=AutoSuggestFromHistory(), patch_stdout=True) except KeyboardInterrupt: logging.warning("^D to exit") except EOFError: return if self.role_client: try: result = prompt( completer=gh_completer_client, style=ClientStyle, vi_mode=True, enable_history_search=True, reserve_space_for_menu=4, complete_while_typing=True, display_completions_in_columns=True, get_rprompt_tokens=self._get_rprompt_tokens, wrap_lines=True, get_prompt_tokens=self._get_prompt_tokens, get_bottom_toolbar_tokens=self. _get_bottom_toolbar_tokens, enable_system_bindings=True, get_title=self._get_title, history=history, auto_suggest=AutoSuggestFromHistory(), patch_stdout=True) except KeyboardInterrupt: logging.warning("^D to exit") except EOFError: return if not result: pass else: cmdargs = "" tokens = result.split(' ') if len(tokens) > 0: cmd = tokens[0] # get command logging.debug("cmd:[{}]".format(cmd)) if cmd == 'clear': clear() elif cmd == 'help': print(""" System: Alt-! Exit: Ctlr-D Skip: Ctrl-C Search: Vi mode standard """) elif cmd == 'viewhooks': self.do_viewHooks() elif cmd == 'execute': cmdargs = result.split(' ', 1) # get arguments if len(cmdargs) > 1: # Args exist logging.debug("Cmdargs:") logging.debug(cmdargs) self.do_execute(cmdargs[1]) else: print("Execute: Mising command arguments") logging.error("Execute: Missing command arguments") elif cmd == 'rtm': if len(tokens) == 2: comm = tokens[1] self.do_rtm(comm) else: print("RTM: Mising command arguments: <on|off>") logging.warning( "RTM: Mising command arguments: <on|off>") elif cmd == 'put': cmdargs = result.split(' ', 1) # get arguments if len(cmdargs) > 0: # Args exist logging.debug("Cmdargs:") logging.debug(cmdargs) self.do_put(cmdargs[1]) else: print("PUT: Missing command arguments") logging.error("PUT: Missing command arguments") elif cmd == 'checkissues': top = 5 # top issue to display states for ghlib.checkIssueStates(self.git_repo, self.agentid, top) elif cmd == 'viewissue': if len(tokens) == 2: issue_number = tokens[1] comments_contents = ghlib.getClosedIssueComments( self.git_repo, issue_number) for x in comments_contents: print(x) else: print("ViewIssue: Need Issue number ") logging.warning("ViewIssue: Need Issue number ") else: print("Unsupported Command") logging.warning("Unsupported Command") else: print("Invalid Command") logging.warning("Invalid Command")
matches = re.findall('[_a-zA-Z0-9\.]+\(', result[:cli.current_buffer.cursor_position]) final = 'None' if matches: match = matches[-1][:-1] final = match if match in globals().keys(): final = match if hasattr(globals()[match], '__doc__'): final = pydoc.render_doc(globals()[match]).split('\n')[2] return [(Token.Toolbar, final)] def title(): return 'MPrompt' style = style_from_dict({Token.Toolbar: '#ffffff bg:#333333',}) myCompleter = WordCompleter(list(mPrompt.locals.keys())+list(mPrompt.locals.get('__builtins__', {}).keys())) while True: text = prompt('PY> ', lexer=PygmentsLexer(PythonLexer), history=history, get_bottom_toolbar_tokens=toolbar_tokens, completer=myCompleter) if text.startswith('!'): print(f'[CMD] {text}') elif text.startswith('?'): mPrompt.push(f'help({text[1:]})') else: mPrompt.push(text)
["a", "Scrape all items (time intensive), apply regression and dump"], "readcsv": ["r", "Read CSV for user inputs to be persisted, check for gone items"], "regression": [ "g", "Apply regression analysis to the vehicles. " + "\n" + "If possible, the price of the vehicle is predicted. The difference between predicted and asked price " + " should help to identified underestimated vehicles." ], "dump": ["d", "Dump found items to CSV according to search pattern"], "help": ["h", "Print help for commands and legend for output"], "quit": ["q", "Quit the programm"], } commandsShort = {} CommandsCompleter = WordCompleter([], ignore_case=True) for key in commands: commandsShort[commands[key][0]] = key CommandsCompleter.words.append(key) while 1: user_input = prompt( '> ', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=CommandsCompleter, ) if user_input in commands: locals()[user_input]() elif user_input in commandsShort:
#from jinja2 import Environment, FileSystemLoader import settings from settings import author from datetime import date import stat from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.contrib.completers import WordCompleter from fuzzyfinder import fuzzyfinder from win32com.client import Dispatch import winshell base_completer = WordCompleter([ ':create', ':delete', ':clone', ':context', ':parent', ':relation', ':list' ]) botype_completer = WordCompleter([':databot', ':metabot']) BOTKeywords = [ 'create', 'delete', 'add', 'remove', 'context', 'relation', 'reset' ] dirs = [ 'awareness/global/contextual', 'awareness/global/temporal', 'awareness/global/relational/children', 'awareness/global/relational/siblings', 'awareness/global/relational/parents', 'docs/en/about', 'docs/en/commands',
try: hostname = sys.argv[1] except IndexError: print "please supply a hostname" exit(1) if "@" in hostname: username, hostname = hostname.split("@") username = username or None try: connection = FTPBackend(hostname, username, '') except AuthenticationException: password = prompt('password: '******'' completer = WordCompleter(connection.parse('listdir')) if username: prmt = '{}@'.format(username) else: prmt = '' prmt += '{}:{}$ '.format(hostname, connection.parse('pwd')) text = prompt(prmt, history=history, completer=completer, complete_while_typing=False) ret = connection.parse(text) if ret: print ret
from prompt_toolkit import AbortAction, prompt from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.history import InMemoryHistory from pygments.style import Style from pygments.styles.default import DefaultStyle from pygments.token import Token import os import urllib3 from tabulate import tabulate import json from pygments.lexers.sql import SqlLexer sql_completer = WordCompleter([ 'create', 'select', 'insert', 'drop', 'delete', 'from', 'where', 'table', 'bulk', 'update', 'limit', 'group', 'by', 'index.number_of_shards', 'index.number_of_replicas', 'index.flush_inteval', 'moving_avg', 'date_range', 'date_histogram' ], ignore_case=True) def do_esql(database, statement): url = database.host.rstrip() + database.url http = urllib3.PoolManager() try: res = http.request('POST', url, fields={"sql": statement}) except Exception as e: print(str(e)) return if res.status != 200: print(res.data.decode('utf-8'))
def main(group_id, location, time_boundary, event_status, pandoc, force): key_path = os.path.normpath(os.path.expanduser('~/.meetup.com-key')) if os.path.exists(key_path): with io.open(key_path, encoding='utf8') as fh: key = fh.read().strip() else: key = None cache = FileCache('.web_cache', forever=True) requests = CacheControl(Session(), cache, cache_etags=False, heuristic=ExpiresAfter(days=1)) while True: resp = requests.get('https://api.meetup.com/status', params=dict(key=key)) if resp.status_code == 200 and resp.json().get('status') == 'ok': break elif resp.status_code == 200 and any( 'auth_fail' == e.code for e in resp.json().get('errors', [])): click.echo( 'Your meetup.com key is required. You can get it from https://secure.meetup.com/meetup_api/key/\n' ) if click.confirm( 'Open https://secure.meetup.com/meetup_api/key/ in your web browser?' ): click.launch('https://secure.meetup.com/meetup_api/key/') click.echo('') key = click.prompt('Key', hide_input=True) else: raise click.ClickException( 'Failed to get meetup.com status. Response was {!r} {!r}'. format(resp.status_code, resp.text)) click.secho( 'For convenience your key is saved in `{}`.\n'.format(key_path), fg='magenta') with open(key_path, 'w') as fh: fh.write(key) while not location: location = location or get_input( u'Location: ', completer=WordCompleter( [u'cluj', u'iasi', u'timisoara', u'bucuresti'], ignore_case=True)) while True: group_id = group_id or get_input( u'Group ID: ', completer=WordCompleter([ u'RoPython-Bucuresti', u'RoPython-Cluj', u'RoPython_Iasi', u'RoPython-Timisoara' ], ignore_case=True)) resp = requests.get('https://api.meetup.com/2/events', params=dict( key=key, group_urlname=group_id, time=time_boundary, status=event_status, )) if resp.status_code == 200: json = resp.json() if json['results']: break else: click.secho( 'Invalid group `{}`. It has no events!'.format(group_id), fg='red') group_id = None if resp.status_code == '400': click.fail( 'Failed to get make correct request. Response was {!r}'.format( resp.text)) else: click.secho('Invalid group `{}`. Response was [{}] {!r}'.format( group_id, resp.status_code, resp.text), fg='red') # click.echo(pformat(dict(resp.headers))) for event in json['results']: dt = datetime.fromtimestamp(event['time'] / 1000) event['duration'] = format_duration( event.get('duration', 3600000) / 1000) event['time'] = dt.strftime('%Y-%m-%d %H:%M') if 'how_to_find_us' in event: address = event['how_to_find_us'], else: address = () if 'venue' in event: address_1 = event['venue'].get('address_1') if address_1: address += address_1, event['venue']['address_1'] = ', '.join(address) else: event['venue'] = {'address_1': address} click.echo("{time}: {name}".format(**event)) click.echo("\t{}".format(pformat(event))) existing_path = glob( os.path.join('content', '*', dt.strftime('%Y-%m-%d*'), 'index.rst')) if existing_path and not force: if len(existing_path) > 1: click.secho('\tERROR: multiple paths matched: {}'.format( existing_path)) else: click.secho('\t`{}` already exists. Not importing.'.format( *existing_path), fg='yellow') else: target_dir = os.path.join( 'content', location, '{}-{}'.format(dt.strftime('%Y-%m-%d'), slugify(event['name']))) target_path = os.path.join(target_dir, 'index.rst') if not os.path.exists(target_dir): os.makedirs(target_dir) if pandoc: with tempfile.NamedTemporaryFile(delete=False) as fh: fh.write(event['description'].encode('utf-8')) rst = subprocess.check_output( ['pandoc', '--from=html', '--to=rst', fh.name]).decode('utf-8') os.unlink(fh.name) else: rst = html2rest(event['description']) doc = u'''{name} ############################################################### :tags: prezentari :registration: meetup.com: {event_url} :start: {time} :duration: {duration} :location: {venue[address_1]}, {venue[city]}, {venue[localized_country_name]} {rst}'''.format(rst=rst, **event) with io.open(target_path, 'w', encoding='utf-8') as fh: fh.write(doc) click.secho('\tWrote `{}`.'.format(target_path), fg='green')
def interactive(): print color.G + "\n\nWelcome to interactive mode!\n\n" task_home_dir = os.path.join(os.path.dirname(__file__), "task") while True: # print already existed task tasks = os.listdir(task_home_dir) for task in tasks: if os.path.isfile(task): tasks.remove(task) print "{0}[{1}]{2} tasks existed:".format(color.R, len(tasks), color.G) for item in tasks: print item print( color.Y + "\n\n" "*.Input a existed task name to operate it or Input a new task name to create.\n" "*.Input q to query vuln from wvs.\n" "*.Input x to exit Ashe.\n" "\n" + color.W) task_completer = WordCompleter(tasks, ignore_case=True) task_name = prompt(u"==>", completer=task_completer) if task_name.lower() == "q": #QueryFromWVS() pass elif task_name.lower() in ['x', 'back']: break elif task_name == "": continue else: task_dir = os.path.join(task_home_dir, task_name) if os.path.isdir(task_dir): choice = prompt( u"the task already exist, operate this task? (Y/n)", ) if choice.lower() not in ["y", "yes", ""]: continue else: os.mkdir(task_dir) print "task {0} created, chose what to do:".format(task_name) urls_file = os.path.join(task_dir, "{0}_urls_by_ashe.txt".format(task_name)) urls_scanned_file = os.path.join( task_dir, "{0}_urls_scanned_by_ashe.txt".format(task_name)) while True: index = taskDealIndex.format(task_name) choice = prompt(unicode(index)) if choice == "1": delete = prompt(u"Are you sure to DELETE this task?(y/N)") if delete.lower() in ["y", "yes"]: shutil.rmtree(task_dir) break else: continue elif choice == "2": path_completer = PathCompleter() xmlfile = prompt( u"parse xml, please input the xml file==>", completer=path_completer, history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), ) xmlfile = xmlfile.strip() if os.path.isfile(xmlfile): des_xml_file = os.path.join(task_dir, os.path.basename(xmlfile)) if os.path.abspath(xmlfile) == os.path.abspath( des_xml_file): # same file pass elif os.path.exists(des_xml_file): copy_choice = prompt( u"The file already exist,Overwirte or keep Two(O/t)?" ) if copy_choice.lower() in ["", "o"]: shutil.copyfile(xmlfile, des_xml_file) # overwrite elif copy_choice.lower() == "t": des_xml_file = os.path.join( task_dir, os.path.basename(xmlfile).split(".")[0] + "_1" + os.path.basename(xmlfile).split(".")[1]) shutil.copy(xmlfile, des_xml_file) else: continue else: shutil.copy(xmlfile, des_xml_file) url_list = GetHttp(xmlfile) print(url_list) fp = open(urls_file, "a+") if len(fp.readlines()) == 0: pass else: fp.write("\n") fp.writelines("\n".join(url_list)) fp.close() else: print "File do not exist!" continue elif choice == "3": IP_domain_file = prompt( u"Input the file that contains domain and IP relationship(Teemo Result File)\n==>" ) IP_domain_file = IP_domain_file.strip() if os.path.isfile(IP_domain_file): des_IP_Domain_file = os.path.join( task_dir, "Teemo-" + os.path.basename(IP_domain_file)) if os.path.abspath(IP_domain_file) == os.path.abspath( des_IP_Domain_file): # same file pass elif os.path.exists(des_IP_Domain_file): shutil.copyfile(IP_domain_file, des_IP_Domain_file) # overwrite else: shutil.copy(IP_domain_file, des_IP_Domain_file) IP2domain(urls_file, des_IP_Domain_file) else: print "File do not exist!" continue elif choice == "4": if os.path.isfile(urls_file): fp = open(urls_file, "r") urls = fp.readlines() fp.close() end_index = -1 if SCANNER.lower() == "wvs11": end_index = AddScans(urls) elif SCANNER.lower() == "wvs10": end_index = AddToWVS(urls) print "{0} urls added".format(end_index + 1) if end_index >= 0: urls_left = urls[end_index + 1:-1] urls_scanned = urls[0:end_index] fp = open(urls_file, "w") fp.writelines(urls_left) fp.close() fp = open(urls_scanned_file, "a") fp.writelines(urls_scanned) fp.write("____above urls added to scan at {0}______\n". format(datetime.datetime.now().strftime( "%m/%d/%Y %H%M"))) fp.close() break else: print "{0} not found!".format(urls_file) elif choice.lower() in ["5", 'back', 'exit']: break else: continue
animal_completer = WordCompleter([ 'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison', 'butterfly', 'cat', 'chicken', 'crocodile', 'dinosaur', 'dog', 'dolphine', 'dove', 'duck', 'eagle', 'elephant', 'fish', 'goat', 'gorilla', 'kangoroo', 'leopard', 'lion', 'mouse', 'rabbit', 'rat', 'snake', 'spider', 'turkey', 'turtle', ], ignore_case=True)
def get_default_preds(): """dynamically build autocomplete options based on an external file""" g = ontospy.Graph(rdfsschema, text=True, verbose=False, hide_base_schemas=False) classes = [(x.qname, x.bestDescription()) for x in g.classes] properties = [(x.qname, x.bestDescription()) for x in g.properties] commands = [('exit', 'exits the terminal'), ('show', 'show current buffer')] return rdfschema + owlschema + classes + properties + commands turtle_completer = WordCompleter([x[0] for x in get_default_preds()], ignore_case=True, WORD=True) # BOTTOM TOOLBAR def get_bottom_toolbar_tokens(cli): # TIP: in order to analyze current text: # t = cli.current_buffer.document.current_line return [( Token.Toolbar, "Please enter some Turtle. [TIP: esc|meta + enter to submit / 'exit' = exit]" )] style = style_from_dict({
def main(): print_logo() modules = load_modules() #Temporal project variables history = InMemoryHistory() suggest = AutoSuggestFromHistory() config = {} words = WordCompleter(PROJECT_OPTIONS, ignore_case=True, WORD=True) module = None end = False while not end: user_input = prompt('({0})> '.format(module) if module else '> ', get_bottom_toolbar_tokens=update_toolbar, auto_suggest=suggest, completer=words, history=history) if not module: #Base if user_input == 'help': print_help() elif user_input == 'exit': end = True elif 'use' in user_input: module = user_input.split(' ')[1] if not module in modules: module = None print('[-] Module "{0}" not found.'.format(module)) else: words = WordCompleter(modules[module].words, ignore_case=True) elif 'createProject' in user_input: config, history = create_project(*user_input.split(' ')) elif 'openProject' in user_input: open_project(*user_input.split(' ')) elif 'showInfo' in user_input: #TODO #Print project info print('[+] Modules jobs:') for m in modules: modules[m].show_info() elif 'showModules' in user_input: print("[+] Available modules:") for m in modules: print("\t{0}".format(m)) else: print( '[-] Option "{0}" not found. Please use "help" to see the correct options.' .format(user_input)) else: if user_input == 'back': module = None words = WordCompleter(PROJECT_OPTIONS, ignore_case=True) else: modules[module].run(user_input)
# code from PyCon talk 'Awesome Commandline Tools by Amjith' # https://speakerdeck.com/amjith/awesome-commandline-tools # by https://twitter.com/amjithr from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter from pygments.lexers.sql import SqlLexer SQLCompleter = WordCompleter(['select', 'show', 'from', 'insert', 'update', 'delete', 'drop', 'where'], ignore_case=True) while 1: user_input = prompt(u'SQL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter, lexer=SqlLexer, ) print(user_input)
def interactive(self): """ interactive shell""" self.op = ShellOperations() #invokes shell opertions self.bindings = KeyBindings() cat_Storage = [] line = "" self.toolBar = ToolBar() #creates tool bar input_History = InMemoryHistory() operators = ["+", "-", "*", '**', '<', ">"] returnShellMethods = {"tod": self.op.do_tod()} listofprintMethods = [ "meow", "help", "bll", "h", "cur", "bdir", "bl", "sh", "wc", "get", "cwl", "cdir", "man", "move", "copy" ] linux_Commands = WordCompleter(listofprintMethods) while (True): #excute while True enter_commands = prompt( ">>", history=input_History, key_bindings_registry=self.bindings.register, completer=linux_Commands, mouse_support=True, get_title=self.get_title, get_bottom_toolbar_tokens=self.toolBar. get_bottom_toolbar_tokens, style=self.toolBar.toolBarStyle) store = enter_commands store = store.split(" ") if (enter_commands in returnShellMethods.keys()): print(returnShellMethods[enter_commands]) if (enter_commands not in returnShellMethods.keys()) and ( enter_commands not in listofprintMethods) and (store[0] not in listofprintMethods): try: exec(enter_commands) except Exception as Err: print(Err) if (enter_commands == 'cl'): self.op.do_cl() if ( enter_commands == "exit" ): #if enter_commands equal to exit then exit interactive shell os.system("exit") if (len(enter_commands) > 1) and (enter_commands[1] in operators): try: print(eval(enter_commands)) except Exception as err: print(err) if (enter_commands in listofprintMethods) and (enter_commands == "bll"): self.op.do_bll() if (enter_commands == "h") and (enter_commands in listofprintMethods): self.op.do_h(line) if (enter_commands == "cur") and (enter_commands in listofprintMethods): self.op.do_cur(line) if (enter_commands == "bdir") and (enter_commands in listofprintMethods): self.op.do_bdir(line) if (enter_commands == 'bl') and (enter_commands in listofprintMethods): self.op.do_bl(line) if (store[0] == "sh") and (store[0] in listofprintMethods): try: self.op.do_show(store[1]) except Exception as err: self.op.do_show(line) if (store[0] == "wc") and (store[0] in listofprintMethods): try: self.op.do_cw(store[1]) except Exception as err: self.op.do_cw(line) if (store[0] == 'get') and (store[0] in listofprintMethods): try: self.op.do_get(store[1]) except Exception as err: self.op.do_get(line) if (store[0] == "cwl") and (store[0] in listofprintMethods): try: self.op.do_cwl(store[1]) except Exception as err: self.op.do_cwl(line) if (store[0] == "cdir") and (store[0] in listofprintMethods): try: self.op.do_cdir(store[1]) except Exception as err: self.op.do_cdir(line) if (store[0] == "help") and (store[0] in listofprintMethods): try: self.op.do_help(store[1]) except Exception as err: self.op.do_help(line) if (store[0] == "meow") and (store[0] in listofprintMethods): if (len(store) == 1): self.op.do_cat(line) if (len(store) == 2): if (do_cat_return[0] in dir()): for cat_evaluation in eval(do_cat_return[0]): print(cat_evaluation) if (store[0] == "meow") and (store[0] in listofprintMethods) and (len(store) == 3): do_cat_return = self.op.do_cat(store) exec(str(do_cat_return))
# All prompt_toolkit imports are for linux curses, a simple command line interface. This will be removed soon. from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.shortcuts import create_prompt_application, create_asyncio_eventloop, prompt_async # These are some imports specific to the client-server. from chat_utils import Login, Sender, Request, Message # import the tuples that we use for communication from chat_utils import toolbar_tokens from chat_utils import tstamp loop = asyncio.get_event_loop() client = [] cmd_complete = WordCompleter(['send', 'bye', 'contacts'], match_middle=True, ignore_case=True) async def client_talk(loop): usr = await prompt_async("username:"******"password:"******">" contacts = [] history = InMemoryHistory() cli = CommandLineInterface(application=create_prompt_application( cin, history=history,
from pygments.lexers import HtmlLexer from prompt_toolkit import prompt from prompt_toolkit.layout.lexers import PygmentsLexer from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.history import InMemoryHistory from completer import EsToolkitCompleter logging.basicConfig(filename="{}/{}".format( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'estoolkit.log'), level=logging.DEBUG) completer = WordCompleter(['set', 'connect', 'GET', 'PUT']) class MyCustomCompleter(Completer): def get_completions(self, document, complete_event): logging.debug("text=%s", document.text) logging.debug("text_before_cursor=%s", document.text_before_cursor) yield Completion('completion', start_position=0) def main(): """ """ history = InMemoryHistory() while True: text = prompt('> ',
def leer2(c, tabla, campo, texto): """Función auxiliar: lee de la entrada un elemento de la base de datos.""" c.execute("SELECT " + campo + " FROM " + tabla) return prompt(texto, completer=WordCompleter([str(t[0]) for t in c.fetchall()], ignore_case=True))
def main(group_id, location, time_boundary, event_status, pandoc): key_path = os.path.normpath(os.path.expanduser('~/.meetup.com-key')) if os.path.exists(key_path): with open(key_path) as fh: key = fh.read().strip() cache = FileCache('.web_cache', forever=True) requests = CacheControl( Session(), cache, cache_etags=False, heuristic=ExpiresAfter(days=1) ) while True: resp = requests.get('https://api.meetup.com/status', params=dict(key=key)) if resp.status_code == 200: break elif resp.status_code == 401: click.echo('Your meetup.com key is required. You can get it from https://secure.meetup.com/meetup_api/key/\n') if click.confirm('Open https://secure.meetup.com/meetup_api/key/ in your web browser?'): click.launch('https://secure.meetup.com/meetup_api/key/') click.echo('') key = click.prompt('Key', hide_input=True) else: click.fail('Failed to get meetup.com status. Response was {!r}'.format(resp.text)) click.secho('For convenience your key is saved in `{}`.\n'.format(key_path), fg='magenta') with open(key_path, 'w') as fh: fh.write(key) while not location: location = location or get_input('Location: ', completer=WordCompleter(['cluj', 'iasi', 'timisoara'], ignore_case=True)) while True: group_id = group_id or get_input('Group ID: ', completer=WordCompleter(['Cluj-py', 'RoPython-Timisoara'], ignore_case=True)) resp = requests.get('https://api.meetup.com/2/events', params=dict( key=key, group_urlname=group_id, time=time_boundary, status=event_status, )) if resp.status_code == 200: json = resp.json() if json['results']: break else: click.secho('Invalid group `{}`. It has no events!'.format(group_id), fg='red') group_id = None if resp.status_code == '400': click.fail('Failed to get make correct request. Response was {!r}'.format(resp.text)) else: click.secho('Invalid group `{}`. Response was [{}] {!r}'.format(group_id, resp.status_code, resp.text), fg='red') # click.echo(pformat(dict(resp.headers))) for event in json['results']: dt = datetime.fromtimestamp(event['time']/1000) click.echo("{}: {}".format( dt.strftime('%Y-%m-%d %H:%M:%S'), event['name'] )) existing_path = glob(os.path.join('content', '*', dt.strftime('%Y-%m-%d*'), 'index.rst')) if existing_path: if len(existing_path) > 1: click.secho('\tERROR: multiple paths matched: {}'.format(existing_path)) else: click.secho('\t`{}` already exists. Not importing.'.format(*existing_path), fg='yellow') else: target_dir = os.path.join('content', location, '{}-{}'.format(dt.strftime('%Y-%m-%d'), slugify(event['name']))) target_path = os.path.join(target_dir, 'index.rst') if not os.path.exists(target_dir): os.makedirs(target_dir) if pandoc: with tempfile.NamedTemporaryFile(delete=False) as fh: fh.write(event['description'].encode('utf-8')) rst = subprocess.check_output(['pandoc', '--from=html', '--to=rst', fh.name]).decode('utf-8') print fh.name #os.unlink(fh.name) else: stream = StringIO() html2rest(event['description'].encode('utf-8'), writer=stream) rst = stream.getvalue().decode('utf-8') with io.open(target_path, 'w', encoding='utf-8') as fh: fh.write('''{name} ############################################################### :tags: unknown :registration: meetup.com: {event_url} {rst}'''.format(rst=rst, **event)) click.secho('\tWrote `{}`.'.format(target_path), fg='green')
def portfolio(cmd, nocolor, value, profit): """Command to manage your local portfolio. Arguments: add, remove, clear, history""" # Database db = TinyDB('db.json') # Add transaction if cmd == 'add': click.echo('Add new transaction') response = requests.get('https://api.coinmarketcap.com/v1/ticker/') crypto_data = response.json() crypto_data_map = {} # Dictionary for faster access all_coins = [] # List of all coin names for crypto in crypto_data: all_coins.append(crypto['symbol']) crypto_data_map[crypto['symbol']] = crypto # buy/sell transaction tx_type_completer = WordCompleter(['buy', 'sell'], ignore_case=True) tx_type = prompt('type (buy/sell) > ', completer=tx_type_completer) while not (tx_type.lower() == 'buy' or tx_type.lower() == 'sell'): click.secho('ERROR: invalid transaction type', fg='red') tx_type = prompt('type (buy/sell) > ', completer=tx_type_completer) # coin type tx_coin_completer = WordCompleter(all_coins, ignore_case=True) tx_coin = prompt('coin > ', completer=tx_coin_completer) while tx_coin not in all_coins: click.secho('ERROR: coin does not exist in list', fg='red') tx_coin = prompt('coin > ', completer=tx_coin_completer) # buy/sell price tx_coin_price = prompt( tx_type + ' price per coin (leave blank to use market price) > ') if not tx_coin_price and tx_coin_price != 0: tx_coin_price = crypto_data_map[tx_coin]['price_usd'] # amount tx_amount = prompt('amount > ') while not tx_amount: click.secho('ERROR: invalid amount') tx_amount = prompt('amount > ') # date tx_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") # coin market value coin_market_price = crypto_data_map[tx_coin]['price_usd'] # calculate tx ID db_transactions = db.all() if not db_transactions: tx_id = 0x1 else: db_transactions = sorted( db_transactions, key=lambda k: k['id'], reverse=True) tx_id = db_transactions[0]['id'] + 0x1 tx_info = { 'type': tx_type.upper(), 'coin': tx_coin, 'price': float(tx_coin_price), 'amount': float(tx_amount), 'date': tx_date, 'id': tx_id } db.insert(tx_info) hodl_change = float(tx_amount) * float(coin_market_price) if(tx_type.lower() == 'buy'): hodl_change = click.style('+' + str(hodl_change), fg='green') if(tx_type.lower() == 'sell'): hodl_change = click.style('-' + str(hodl_change), fg='red') tx_info_table = [ ['ADDED TRANSACTION'], ['Type', tx_type.upper()], ['Coin', tx_coin], ['Price ($)', tx_coin_price], ['Amount', tx_amount], ['Timestamp', tx_date], ['ID', tx_id], ['Δ holdings', hodl_change] ] click.echo(SingleTable(tx_info_table).table) # Remove transaction if cmd == 'remove': if not sys.stdin.isatty(): remove_tx_tuple = sys.stdin.readline() else: remove_tx_tuple = prompt('remove transactions > ') if not remove_tx_tuple: return remove_tx_tuple = tuple(int(x.strip()) for x in remove_tx_tuple.split(',')) transaction = Query() removed_ids = [] for tx_id in remove_tx_tuple: if db.search(transaction.id == tx_id): removed_ids.append(tx_id) db.remove(transaction.id == tx_id) if removed_ids: click.echo('Removed transaction(s): ' + str(tuple(removed_ids))) else: click.echo('No transactions were removed') # Clear transaction database if cmd == 'clear': if not db.all(): click.echo('There are no transactions to delete') return decision = prompt( 'are you sure you want to clear all transactions? (y/n) > ') if decision.lower() == 'y': db.purge() click.echo('DELETED ALL TRANSACTIONS') # Print all transactions if cmd == 'history': db_transactions = db.all() if not db_transactions: click.echo('There are no transactions to display') return for tx in db_transactions: if(tx['type'] == 'BUY'): tx_type = click.style(tx['type'], fg='green') if(tx['type'] == 'SELL'): tx_type = click.style(tx['type'], fg='red') tx_info_table = [ ['Type', tx_type], ['Coin', tx['coin']], ['Price ($)', tx['price']], ['Amount', tx['amount']], ['Timestamp', tx['date']], ['ID', tx['id']] ] table = SingleTable(tx_info_table) table.inner_heading_row_border = False click.echo(table.table) # Display portfolio data if not cmd: if not db.all(): click.echo('Your portfolio is empty.') return response = requests.get('https://api.coinmarketcap.com/v1/ticker/') crypto_data = response.json() crypto_data_map = {} # Dictionary for faster access all_coins = [] # List of all coin names for crypto in crypto_data: all_coins.append(crypto['symbol']) crypto_data_map[crypto['symbol']] = crypto total_hodlings_usd = 0 investment_usd = 0 all_coin_info = {} for tx in db.all(): if tx['coin'] in all_coin_info: coin_info = all_coin_info[tx['coin']] else: all_coin_info[tx['coin']] = coin_info = { 'amount': 0, 'investment': 0, 'profit': 0 } if tx['type'] == 'BUY': modifier = 1 elif tx['type'] == 'SELL': modifier = -1 total_hodlings_usd += modifier * \ tx['amount'] * float(crypto_data_map[tx['coin']]['price_usd']) investment_usd += modifier * tx['amount'] * tx['price'] coin_info['amount'] += modifier * tx['amount'] coin_info['investment'] += modifier * tx['amount'] * tx['price'] all_coin_info[tx['coin']] = coin_info # Calculate profit for each coin for key in all_coin_info: coin_info = all_coin_info[key] coin_info['coin'] = key coin_info['profit'] = coin_info['amount'] * float( crypto_data_map[key]['price_usd']) - coin_info['investment'] all_coin_info = all_coin_info.values() all_coin_info = sorted( all_coin_info, key=lambda k: k['profit'], reverse=True) # Calculate profits port_profit = round(total_hodlings_usd - investment_usd, 5) if not nocolor: if port_profit > 0: port_profit = click.style(str(port_profit), fg='green') elif port_profit < 0: port_profit = click.style(str(port_profit), fg='red') min_info = '' if value: min_info += 'Value: ' + str(round(total_hodlings_usd, 5)) + ' ' if profit: min_info += 'Profit: ' + str(port_profit) if value or profit: click.echo(min_info + '\n') return # Individual coin value and profit table coin_table = [ ['Coin', 'Amount', 'Investment ($)', 'Profit ($)'], ] + [ [ coin_info['coin'], round(coin_info['amount'], 5), round(coin_info['investment'], 5), click.style(str(round(coin_info['profit'], 5)), fg='green') if coin_info['profit'] > 0 else click.style(str(round(coin_info['profit'], 5)), fg='red') if not nocolor or (coin_info['profit'] == 0) else round(coin_info['profit'], 5) ] for coin_info in all_coin_info ] table = SingleTable(coin_table) table.inner_row_border = True table.inner_heading_row_border = False click.echo(table.table) # Portfolio value and profit table total_table = [ ['Portfolio Value ($)', round(total_hodlings_usd, 5)], ['Investment ($)', round(investment_usd, 5)], ['Profit ($)', str(port_profit)], ] table = SingleTable(total_table) table.inner_row_border = True table.inner_heading_row_border = False click.echo(table.table)
from __future__ import unicode_literals import sys from prompt_toolkit import AbortAction, prompt from prompt_toolkit.contrib.completers import WordCompleter from prompt_toolkit.history import InMemoryHistory from pygments.lexers.rdf import SparqlLexer from pygments.style import Style from pygments.styles.default import DefaultStyle from pygments.token import Token sparql_completer = WordCompleter([ 'select', 'insert', 'delete', 'where', ], ignore_case=True) class DocumentStyle(Style): styles = { Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000', Token.Menu.Completions.Completion: 'bg:#008888 #ffffff', Token.Menu.Completions.ProgressButton: 'bg:#003333', Token.Menu.Completions.ProgressBar: 'bg:#00aaaa', } styles.update(DefaultStyle.styles)
rsvps = client.GetRsvps(event_id='239174106', urlname='_ChiPy_') member_id = ','.join( [str(i['member']['member_id']) for i in rsvps.results]) members = client.GetMembers(member_id=member_id) names = [] for member in members.results: try: names.append(member['name']) except: pass # ignore those who do not have a complete profile return names command_completer = WordCompleter(['add'], ignore_case=True) def execute(command, person_num_line): # parse command # add <name> <lines> command = command.strip() parsed_command = command.split(' ') entered_command = parsed_command.pop(0) if entered_command == 'add': num_lines_of_code = parsed_command.pop(-1) parsed_name = ' '.join(parsed_command) try: int_num_lines_of_code = int(num_lines_of_code)
bot_path = '../bots' temporalPath = "/awareness/temporal/" relationalPath = "/awareness/relational/" contextualPath = "/awareness/contextual/" BOTKeywords = [ 'create', 'delete', 'add', 'remove', 'context', 'relation', 'reset' ] relation_type = [ 'is a', 'has a', 'is', 'has', 'part of', 'type of', 'kind of', 'attribute of', 'piece of', 'member of', 'is like' ] #relation_type = [':is a', ':has a', ':is', ':has', ':part of', ':type of', ':kind of', ':attribute of', ':piece of', ':member of', ':is like'] relation_completer = WordCompleter([ 'is a', 'has a', 'is', 'has', 'part of', 'type of', 'kind of', 'attribute of', 'piece of', 'member of', 'is like' ]) base_completer = WordCompleter([ ':create', ':delete', ':make', ':clone', ':define', ':analyse', ':list', ':freeform' ]) bottype_completer = WordCompleter([':databot', ':metabot', ':relationbot']) deleter_completer = WordCompleter([':list']) cloner_completer = WordCompleter([':list']) define_completer = WordCompleter([':relation', ':context']) #relation_completer = WordCompleter([':inherited', ':composited', ':associative', ':aggregative']) cmd = '' user_input = 'start'
if __name__ == '__main__': g = create_grammar() lexer = GrammarLexer(g, lexers={ 'operator1': SimpleLexer(Token.Operator), 'operator2': SimpleLexer(Token.Operator), 'var1': SimpleLexer(Token.Number), 'var2': SimpleLexer(Token.Number), }) completer = GrammarCompleter( g, { 'operator1': WordCompleter(operators1), 'operator2': WordCompleter(operators2), }) try: # REPL loop. while True: # Read input and parse the result. text = prompt('Calculate: ', lexer=lexer, completer=completer, style=ExampleStyle) m = g.match(text) if m: vars = m.variables() else:
# Definitions of commands CMD_HELP = "help" CMD_LOAD = "load" CMD_REGISTERS = "registers" CMD_FIND = "find" CMD_PAYLOAD = "payload" CMD_CONTEXT = "context" CMD_CONFIG = "config" CMD_EXPLOIT = "exploit" CMD_EXIT = "exit" command_list = [ CMD_HELP, CMD_LOAD, CMD_REGISTERS, CMD_FIND, CMD_CONFIG, CMD_EXIT ] command_completer = WordCompleter(command_list) command_history = InMemoryHistory() def main(time_mesure=False): if (time_mesure): pr = cProfile.Profile() pr.enable() #try: # Launching ROPGenerator write_colored(ASCII_art) Config.load_config() Logs.init() quit = False
# coding: utf-8 from nutstore_cli.execution import COMMANDS from prompt_toolkit.contrib.completers import WordCompleter completer = WordCompleter(words=COMMANDS, ignore_case=False)
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter from pygments.lexers.sql import SqlLexer SQLCompleter = WordCompleter(['SLECET', 'SHOW', 'FROM', 'WHERE'], ignore_case=True) while 1: inp = prompt( u'>> ', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter, lexer=SqlLexer # syntax highlighting ) if inp == "quit": break print(inp)
from prompt_toolkit import prompt from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.contrib.completers import WordCompleter from bucket.cmdparser import CmdParser from bucket.const import AVAILABLE_COMMANDS command_completer = WordCompleter(AVAILABLE_COMMANDS, ignore_case=True) def main(): history = InMemoryHistory() parser = CmdParser() try: print('Bucket v1.0 - Welcome!') print('If you press esc-!, you can enter system commands.') while True: cmd = prompt(">_ ", history=history, completer=command_completer, complete_while_typing=False, enable_system_bindings=True) if cmd: parser.parse(cmd) except (EOFError, KeyboardInterrupt): print('GoodBye!')
class PromptInterface(object): go_on = True completer = WordCompleter([ 'block', 'tx', 'header', 'mem', 'help', 'state', 'node', 'exit', 'quit', 'config', 'db', 'log' ]) commands = [ 'quit', 'help', 'block {index/hash}', 'header {index/hash}', 'tx {hash}', 'mem', 'nodes', 'state', 'config {node, db} int int' 'config log on/off' 'pause', ] token_style = style_from_dict({ Token.Command: '#ff0066', Token.Neo: '#0000ee', Token.Default: '#00ee00', Token.Number: "#ffffff", }) history = InMemoryHistory() start_height = Blockchain.Default().Height start_dt = datetime.datetime.utcnow() node_leader = None paused = False def paused_loop(self): while self.paused: # self.__log.debug("paused...") time.sleep(1) def get_bottom_toolbar(self, cli=None): try: return [(Token.Command, 'Progress: '), (Token.Number, str(Blockchain.Default().Height)), (Token.Neo, '/'), (Token.Number, str(Blockchain.Default().HeaderHeight))] except Exception as e: print("couldnt get toolbar: %s " % e) return [] def quit(self): print('Shutting down. This may take a bit...') self.go_on = False self.paused = False Blockchain.Default().Dispose() reactor.stop() self.node_leader.Shutdown() def help(self): tokens = [] for c in self.commands: tokens.append((Token.Command, "%s\n" % c)) print_tokens(tokens, self.token_style) def toggle_pause(self): if self.paused: self.paused = not self.paused # reactor.run() print("resusiming execution") else: self.paused = not self.paused print('pausing execution!') reactor.callLater(1, self.paused_loop) 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 show_nodes(self): if self.node_leader and len(self.node_leader.Peers): out = '' for peer in self.node_leader.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 show_block(self, args): item = self.get_arg(args) txarg = self.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.Transactions: self.show_tx([tx]) else: print("could not locate block %s" % item) else: print("please specify a block") def show_header(self, args): item = self.get_arg(args) if item is not None: header = Blockchain.Default().GetHeaderBy(item) if header is not None: print(json.dumps(header.ToJson(), indent=4)) else: print("could not locate Header %s \n" % item) else: print("please specify a header") def show_tx(self, args): item = self.get_arg(args) if item is not None: try: tx, height = Blockchain.Default().GetTransaction(item) if height > -1: bjson = json.dumps(tx.ToJson(), indent=4) tokens = [(Token.Command, bjson)] print_tokens(tokens, self.token_style) print('\n') except Exception as e: print("Could not find transaction with id %s " % item) print( "Please specify a tx hash like 'db55b4d97cf99db6826967ef4318c2993852dff3e79ec446103f141c716227f6'" ) else: print("please specify a tx hash") def show_account_state(self, args): item = self.get_arg(args) print("account to show %s " % item) 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 show_asset_state(self, args): item = self.get_arg(args) print("asset to show %s " % item) if item is not None: 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 show_contract_state(self, args): item = self.get_arg(args) if item is not None: if item.lower() == 'all': contracts = Blockchain.Default().ShowAllContracts() print("contracts: %s " % contracts) else: contract = Blockchain.Default().GetContract(item) if contract is not None: bjson = json.dumps(contract.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("please specify a contract") def show_spent_coins(self, args): item = self.get_arg(args) if item is not None: if item.lower() == 'all': coins = Blockchain.Default().GetAllSpentCoins() print("coins %s " % coins) else: coin = Blockchain.Default().GetSpentCoins(item) if coin is not None: bjson = json.dumps(coin.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print("\n") else: print("please specify a tx hash") 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 configure(self, args): what = self.get_arg(args) if what == 'node': c1 = self.get_arg(args, 1, convert_to_int=True) c2 = self.get_arg(args, 2, convert_to_int=True) if not c1: print("please provide settings. arguments must be integers") if c1 is not None and c1 > 1: if c1 > 200: c1 = 200 print("Node request part must be less than 201") self.node_leader.BREQPART = c1 print("Set Node Request Part to %s " % c1) if c2 is not None and c2 >= self.node_leader.BREQPART: self.node_leader.BREQMAX = c2 print("Set Node Request Max to %s " % c2) self.show_state() elif what == 'db': c1 = self.get_arg(args, 1, convert_to_int=True) c2 = self.get_arg(args, 2, convert_to_int=True) if c1 is not None and c1 > 1: Blockchain.Default().CACHELIM = c1 print("Set DB Cache Limit to %s " % c1) if c2 is not None and c2 >= self.node_leader.BREQPART: Blockchain.Default().CMISSLIM = c2 print("Set DB Cache Miss Limit %s " % c2) self.show_state() elif what == 'log' or what == 'logs': c1 = self.get_arg(args, 1).lower() if c1 is not None: if c1 == 'on' or c1 == '1': print("turning on logging") logger = logging.getLogger() logger.setLevel(logging.DEBUG) if c1 == 'off' or c1 == '0': print("turning off logging") logger = logging.getLogger() logger.setLevel(logging.ERROR) else: print("cannot configure log. Please specify on or off") else: print("cannot configure %s " % what) print( "Try 'config node 100 1000' or config db 1000 4' or config log on/off" ) def get_arg(self, arguments, index=0, convert_to_int=False): try: arg = arguments[index] if convert_to_int: return int(arg) return arg except Exception as e: pass return None def parse_result(self, result): if len(result): commandParts = [s for s in result.split()] return commandParts[0], commandParts[1:] return None, None 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 == 'asset': self.show_asset_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
class PromptInterface(object): go_on = True completer = WordCompleter([ 'block', 'tx', 'header', 'mem', 'help', 'state', 'node', 'exit', 'quit', 'config', 'import', 'export', 'open', 'wallet', 'contract', 'asset', ]) _gathering_password = False _gathered_passwords = [] _gather_password_action = None _gather_address_str = None _num_passwords_req = 0 _wallet_create_path = None _wallet_send_tx = None _invoke_test_tx = None _invoke_test_tx_fee = None Wallet = None commands = [ 'quit', 'help', 'block {index/hash}', 'header {index/hash}', 'tx {hash}', 'asset {assetId}', 'asset search {query}', 'contract {contract hash}', 'contract search {query}', 'mem', 'nodes', 'state', 'config log {on/off}', 'import wif {wif}', 'import contract {path} {params} {returntype}', 'export wif {address}' 'open wallet {path}', 'create wallet {path}', 'wallet {verbose}', 'wallet rebuild {start block}', 'send {assetId or name} {address} {amount}', 'testinvoke {contract hash} {params}', 'invoke', 'cancel', ] token_style = style_from_dict({ Token.Command: '#ff0066', Token.Neo: '#0000ee', Token.Default: '#00ee00', Token.Number: "#ffffff", }) history = InMemoryHistory() start_height = Blockchain.Default().Height start_dt = datetime.datetime.utcnow() def get_bottom_toolbar(self, cli=None): out = [] try: out = [(Token.Command, 'Progress: '), (Token.Number, str(Blockchain.Default().Height)), (Token.Neo, '/'), (Token.Number, str(Blockchain.Default().HeaderHeight))] except Exception as e: pass return out def quit(self): print('Shutting down. This may take a bit...') self.go_on = False Blockchain.Default().Dispose() reactor.stop() NodeLeader.Instance().Shutdown() def help(self): tokens = [] for c in self.commands: tokens.append((Token.Command, "%s\n" % c)) print_tokens(tokens, self.token_style) def do_open(self, arguments): item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if not os.path.exists(path): print("wallet file not found") return self._num_passwords_req = 1 self._wallet_create_path = path self._gathered_passwords = [] self._gathering_password = True self._gather_password_action = self.do_open_wallet else: print("Please specify a path") else: print("item is? %s " % item) def do_create(self, arguments): item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if os.path.exists(path): print("File already exists") return self._num_passwords_req = 2 self._wallet_create_path = path self._gathered_passwords = [] self._gathering_password = True self._gather_password_action = self.do_create_wallet # print("create wallet! Please specify a password") else: print("Please specify a path") def do_create_wallet(self): # print("do create wallet with passwords %s "% self._gathered_passwords) psswds = self._gathered_passwords path = self._wallet_create_path self._wallet_create_path = None self._gathered_passwords = None self._gather_password_action = None if len(psswds) != 2 or psswds[0] != psswds[1] or len(psswds[0]) < 10: print( "please provide matching passwords that are at least 10 characters long" ) return passwd = psswds[1] try: self.Wallet = UserWallet.Create(path=path, password=passwd) except Exception as e: print("Exception creating wallet: %s " % e) contract = self.Wallet.GetDefaultContract() key = self.Wallet.GetKey(contract.PublicKeyHash) print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4)) print("pubkey %s " % key.PublicKey.encode_point(True)) dbloop = task.LoopingCall(self.Wallet.ProcessBlocks) dbloop.start(1) def do_open_wallet(self): passwd = self._gathered_passwords[0] path = self._wallet_create_path self._wallet_create_path = None self._gathered_passwords = None self._gather_password_action = None try: self.Wallet = UserWallet.Open(path, passwd) dbloop = task.LoopingCall(self.Wallet.ProcessBlocks) dbloop.start(1) print("Opened wallet at %s" % path) except Exception as e: print("could not open wallet: %s " % e) # traceback.print_stack() # traceback.print_exc() def do_import(self, arguments): item = get_arg(arguments) if item: if item == 'wif': if not self.Wallet: print("Please open a wallet before importing WIF") return wif = get_arg(arguments, 1) if wif: prikey = KeyPair.PrivateKeyFromWIF(wif) if prikey: key = self.Wallet.CreateKey(prikey) print("imported key %s " % wif) print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex()) print("Wallet: %s " % json.dumps(self.Wallet.ToJson(), indent=4)) else: print("invalid wif") return elif item == 'contract': return self.load_smart_contract(arguments) elif item == 'contract_addr': return ImportContractAddr(self.Wallet, arguments[1:]) print("please specify something to import") return def do_export(self, arguments): item = get_arg(arguments) if item == 'wif': if not self.Wallet: print("please open a wallet") return addr = get_arg(arguments, 1) if not addr: print('please specify an address') return if not self.Wallet.ContainsAddressStr(addr): print("address %s not found in wallet" % addr) return self._num_passwords_req = 1 self._gather_address_str = addr self._gathered_passwords = [] self._gathering_password = True self._gather_password_action = self.do_export_wif return print("Command export %s not found" % item) def do_export_wif(self): passwd = self._gathered_passwords[0] address = self._gather_address_str self._gather_address_str = None self._gathered_passwords = None self._gather_password_action = None if not self.Wallet.ValidatePassword(passwd): print("incorrect password") return keys = self.Wallet.GetKeys() for key in keys: export = key.Export() print("key export : %s " % export) def show_wallet(self, arguments): if not self.Wallet: print("please open a wallet") return item = get_arg(arguments) if not item: print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4)) return if item in ['v', '--v', 'verbose']: print("Wallet %s " % json.dumps(self.Wallet.ToJson(verbose=True), indent=4)) return if item == 'migrate' and self.Wallet is not None: print("migrating wallet...") self.Wallet.Migrate() print("migrated wallet") if item == 'delete_addr': addr_to_delete = get_arg(arguments, 1) print("address to delete %s" % addr_to_delete) DeleteAddress(self, self.Wallet, addr_to_delete) if item == 'close': print('closed wallet') self.Wallet = None if item == 'rebuild': self.Wallet.Rebuild() try: item2 = int(get_arg(arguments, 1)) if item2 and item2 > 0: print('restarting at %s ' % item2) self.Wallet._current_height = item2 except Exception as e: pass if item == 'unspent': self.Wallet.FindUnspentCoins() def do_send(self, arguments): construct_and_send(self, self.Wallet, arguments) 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 tokens = [(Token.Number, out)] print_tokens(tokens, self.token_style) def show_nodes(self): if len(NodeLeader.Instance().Peers) > 0: out = '' 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 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: # with open("b_1445025.txt",'w') as myfile: # for tx in block.FullTransactions: # myfile.write(json.dumps(tx.ToJson(), indent=4)) 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_header(self, args): item = get_arg(args) if item is not None: header = Blockchain.Default().GetHeaderBy(item) if header is not None: print(json.dumps(header.ToJson(), indent=4)) else: print("could not locate Header %s \n" % item) else: print("please specify a header") def show_tx(self, args): item = get_arg(args) if item is not None: try: tx, height = Blockchain.Default().GetTransaction(item) if height > -1: bjson = json.dumps(tx.ToJson(), indent=4) tokens = [(Token.Command, bjson)] print_tokens(tokens, self.token_style) print('\n') except Exception as e: print("Could not find transaction with id %s " % item) print( "Please specify a tx hash like 'db55b4d97cf99db6826967ef4318c2993852dff3e79ec446103f141c716227f6'" ) else: print("please specify a tx hash") 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 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 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: bjson = json.dumps(contract.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("please specify a contract") def load_smart_contract(self, args): if not self.Wallet: print("please open wallet") return function_code = LoadContract(args[1:]) if function_code is not None: contract_script = GatherContractDetails(function_code, self) if contract_script is not None: tx, fee, results, num_ops = test_invoke( contract_script, self.Wallet, []) if tx is not None and results is not None: self._invoke_test_tx = tx self._invoke_test_tx_fee = fee print( "\n-------------------------------------------------------------------------------------------------------------------------------------" ) print("Test deploy invoke successful") print("Total operations executed: %s " % num_ops) print("Results %s " % [str(item) for item in results]) print("Deploy Invoke TX gas cost: %s " % (tx.Gas.value / Fixed8.D)) print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------------------------------------------------------------------------------\n" ) print( "You may now deploy this contract on the blockchain by using the 'invoke' command with no arguments or type 'cancel' to cancel deploy\n" ) return else: print("test ivoke failed") print("tx is, results are %s %s " % (tx, results)) return def test_invoke_contract(self, args): self._invoke_test_tx = None self._invoke_test_tx_fee = None if not self.Wallet: print("please open a wallet") return if args and len(args) > 0: tx, fee, results, num_ops = TestInvokeContract(self.Wallet, args) if tx is not None and results is not None: self._invoke_test_tx = tx self._invoke_test_tx_fee = fee print( "\n-------------------------------------------------------------------------------------------------------------------------------------" ) print("Test invoke successful") print("Total operations: %s " % num_ops) print("Results %s " % [str(item) for item in results]) print("Invoke TX gas cost: %s " % (tx.Gas.value / Fixed8.D)) print("Invoke TX Fee: %s " % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------------------------------------------------------------------------------\n" ) print( "You may now invoke this on the blockchain by using the 'invoke' command with no arguments or type 'cancel' to cancel invoke\n" ) return else: print("Error testing contract invoke") return print("please specify a contract to invoke") def invoke_contract(self, args): if not self._invoke_test_tx: print( "Please test your invoke before deploying it with the 'testinvoke {contracthash} *args' command" ) return result = InvokeContract(self.Wallet, self._invoke_test_tx, self._invoke_test_tx_fee) self._invoke_test_tx = None self._invoke_test_tx_fee = None return def cancel_operations(self): self._invoke_test_tx = None print("Operation cancelled") return 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 configure(self, args): what = get_arg(args) if what == 'log' or what == 'logs': c1 = get_arg(args, 1).lower() if c1 is not None: if c1 == 'on' or c1 == '1': print("turning on logging") logger = logging.getLogger() logger.setLevel(logging.DEBUG) if c1 == 'off' or c1 == '0': print("turning off logging") logger = logging.getLogger() logger.setLevel(logging.ERROR) else: print("cannot configure log. Please specify on or off") else: print("cannot configure %s " % what) print("Try 'config log on/off'") def parse_result(self, result): if len(result): commandParts = [s for s in result.split()] return commandParts[0], commandParts[1:] return None, None 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()
animal_completer = WordCompleter( [ 'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison', 'butterfly', 'cat', 'chicken', 'crocodile', 'dinosaur', 'dog', 'dolphine', 'dove', 'duck', 'eagle', 'elephant', ], meta_dict={ 'alligator': 'An alligator is a crocodilian in the genus Alligator of the family Alligatoridae.', 'ant': 'Ants are eusocial insects of the family Formicidae', 'ape': 'Apes (Hominoidea) are a branch of Old World tailless anthropoid catarrhine primates ', 'bat': 'Bats are mammals of the order Chiroptera', }, ignore_case=True)
self.wallet += total ## remove sheep from the fold for s in sheepment: self.sheep.pop(s) print(SHIP_SUCCESS.format(len(grades), total)) self.newOrder(self.order[ORDER_NO_STR]**2) return def doTicket(self): ## print the current order print("{}: {}".format(ORDER_NO_STR, self.order[ORDER_NO_STR])) print("Minimum Grade: {}".format(min(self.order[ORDER_GRADE_STR]))) print("Maximum Grade: {}".format(max(self.order[ORDER_GRADE_STR]))) return print(BANNER_TXT) GAME = Game() while 1: ## Game loop ## Start a new order while 1: ## User input loop CURRENT_FOLD = [a for a in GAME.sheep.keys()] ACTIONS_LIST = list(ACTIONS) ACTIONS_LIST.extend(CURRENT_FOLD) COMPLETER = WordCompleter(ACTIONS_LIST) USER_INPUT = prompt( u'Shepherd>', completer=COMPLETER, ) doThing(GAME, USER_INPUT)