def interact(options): """ Controls interactive prompt with user """ url = options["url"] log("Interacting with: {url}".format(url=url)) help() log("Type your command or \"help\" for usage.") exit = False first = True while not exit: if first: command = ask("$ [introspect]") else: command = ask("$") if first and not command: command = "introspect" if first: first = False if command in ["exit", "quit"]: log("Exiting...") exit = True elif "help" == command: help() elif "query" == command: run_query(url) elif "introspect" == command: introspect(url) else: error("Unrecognized command: {command}".format(command=command)) help()
def command(self, cmd_string): try: link = ask("Link URL: ") name = ask("Link Text (You may leave blank): ").strip() or None body = ask("Additional description of the link? ") or None except NoEntry: return None return LinkNote(link, name, body)
def command(self, cmd_string): tokens = cmd_string.lower().strip().split() summary = ask("Table summary: ") table = [] while True: try: s = ask("Enter row of data (comma separated)", persist=False) if not s: break row = s.split(",") table.append(row) except NoEntry: return None return TableNote(summary, table, header="header" in tokens)
def saveMap(self): '''Basic map saving functionallity''' fileName = input("Save level as (Without .lvl extention)(enter 'x' to cancel): ") if fileName == 'x': print("Save cancelled"); return 0; fileName += ".lvl" filePath = "levels/" + fileName try: file = open(filePath, 'r'); found = True; file.close(); except: found = False; if found: answer = util.ask("Level already created. Overight?: (Yes/No) "); if answer == True: found = False; else: print("Save canceled!"); if found == False: file = open(filePath, 'w') mapOutPut = "mapWidth " + str(self.cols) + "\nmapHeight " + str(self.rows) + "\n" + self.getMapString() file.write(mapOutPut); file.close(); for layer in self.layerList: layer.tileListCatch = util.shallowCopy(layer.tileList); print(fileName+" saved");
def command(self, cmd_string): filename = cmd_string.strip() with mycsv.CSVFile(filename) as fp: data = fp.readlines() print "Loaded %d lines from %s" % (len(data), filename) summary = ask("Table summary: ") return CSVNote(summary, data)
def q3(): print(c.reset) answer = ask("Please use one word to describe the texture of their magical fur:") if answer.startswith("smile"): print(c.base3 + ":)") return True print(c.base3 + ":(") return False
def q2(): print(c.reset) answer = ask("Where are they dancing?") if answer.startswith("rainbow"): print(c.base3 + ":)") return True print(c.base3 + ":(") return False
def q1(): print(c.reset) answer = ask("What color are the unicorns?") if answer == 'pink': print(c.base3 + ":)") return True print(c.base3 + ":(") return False
def q1(): print(c.reset) answer = ask(c.red + 'How old is Drake Griffith?') if answer == '12': print(c.base3 + ':)') return True print(c.base3 + ':(') return False
def q5(): print(c.reset) answer = ask(c.blue + "What are some of Drake's best friends") if answer == 'josh' or answer == 'evan' or answer == 'michael' or answer == 'jake': print(c.base3 + ':)') return True print(c.base3 + ':(') return False
def q4(): print(c.reset) answer = ask(c.red + "What is my favorite TV show?") if answer == 'spongebob' or answer == 'family guy' or answer == 'south park': print(c.base3 + ':)') return True print(c.base3 +':(') return False
def q3(): print(c.reset) answer = ask(c.base3 + "What is Drake's favorite number?") if answer == '1738' or answer == '819': print(c.base3 + ':)') return True print(c.base3 + ':(') return False
def q2(): print(c.reset) answer = ask(c.blue + "What is Drake's Favorite Subject in School?") if answer == 'math': print(c.base3 + ':)') return True print(c.base3 + ':(') return False
def command(self, cmd_string): proc = subprocess.Popen(cmd_string, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout,stderr = proc.communicate() print "" print stdout print "" summary = ask("Enter a comment for this output") return ExecNote(cmd_string, summary, stdout, stderr)
def execute(self) -> None: with Logger(f":dizzy: {underline('Execution:')}") as logger: if self._manifest.context.confirm == ConfirmationMode.ONCE: if ask(logger=logger, message=bold('Execute?'), chars='yn', default='n') == 'n': raise UserError(f"user aborted") for resource in self._manifest.resources.values(): resource.execute()
def introspect(url): """ Performs introspection on a GraphQL API """ list_query_type_query = """ { __schema { types { name } } } """ query_types = [] result = gql_call(url, list_query_type_query) if result is None: return for entry in result["data"]["__schema"]["types"]: if entry["name"] and (entry["name"].startswith("__") or entry["name"] in ["String", "Boolean"]): continue else: query_types.append(entry["name"]) log("Available query types: ") counter = 0 for query_type in query_types: log("\t[{id}] {name}".format(id=counter, name=query_type)) counter += 1 exit = False while not exit: answer = ask( "Enter number for details (also, \"a\" to dump all or \"r\" to return): " ) if answer.isdigit(): index = int(answer.strip()) try: name = query_types[index] except IndexError: error("Not a valid selection: {index}".format(index=index)) else: log("More info on {id}".format(id=name)) query_type_introspect(url, name) elif answer == "r": exit = True elif answer == "a": exit = True for query_type in query_types: query_type_introspect(url, query_type) else: error("Unrecognized input: {answer}".format(answer=answer))
def loadMap(self, askForSave=True): '''Basic mapmaker loading functionality''' if askForSave == True: if util.ask("Save your work? (Yes/No)"): self.saveMap(); fileName = util.askForFileName(); if fileName != -1: loadedTileLists = util.loadTileLists(fileName); i = 0; while i < len(loadedTileLists): self.updateTileMapFromMapList(loadedTileLists[i],self.layerList[i]); i+=1; else: print("Canceling Load");
def setup(): """ Gets required details from user so we can start interacting with a GraphQL API """ url = ask("URL [{default_url}]: ".format(default_url=DEFAULT_URL)).strip() if not url: url = DEFAULT_URL else: log("User provided \"{url}\"".format(url=url)) # TODO Also, validate that the URL is valid if not url: raise ApplicationCriticalError("Invalid URl detected.") return {"url": url}
def Selaz(self): if len(self.notepageID)> 0 or len(self.frampageID)>0 : #wx.GetApp().SetTopWindow(self.winMDI) chiudi=util.ask(self, _("Per terminare la sessione devi prima chiudere tutti i moduli attivi")+"\n"+ _("Sono ancora aperte ") + str(len(self.notepageID)) + _(" schede e ") + str(len(self.frampageID))+ _(" finestre") + "\n" + _("Vuoi chiudere tutti i moduli attivi automaticamente ?"), _("Attenzione !!!")) if (chiudi==True) : id=len(self.notepageID) while id>0 : id=id-1 new = self.notebook_1.GetSelection() # codice ripetuto if new!=id : aux=self.notepageObj[new] aux.Hide() self.sizer_6.Detach(aux) topo=self.notepageObj[id] self.sizer_6.Add(topo, 1, wx.EXPAND, 0) topo.Show(True) self.sizer_6.Layout() self.notebook_1.SetSelection(id) # fine codice ripetuto aux=self.notepageObj[id] aux.SetFocus() # boh, forse utile aux.Close(False) #aggiunto None per retro 0.9.7. id=len(self.frampageID) while id>0 : id=id-1 finestra=self.frampageFra[id] #codice ripetuto finestra.Iconize(False) finestra.Raise() finestra.SetFocus() #fine codice ripetuto finestra.Close(False) # aggiunto None per retro 0.9.7 if len(self.notepageID) == 0 and len(self.frampageID) == 0 : if self.selazon==False: self.BackUp(self) self.win_logo_MDI.Hide() self.sizer_6.Detach(self.win_logo_MDI) self.win_logo_MDI.Destroy() #self.sizer_1.Destroy() #self.sizer_2.Destroy() #self.sizer_4.Destroy() #self.sizer_3.Destroy() #self.sizer_6.Destroy() #self.sizer_5.Destroy() self.notebook_1.Destroy() self.winMDI.Destroy() self.ftoolbar(False) self.fmenubar(False) self.SetStatusText("", 1) self.SetStatusText("", 2) self.SetStatusText("", 3) self.selazon=True self.SetStatusText(" "+_("Seleziona Azienda")) self.SetTitle(longversion) # === per retrocompatibilita' con la 0.9.7 rec = self.SetTTL #per retrocompatibilita' con la 0.9.7. poi da eliminare control = [_("Seleziona Azienda"),"Z", rec, self.AggMenu,1031, self.CMD] win = selaz.create(self, control) # ========== fine per la 0.9.7 self.win=win self.SendSizeEvent()
if __name__ == "__main__": path = setup_paths() env = Environment(loader=FileSystemLoader(os.path.join(path, 'templates'))) plugins = [] for plugin in get_plugins(os.path.join(path, 'plugins')): print "Loaded plugin %s" % plugin.name plugins.append(plugin) try: notebook = Notebook.load(FILENAME) print "Loaded a notebook with %d notes" % len(notebook.notes) except Exception, e: print e import util title = util.ask("Enter notebook title:") notebook = Notebook(title) notebook.save(FILENAME) while True: try: has_plugin = False if notebook.timecard: t = notebook.total_time hours = int(t.total_seconds())/3600 minutes = (int(t.total_seconds())-(3600*hours))/60 seconds = int(t.total_seconds())-(3600*hours)-(60*minutes) prompt = "jot %02d:%02d:%02d >>" % (hours, minutes,seconds) else: prompt = "jot >>"
def Selaz(self): if len(self.notepageID) > 0 or len(self.frampageID) > 0: #wx.GetApp().SetTopWindow(self.winMDI) chiudi = util.ask( self, _("Per terminare la sessione devi prima chiudere tutti i moduli attivi" ) + "\n" + _("Sono ancora aperte ") + str(len(self.notepageID)) + _(" schede e ") + str(len(self.frampageID)) + _(" finestre") + "\n" + _("Vuoi chiudere tutti i moduli attivi automaticamente ?"), _("Attenzione !!!")) if (chiudi == True): id = len(self.notepageID) while id > 0: id = id - 1 new = self.notebook_1.GetSelection() # codice ripetuto if new != id: aux = self.notepageObj[new] aux.Hide() self.sizer_6.Detach(aux) topo = self.notepageObj[id] self.sizer_6.Add(topo, 1, wx.EXPAND, 0) topo.Show(True) self.sizer_6.Layout() self.notebook_1.SetSelection( id) # fine codice ripetuto aux = self.notepageObj[id] aux.SetFocus() # boh, forse utile aux.Close(False) #aggiunto None per retro 0.9.7. id = len(self.frampageID) while id > 0: id = id - 1 finestra = self.frampageFra[id] #codice ripetuto finestra.Iconize(False) finestra.Raise() finestra.SetFocus() #fine codice ripetuto finestra.Close(False) # aggiunto None per retro 0.9.7 if len(self.notepageID) == 0 and len(self.frampageID) == 0: if self.selazon == False: self.BackUp(self) self.win_logo_MDI.Hide() self.sizer_6.Detach(self.win_logo_MDI) self.win_logo_MDI.Destroy() #self.sizer_1.Destroy() #self.sizer_2.Destroy() #self.sizer_4.Destroy() #self.sizer_3.Destroy() #self.sizer_6.Destroy() #self.sizer_5.Destroy() self.notebook_1.Destroy() self.winMDI.Destroy() self.ftoolbar(False) self.fmenubar(False) self.SetStatusText("", 1) self.SetStatusText("", 2) self.SetStatusText("", 3) self.selazon = True self.SetStatusText(" " + _("Seleziona Azienda")) self.SetTitle(longversion) # === per retrocompatibilita' con la 0.9.7 rec = self.SetTTL #per retrocompatibilita' con la 0.9.7. poi da eliminare control = [ _("Seleziona Azienda"), "Z", rec, self.AggMenu, 1031, self.CMD ] win = selaz.create(self, control) # ========== fine per la 0.9.7 self.win = win self.SendSizeEvent()
def command(self, cmd_string): summary = ask('Enter image description:') filename = os.path.abspath(cmd_string.strip()) return ImageFileNote(summary, filename)
def execute(self) -> None: # attempt to resolve all dependencies (resolving an already-resolved dependency has no side-effects) for dependency in self._dependencies.values(): dependency.execute() # if we're already resolving, we have a circular dependency loop if self._status == ResourceStatus.RESOLVING: raise UserError(f"illegal config: circular resource dependency encountered!") # if we were already resolved, do nothing (this can happen) elif self._status == ResourceStatus.VALID: return # fail if not initialized, or already resolving (circular dependency), and do nothing if already resolved elif self._status is None: raise Exception(f"internal error: cannot resolve un-initialized resource ('{self.name}')") with Logger(f":point_right: Inspecting {bold(self.name)} ({faint(self.type)})...") as logger: # post-process configuration config_context: dict = deepcopy(self._manifest.context.data) config_context.update({ alias: { 'name': dep.name, 'type': dep.type, 'state': dep.state, } for alias, dep in self._dependencies.items() }) self._resolved_config = post_process(value=self._config, context=config_context) # validate the config, now that it's been resolved try: jsonschema.validate(self._resolved_config, self._config_schema) except ValidationError as e: path: str = '' for token in e.path: if path: path: str = path + '[' + str(token) + ']' if type(token) == int else path + '.' + str(token) else: path = str(token) raise UserError(f"illegal config for '{self.name}.config.{path}': {e.message}\n" f"Must match schema: {e.schema}") from e # invoke the "state" action state_result = self._resolve_state(logger=logger) # save resource status self._status: ResourceStatus = ResourceStatus[state_result['status']] if self._status == ResourceStatus.VALID: self._state = state_result['state'] elif self._status == ResourceStatus.STALE: # parse "apply" actions from the "state" action's response self._apply_actions = \ [Action(work_dir=self._manifest.context.work_dir / self.name / action['name'], name=action['name'], description=action['description'] if 'description' in action else action['name'], image=action['image'] if 'image' in action else self.type, entrypoint=action['entrypoint'] if 'entrypoint' in action else None, args=action['args'] if 'args' in action else None) for action in state_result['actions']] if self._manifest.context.confirm == ConfirmationMode.RESOURCE: if util.ask(logger=logger, message=bold('Execute this resource?'), chars='yn', default='n') == 'n': raise UserError(f"user aborted") # execute the "apply" actions for action in self._apply_actions: with Logger(header=f":wrench: {action.description} ({action.name})") as action_logger: # confirm if necessary if self._manifest.context.confirm == ConfirmationMode.ACTION: if ask(logger=action_logger, message=bold('Execute?'), chars='yn', default='n') == 'n': raise UserError(f"user aborted") # execute self._docker_invoker.run( logger=action_logger, local_work_dir=self._manifest.context.work_dir / self.name / action.name, container_work_dir=str(self._manifest.context.workspace_dir), image=action.image, entrypoint=action.entrypoint, args=action.args, input={ 'name': self.name, 'type': self.type, 'version': self._manifest.context.version, 'verbose': self._manifest.context.verbose, 'workspace': str(self._manifest.context.workspace_dir), 'config': self._resolved_config, 'staleState': state_result["staleState"] if "staleState" in state_result else {} } ) # verify that the resource is now VALID updated_state_result: dict = self._resolve_state(logger=logger) if ResourceStatus[updated_state_result['status']] != ResourceStatus.VALID: raise UserError(f"protocol error: expected '{self.name}' to be VALID after applying actions") else: self._status = ResourceStatus.VALID self._state = updated_state_result['state'] else: raise Exception(f"internal error: unrecognized status '{self._status}' for '{self.name}'")