def check_ranks(): nav() print( " ================== How many Crypto's would you like listed?(1-879) ====================" ) ranks = raw_input(" ") url = "https://api.coinmarketcap.com/v1/ticker/?limit=" + str(ranks) response = urllib.urlopen(url) data = json.loads(response.read()) i = 0 rank = 1 while i < int(ranks): percent = float(data[i]['percent_change_1h']) rankString = str(rank) + "). " print(rankString + data[i]['name'] + " | " + data[i]['price_usd'] + " | " + color(percent)) rank += 1 i += 1 btc_price = str(data[0]['price_usd']) raw_input( " ================== Enter anything to return to menu ====================" ) menu()
def wallet_stats(d, wallet): jumbo() nav() print(" ==================== Wallet: " + dic2pretty(wallet) + " ======================") print( " ==================== =Rank= ===Name=== ==Price== ==1h %== ======================" ) data = calculate(str(d[0]['btc']), str(d[0]['eth']), str(d[0]['xrp'])) btc_per = color(data[0]['btc_per']) eth_per = color(data[0]['eth_per']) xrp_per = color(data[0]['xrp_per']) print(" ==================== 1 Bitcoin $" + str(round(data[0]['btc_usd'], 2)) + " " + btc_per) print(" ==================== 2 Ethereum $" + str(round(data[0]['eth_usd'], 2)) + " " + eth_per) print(" ==================== 3 Ripple $" + str(round(data[0]['xrp_usd'], 2)) + " " + xrp_per) total = data[0]['btc_usd'] + data[0]['eth_usd'] + data[0]['xrp_usd'] print( " ----------------------------------------------------------------------------------------" ) print(" ==================== Total Value: $" + str(round(total, 2)) + " ======================") print(" ") raw_input( " ================== Enter anything to return to menu ===================" ) menu()
def getRecipeInformation(): _collectedIngredients = [] try: if not (os.path.isdir(_workingDir + "/Recipes")): createWorkingDirs() except Exception as error: print(error) _recipeName = raw_input("What is the recipe name?\n") print "\n\nEnter a blank line to continue\n" print "Enter the ingredients one per line." while True: _inputFromUser = raw_input() if _inputFromUser: _collectedIngredients.append(_inputFromUser) else: break createNewRecipe(_recipeName, _collectedIngredients)
def AddTitulo(self): busca = sd_times_pb2.Time() times = proxy.List(busca) try: print "\n###################################" for time in times.time: print "ID:", time.id," Nome:", time.nome print "Titulos: ", time.titulos print "###################################\n" except ValueError: print "\nNão foi possivel consultar o estoque\n" ID = int(raw_input("Informe o ID do time a ser alterado: ")) menino_burro = True for time in times.time: if ID == time.id: alterar = time menino_burro=False if menino_burro: print "\n\nQueridão informe um ID válido\n\n" else: titulo = raw_input("Informe o novo Titulo: ") alterar.titulos = alterar.titulos + " : " + titulo resp = proxy.AddTitulo(alterar) if resp == "true": print "\nTime atualizado com sucesso\n" else: print "\nDeu erro\n"
def generic_enumerator_multiattributes_dfs(arr_data,arr_types,refinement_index_arr,depthmax_arr,configuration,refinement_index_attr=0,bitwise=None,stats=None): #TODO! yielded_item=value_to_yield(arr_data,arr_types,refinement_index_attr,refinement_index_arr) if yielded_item not in configuration['skip_list'] : if yielded_item is not None : yield yielded_item,bitwise,stats bitwiseConfig=configuration['bitwise'] if (configuration['bitwise'] is not None) else bitwise statsConfig=configuration['stats'] if (configuration['stats'] is not None) else stats closingConfig=configuration['closing'] if (configuration['closing'] is not None) else arr_data closingRefinConfig=configuration['closing_refin'] if (configuration['closing_refin'] is not None) else refinement_index_arr configuration['stats']=None configuration['bitwise']=None configuration['closing']=None configuration['closing_refin']=None closingRefinConfig=[(closingRefinConfig[0][0],refinement_index_arr[0][1])] print closingRefinConfig raw_input('...') #print closingRefinConfig if yielded_item not in configuration['skip_list']: for actual_refin in range(refinement_index_attr,len(arr_data)): #childs=children_generic(arr_data, arr_types,refinement_index_arr,depthmax_arr,configuration, actual_refin) childs=children_generic([closingConfig[i] if closingConfig[i] is not None else arr_data[i] for i in range(len(arr_data))], arr_types, [closingRefinConfig[i] if closingRefinConfig[i] is not None else refinement_index_arr[i] for i in range(len(refinement_index_arr))],depthmax_arr,configuration, actual_refin) for pos in range(len(childs[0])): for p,psg_bitwise,psg_stats in generic_enumerator_multiattributes_dfs(childs[0][pos]+arr_data[actual_refin+1:],childs[1][pos]+arr_types[actual_refin+1:],childs[2][pos]+refinement_index_arr[actual_refin+1:],depthmax_arr,configuration,actual_refin,bitwiseConfig,statsConfig): yield p,psg_bitwise,psg_stats
def open(self,cus): print "7.1 OPEN SA " print "7.2 OPEN CA" print "7.3 OPEN FD" x=raw_input() conn=pymysql.connect("localhost","root","","bankM5",autocommit=True) cur=conn.cursor() cur2=conn.cursor() showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime()) if x=="7.1": sq3="SELECT acc_type from account_type where cust_id= "+cus+" and acc_type='saving'" t=cur.execute(sq3) if(t==1): print("your saving account already exists") else: print("enter balance to deposit:") balance=raw_input() balance=int(balance) if(balance<0): print("invalid amount") else: balance=str(balance) sql="update cust_info set balance ='0' where cust_id = "+cus cur.execute(sql) sql2="insert into account_type values('saving','"+balance+"','5','"+cus+"')" sql3="insert into transact values('"+cus+"','saving','"+showtime+"','"+balance+"','"+balance+"','0',null,null)" cur.execute(sql2) cur.execute(sql3) print("Saving account created") elif x=="7.2": sq3="SELECT acc_type from account_type where cust_id= "+cus+" and acc_type='current'" t=cur.execute(sq3) if(t==1): print("your current account already exists") else: print("enter balance to deposit:") balance=raw_input() balance=int(balance) if(balance<5000): print("invalid amount") else: balance=str(balance) sql="update cust_info set balance ='0' where cust_id = "+cus cur.execute(sql) sql2="insert into account_type values('current','"+balance+"','5','"+cus+"')" sql3="insert into transact values('"+cus+"','current','"+showtime+"','"+balance+"','"+balance+"','0',null,null)" cur.execute(sql2) cur.execute(sql3) print("current account created") elif x=="7.3": s1=open_fd() s1.regist(cus) else: print "invalid input"
def input(prompt=None): """Wraps 'raw_input' and encodes its return value Using the encoding of sys.stdin if available, or the preferred encoding of the current locale. """ answer = raw_input() if prompt is None else raw_input(prompt) return str(answer, sys.stdin.encoding or locale.getpreferredencoding())
def testGetInput(self): self.mox.StubOutWithMock(__builtin__, 'raw_input') prompt = 'Some prompt' response = 'Some response' __builtin__.raw_input(prompt).AndReturn(response) self.mox.ReplayAll() self.assertEquals(response, cros_build_lib.GetInput(prompt)) self.mox.VerifyAll()
def ingresoUsuario(): usuario = raw_input("Ingresa tu correo: ") contrasena = raw_input("Ingresa tu contraseña: ") usuarioRegistrado = [usuario, contrasena] for a in usuarios: if usuarioRegistrado == a: print "Has ingresado con éxito." menuDatos() else: print "Datos incorrectas, ingrésalos de nuevo." print ingresoUsuario()
def nuevoUsuario(): usuario = raw_input("Ingresa tu correo: ") contrasena = raw_input("Crea tu contraseña: ") if usuario.__contains__("@") and (usuario.__contains__(".com") or usuario.__contains__(".es")): usuarioNuevo = [usuario, contrasena] usuarios.append(usuarioNuevo) print "Has creado tu usuario." ingresoUsuario() else: print "Correo invalido" nuevoUsuario()
def menuDatos(): opcion = 0 while True: print("¿A qué deseas acceder?") print("1 - La lista de estados y regiones de EEUU.") print("2 - Las estaciones meteorológicas de los estados y regiones.") print( "3 - Las estaciones meteorologicas para un estado en particular.") print( "4 - Los datos disponibles de la estación meteorologica para una estación en particular." ) print("5 - Salir") opcion = elegirOpcion() if opcion == 1: print stateJson() print "Ingrese 0 para continuar" elegirOpcion() elif opcion == 2: print allStation() print "Ingrese 0 para continuar" elegirOpcion() elif opcion == 3: station = int( raw_input( "Ingresa el n�mero del estado que deseas consultar: ")) if (station < 10): station = "0" + str(station) else: station = station print getStions(station) print "Ingrese 0 para continuar" elegirOpcion() elif opcion == 4: estado = int(raw_input("Ingresa el número del estado: ")) estacion = int(raw_input("Ingresa el número de la estación: ")) print listarEstacion(estado, estacion) print "Ingrese 0 para continuar" elegirOpcion() elif opcion == 5: print "1 - Cerrar sesion y salir" print "2 - Cerrar sesion sin salir" print "3 - No cerrar sesion" opcion = elegirOpcion() if opcion == 1: print "Llamar funcion de correo etc" print "Llamar funcion para terminar ejecucion" elif opcion == 2: print "Llamar funcion de correo etc" MenuPrincipal()
def AddTime(self): time = sd_times_pb2.Time() time.nome = raw_input("Nome:") time.data = raw_input("Data de Criação:") time.titulos = raw_input("Titulos:") teste = proxy.BuscaTime(time) if teste.nome != "lixo" : print "\n\nQueridão esse time já existe no banco\n\n" else: msg = proxy.AddTime(time) if msg == "true": print "Sucesso\n\n" else: print "Algo errado não está certo\n\n"
def read_response(prompt=''): """ Prompt the user for a response. Prints the given prompt (which should be a Unicode string), and returns the text entered by the user as a Unicode string. :param prompt: A Unicode string that is presented to the user. """ # For Python 2, raw_input takes a byte string argument for the prompt. # This must be encoded using the encoding used by sys.stdout. # The result is a byte string encoding using sys.stdin.encoding. # However, if the program is not being run interactively, sys.stdout # and sys.stdin may not have encoding attributes. # In that case we don't print a prompt (stdin/out isn't interactive, # so prompting is pointless), and we assume the returned data is # encoded using sys.getdefaultencoding(). This may not be right, # but it's likely the best we can do. # Isn't Python 2 encoding support wonderful? :-) if sys.stdout.encoding: prompt = prompt.encode(sys.stdout.encoding) else: prompt = '' enc = sys.stdin.encoding or sys.getdefaultencoding() return raw_input(prompt).decode(enc)
def get_jwt(j_name, j_pw, j_api_stack): url = j_api_stack + "/login" payload = "{\"username\":\"" + j_name + "\",\"password\":\"" + j_pw + "\"}" headers = { 'accept': "application/json; charset=UTF-8", 'content-type': "application/json; charset=UTF-8" } response = requests.request("POST", url, data=payload, headers=headers) jwt_json = json.loads(response.text) customer_number = 1 for customer in jwt_json["customerNames"]: print customer_number, customer_number += 1 print(customer["customerName"]) tenant_index = int(raw_input("Select Tenant: ")) tenant_index -= 1 tenant = jwt_json["customerNames"][tenant_index]["customerName"] payload = "{\"username\":\"" + j_name + "\",\"password\":\"" + j_pw + "\",\"customerName\":\"" + tenant + "\"}" headers = { 'accept': "application/json; charset=UTF-8", 'content-type': "application/json; charset=UTF-8" } response = requests.request("POST", url, data=payload, headers=headers) jwt_json = json.loads(response.text) return jwt_json["token"]
def open_interface(self): while 1: message = raw_input().split() try: if len(message) >= 1: if message[0].upper() == self.link_down: if (len(message) >= 3): print 'Remove link to ' + message[1] + ':' + message[2] + '. ' self.cmd_linkdown(message[1], message[2]) else: print 'Missing arguments. ' elif message[0].upper() == self.link_up: if (len(message) >= 3): self.cmd_linkup(message[1], message[2]) else: print 'Missing arguments. ' elif message[0].upper() == self.show_routes: self.cmd_showrt() elif message[0].upper() == self.show_next_hops: self.cmd_show_next_hop() elif message[0].upper() == self.close: self.cmd_close() elif message[0].upper() == self.dv_update: self.send_DV(message[1], message[2], self.dv_update) else: print 'Command not found. ' except Exception as e: print e stdout.flush()
def delete(self, args): """ Delete an application. If we wouldn't check the token here it could happen that we ask the user for confirmation and then fire the api request. If the token wasn't valid this would result in a TokenRequiredError being raised and after getting the credentials and creating a token this method would be called a second time. This would result in asking the user two times if he really wants to delete the app which is a rather bad user experience. """ if self.api.check_token(): #noinspection PyTupleAssignmentBalance app_name, deployment_name = self.parse_app_deployment_name(args.name) if deployment_name: raise InputErrorException('DeleteOnlyApplication') if not args.force_delete: question = raw_input('Do you really want to delete this ' + 'application? Type "Yes" without the quotes to delete: ') else: question = 'Yes' if question.lower() == 'yes': try: self.api.delete_app(app_name) except ForbiddenError: raise InputErrorException('NotAllowed') except BadRequestError: raise InputErrorException('CannotDeleteDeploymentExist') else: print messages['SecurityQuestionDenied'] else: raise TokenRequiredError
def addConfig(self, args): """ Adds the given variable and value to the config addon. """ app_name, deployment_name = self.parse_app_deployment_name(args.name) if not deployment_name: deployment_name = "default" if not args.variables: raise InputErrorException("NoVariablesGiven") args_variables, force = extract_flag_from_variables(args.variables, ("-f", "--force"), args.force_add) variables = parse_config_variables(args_variables, "add") try: self.api.update_addon( app_name, deployment_name, CONFIG_ADDON, CONFIG_ADDON, settings=variables, force=force ) except GoneError: # Add addon if it didn't exist. self.api.create_addon(app_name, deployment_name, CONFIG_ADDON, variables) except ThrottledError as te: # Overwrite the variable if didn't force, but type Yes question = raw_input( "{0} Do you really want to overwrite it? " 'Type "Yes" without the quotes to proceed: '.format(te.message) ) if question.lower() == "yes": self.api.update_addon( app_name, deployment_name, CONFIG_ADDON, CONFIG_ADDON, settings=variables, force=True ) return True
def run(self): aExit = False print("Escolhe o que quer fazer:") print("1 - Calcular peso de uma porcao de uma receita.") print("2 - Reiniciar os ingredientes.") print("3 - Sair.") while(not aExit): aChoix = raw_input("Opcao: ") try: # Test if it is an number aChoix = int(aChoix) if aChoix > 0 and aChoix < 4: # Test if this number belongs to one choice pass else: print("Por favor, escolher em {1, 2, 3}.") continue except: print("Por favor, entrar um numero.") continue if aChoix == 1 : # Calculate portion self.__enterRecipe() self.__displayResult(self.__model.calculatePortions()) elif aChoix == 2: # Reset local database self.__model.resetDatabase() elif aChoix == 3: # Exit aExit = True else: raise MyException("run: opcao impossivel.\n")
def RemoveTime(self): busca = sd_times_pb2.Time() times = proxy.List(busca) try: print "\n###################################" for time in times.time: print "ID:", time.id," Nome:", time.nome print "###################################" except ValueError: print "\nNão foi possivel consultar o estoque\n" #time que sera removido remove = sd_times_pb2.Time() remove.id = int(raw_input("Informe o ID do time: ")) #remove.nome = "remove" menino_burro = True for time in times.time: if remove.id == time.id: menino_burro = False if menino_burro: print "\n\nQueridão informe um ID válido\n\n" else: resp = proxy.RemoveTime(remove) if resp == "true": print "\nTime removido com sucesso\n" else: print "\nDeu erro\n"
def get_email(settings): sys.stderr.write(settings.login_name) sys.stderr.flush() email = raw_input() set_user_config(settings, email=email) return email
def undeploy(self, args): """ Undeploys the deployment, deletes the database and files. """ #noinspection PyTupleAssignmentBalance app_name, deployment_name = self.parse_app_deployment_name(args.name) if not deployment_name: raise InputErrorException('NoDeployment') if not self.does_app_exist(app_name): raise InputErrorException('WrongApplication') if not args.force_delete: question = raw_input('Do you really want to delete this ' + 'deployment? This will delete everything including files ' + 'and the database. Type "Yes" without the quotes to delete: ') else: question = 'Yes' if question.lower() == 'yes': args.force_delete = True try: self.api.delete_deployment(app_name, deployment_name) except GoneError: raise InputErrorException('WrongDeployment') else: print messages['SecurityQuestionDenied'] return True
def get_credentials(create=False): """ We use this to ask the user for his credentials in case we have no valid token. If create is true, the user is asked twice for the password, to make sure, that no typing error occurred. This is done three times after that a PasswordsDontMatchException is thrown. """ email = raw_input('Email : ') password = None for i in range(3): #noinspection PyArgumentEqualDefault password = recode_input(getpass('Password: '******'Password (again): ')) if password != password2: print messages['PasswordsDontMatch'] if i == 2: #noinspection PyExceptionInherit raise PasswordsDontMatchException() else: break else: break return email, password
def get_email(settings): sys.stderr.write(settings.login_name) sys.stderr.flush() email = raw_input() return email
def undeploy(self, args): """ Undeploys the deployment, deletes the database and files. """ app_name, deployment_name = self.parse_app_deployment_name(args.name) if not deployment_name: deployment_name = "default" if not self.does_app_exist(app_name): raise InputErrorException("WrongApplication") if not args.force_delete: question = raw_input( "Do you really want to delete deployment '{0}'? ".format(args.name) + 'This will delete everything including files and the database. Type "Yes" without the quotes to delete: ' ) else: question = "Yes" if question.lower() == "yes": args.force_delete = True try: self.api.delete_deployment(app_name, deployment_name) except GoneError: raise InputErrorException("WrongDeployment") else: print messages["SecurityQuestionDenied"] return True
def user_yes_no_query(question): sys.stdout.write('%s [y/n]\n' % question) while True: try: return strtobool(raw_input().lower()) except ValueError: sys.stdout.write('Please respond with \'y\' or \'n\'.\n')
def get_credentials(create=False): """ We use this to ask the user for his credentials in case we have no valid token. If create is true, the user is asked twice for the password, to make sure, that no typing error occurred. This is done three times after that a PasswordsDontMatchException is thrown. """ email = raw_input('Email : ') password = None for i in range(3): #noinspection PyArgumentEqualDefault password = getpass.getpass('Password: '******'Password (again): ') if password != password2: print messages['PasswordsDontMatch'] if i == 2: #noinspection PyExceptionInherit raise PasswordsDontMatchException() else: break else: break return email, password
def get_stack(): stack_number = 1 for stack in stacks: print stack_number, stacks[stack_number - 1] stack_number += 1 stack_index = int(raw_input("Select Stack: ")) stack_index -= 1 return stacks[stack_index]
def _read_from_user(): import sys if sys.version_info.major < 3: from __builtin__ import raw_input return raw_input() return input()
def totalDis(): clist = [] while True: listinpt = raw_input("Please enter city list or 'q' to quit:") clist.append(listinpt) if (listinpt == 'q'): break print stats.TotalDistance(clist)
def getdata(elements): data = [] #get data but first make a list. for i in range(elements): #we ask the programmer how many data objects are their. For each one we then ask okay whats the data. input_element = raw_input("Data: ") data.append(input_element) return data
def Map_init(): #creates the Map list Map = [] #Asks for how high and/or wide you want the map to be Map_Width = int(raw_input("What Width?")) Map_Height = int(raw_input("What Height?")) #Add as many columns as the Width for x in range(Map_Width): Map.append([]) #Add as many tiles in those columns as the Height for y in range(Map_Height): Map[x].append(Tile("Air", "Sky1")) #Return the 2D list: Map return Map
def _set_unknown_hosts_policy(self, hosts, port, ssh_config, policy): known_hosts_filename = os.path.expanduser('~/.ssh/known_hosts') if not os.path.exists(known_hosts_filename) or \ not os.path.isfile(known_hosts_filename): raise FieldConnectionError( 'Error: ~/.ssh/known_hosts file does not exist, ' \ 'please create it.') all_host_keys = paramiko.util.load_host_keys(known_hosts_filename) # build list of hosts that don't have an ssh-rsa entry in known_hosts unknown_hosts = [] for host in hosts: host_config = None if ssh_config: host_config = ssh_config.lookup(host) host_port = 22 if port: host_port = port elif host_config: host_port = host_config.get('port', host_port) # try host and [host]:port as keys to check in known_hosts as # format depends on ssh version keys_to_check = set([host, '[%s]:%d' % (host, int(host_port))]) found_keys = keys_to_check.intersection(set(all_host_keys.keys())) if not found_keys: unknown_hosts.append(host) else: host_keys = all_host_keys.get(sorted(found_keys)[0], None) rsakey = host_keys.get('ssh-rsa', None) if not rsakey: unknown_hosts.append(host) # if we found an unknown host and we're configured to reject, ask user for permission to add if unknown_hosts and (policy == RejectPolicy): unknown_hosts_str = '{' + ', '.join(sorted(unknown_hosts)) + '}' response = raw_input( 'Unknown hosts: %s. Add to known_hosts (Y/N) [N]? ' % unknown_hosts_str) if not response.upper() == 'Y': print('Quitting.', file=sys.stderr) exit(1) return AutoAddPolicy return policy
def totaltime(): clist = [] while (1): listinpt = raw_input("Please enter city list or 'q' to quit:") if (listinpt == 'q'): break else: clist.append(listinpt) print stats.TotalTime(clist)
def main(): while True: nns = raw_input("... Scala: n ? ") if nns == "": print("EOF => exit") break nn = int(nns) res = scala( nn) # @TODO: la chiamata scala() con accumulatore iniziale (=0) print("::: scala(%d) -> %r" % (nn, res))
def edit(): name = raw_input("Please enter the city you want to edit:") code = raw_input("Please enter city code if you don't want to change it enter 0:") country = raw_input("Please enter country if you don't want to change it press enter:") timezone = raw_input("Please enter timezone if you don't want to change it enter 0:") continent = raw_input("Please enter continent if you don't want to change it press enter:") popu = raw_input("Please enter population if you don't want to change it enter 0:") region = raw_input("Please enter region if you don't want to change it enter 0:") stats.editCity(name, code, country, continent, timezone, popu, region)
def ask_wallet(): nav() print( " ================== Wallet's Available ====================" ) wallets = glob.glob('wallets/*.json') empty = 0 try: print("1.) " + dic2pretty(wallets[0])) except IndexError: empty += 1 try: print("2.) " + dic2pretty(wallets[1])) except IndexError: empty += 1 try: print("3.) " + dic2pretty(wallets[2])) except IndexError: empty += 1 if empty == 3: print(" ") print("No wallets to display (Add a wallet from the Menu)") print(" ") raw_input( " ================== Enter anything to return to menu ====================" ) menu() else: answer = raw_input(" ======== Wallet Select: ") if int(answer) == 1: wallet_controller(answer, wallets[0]) elif int(answer) == 2: wallet_controller(answer, wallets[1]) elif int(answer) == 3: wallet_controller(answer, wallets[2]) else: not_cool()
def menu(): nav() print( " ==================== 1.) Check Rankings 2.) Add Wallet ======================" ) print( " ==================== 3.) Check Wallet 4.) Exit ======================" ) print( " ==================== 5.) Visit Planet Cryptoid ======================" ) foot() rank = raw_input(" ") menu_controller(rank)
def get_db_rrn(d_jwt, d_api_stack): url = d_api_stack + "/search/config" payload = "{\"timeRange\":{\"type\":\"to_now\",\"value\":\"epoch\"},\"query\":\"config where api.name = 'azure-sql-db-list' \"}" headers = { 'accept': "application/json; charset=UTF-8", 'content-type': "application/json; charset=UTF-8", 'x-redlock-auth': d_jwt } response = requests.request("POST", url, data=payload, headers=headers) sql_db_json = json.loads(response.text) sql_db_count = sql_db_json["data"]["totalRows"] db_counter = 0 while db_counter < sql_db_count: print db_counter + 1, sql_db_json["data"]["items"][db_counter]["name"] db_counter += 1 db_index = int(raw_input("Select DB: ")) - 1 return sql_db_json["data"]["items"][db_index]["rrn"]
def addConfig(self, args): """ Adds the given variable and value to the config addon. """ #noinspection PyTupleAssignmentBalance app_name, deployment_name = self.parse_app_deployment_name(args.name) if not deployment_name: raise InputErrorException('NoDeployment') if not args.variables: raise InputErrorException('NoVariablesGiven') variables = parse_config_variables(args.variables, 'add') force = args.force_add try: self.api.update_addon( app_name, deployment_name, 'config.free', 'config.free', settings=variables, force=force) except GoneError: # Add addon if it didn't exist. self.api.create_addon(app_name, deployment_name, 'config.free', variables) except ThrottledError as te: # Overwrite the variable if didn't force, but type Yes question = raw_input('{} Do you really want to overwrite it? ' \ 'Type "Yes" without the quotes to proceed: '.format(te.message)) if question.lower() == 'yes': self.api.update_addon( app_name, deployment_name, 'config.free', 'config.free', settings=variables, force=True) return True
def initializer(): if not(createWorkingDirs()): createWorkingDirs() _chooseFunction = [exit, getRecipeInformation, createWeeklyList,] print "\nMenu\n\n" + "1. Create a new recipe.\n" + "2. Get a weekly list.\n" + "0. EXIT.\n" try: _inputFromUser = int(raw_input("\nChoose your option.\n")) except ValueError: print "enter a valid option 1,2,0" initializer() if (_inputFromUser > 2) or (_inputFromUser < 0) or (isinstance(_inputFromUser, int) == False): print "enter a valid option please 1,2,0" initializer() else: _chooseFunction[_inputFromUser]()
def delete(self, args): """ Delete an application. If we wouldn't check the token here it could happen that we ask the user for confirmation and then fire the api request. If the token wasn't valid this would result in a TokenRequiredError being raised and after getting the credentials and creating a token this method would be called a second time. This would result in asking the user two times if he really wants to delete the app which is a rather bad user experience. """ if self.api.check_token(): app_name, deployment_name = self.parse_app_deployment_name(args.name) if not self.does_app_exist(app_name): raise InputErrorException("WrongApplication") if deployment_name: raise InputErrorException("DeleteOnlyApplication") if not args.force_delete: question = raw_input( "Do you really want to delete application '{0}'? ".format(app_name) + 'Type "Yes" without the quotes to delete: ' ) else: question = "Yes" if question.lower() == "yes": try: self.api.delete_app(app_name) except ForbiddenError: raise InputErrorException("NotAllowed") except BadRequestError: raise InputErrorException("CannotDeleteDeploymentExist") except GoneError: raise InputErrorException("WrongApplication") else: print messages["SecurityQuestionDenied"] else: raise TokenRequiredError
def delete(self, args): """ Delete an application. If we wouldn't check the token here it could happen that we ask the user for confirmation and then fire the api request. If the token wasn't valid this would result in a TokenRequiredError being raised and after getting the credentials and creating a token this method would be called a second time. This would result in asking the user two times if he really wants to delete the app which is a rather bad user experience. """ if self.api.check_token(): #noinspection PyTupleAssignmentBalance app_name, deployment_name = self.parse_app_deployment_name(args.name) if not self.does_app_exist(app_name): raise InputErrorException('WrongApplication') if deployment_name: raise InputErrorException('DeleteOnlyApplication') if not args.force_delete: question = raw_input('Do you really want to delete this ' + 'application? Type "Yes" without the quotes to delete: ') else: question = 'Yes' if question.lower() == 'yes': try: self.api.delete_app(app_name) except ForbiddenError: raise InputErrorException('NotAllowed') except BadRequestError: raise InputErrorException('CannotDeleteDeploymentExist') except GoneError: raise InputErrorException('WrongApplication') else: print messages['SecurityQuestionDenied'] else: raise TokenRequiredError
def __enterRecipe(self): """Procedure to set a new recipe""" aNiveau = 0; aListIngr=[] # Meta Group level of the recipe and ingredients list aCheckpoint = False # Boolean used to check the input type # Set o recipe level print("Entrar o nivel da receita :") while(not aCheckpoint): aNiveau = raw_input("Nivel: ") try: # Test if it is an number aNiveau = int(aNiveau) if aNiveau > 0 and aNiveau < 5: # Test if this number is a MetaGroup level aCheckpoint = True else: print("Por favor, escolher em {1, 2, 3, 4}.") except: print("Por favor, entrar um numero.") continue # Set ingredients and their weight of the recipe aCheckpoint = False # Used to finish ingredient set aIdx = 0 # Added ingredient index aNumero=0; aIngredient=0 # Ingredient number, ingredient object in the recipe aPoids=0; # Ingredient weight in the recipe aDeadWeight=0; # Weight of ingredients without energetic value aCheckpointIngr = False print("Entra o peso dos ingredientes sem valor energetico :") # Set weight of ingredients without energetic value while(not aCheckpointIngr): aPeso = raw_input("Peso: ") try: aPeso = int(aPeso) # Test if it is an number aDeadWeight = aPeso # set dead weight aCheckpointIngr = True except: print("Por favor, entrar um numero.") aCheckpointIngr = False print("Entrar os ingredientes et os pesos de cada:") while(not aCheckpoint): # Set ingredient while(not aCheckpointIngr): print("Entrar o numero do ingrediente "+str(aIdx+1)+": ") aNumero = raw_input("Numero: ") try: # Test if it is an number aNumero = int(aNumero) if self.__model.checkNumIngr(aNumero): # Test if the ingredient number exist aIngredient = self.__model.getIngredient(aNumero) # Set choosen ingredient aCheckpointIngr = True else: print("Por favor, escolher um numero valido.") except: print("Por favor, entrar um numero.") aCheckpointIngr = False # Set weight while(not aCheckpointIngr): print("Entrar o peso em g. do ingrediente "+str(aIdx+1)+": ") aPoids = raw_input("Peso: ") try: # Test if it is an number aPoids = int(aPoids) aCheckpointIngr = True except: print("Por favor, entrar um numero.") # Append to the ingredient recipe list aListIngr.append(IngredientRecette(aPoids, aIngredient)) # Add another ingredient ? aCheckpointIngr = False; aChoix = 0; while(not aCheckpointIngr): print("Quer adicionar um outro ingrediente ? (s/n)") aChoix = raw_input("s ou n ? ") if aChoix == "s" : # Check if the response is "s" aCheckpointIngr = True aIdx += 1 elif aChoix == "n" : # Check if the response is "n" aCheckpointIngr = True aCheckpoint = True self.__model.recette = Recipe(aNiveau, aListIngr, aDeadWeight) else: print("Por favor, entrar s ou n.") aCheckpointIngr = False
def addr(): cityCode1 = raw_input("Please enter departure airport code:") cityCode2 = raw_input("Please enter arrive airport code:") distance = raw_input("Please enter distance:") stats.addRoute(cityCode1, cityCode2, distance)
def addc(): name = raw_input("Please enter city name:") code = raw_input("Please enter city code:") country = raw_input("Please enter country:") timezone = raw_input("Please enter timezone:") continent = raw_input("Please enter continent:") NS = raw_input("Please enter 'N' or 'S':") NSV = raw_input("Please enter latitude value:") EW = raw_input("Please enter 'E' or 'W':") EWV = raw_input("Please enter longitude value:") popu = raw_input("Please enter population:") region = raw_input("Please enter region:") stats.addCity(name, code, country, continent, timezone, NS, NSV, EW, EWV, popu, region)
def raw_input(prompt): """ Catch raw input from the console """ console_print(sys.stdout, prompt, newline=False) return to_unicode(builtins.raw_input(), sys.stdin.encoding)
def removec(): cityCode = raw_input("Please enter city code:") stats.removeCity(cityCode) print stats.allCities()
def raw_input(prompt=None): if prompt: sys.stderr.write(str(prompt)) return __builtin__.raw_input()
from __builtin__ import raw_input print "How old are you:?" age = raw_input() print "How tall are you?" height=raw_input() print "How much do you weigh?" weigh=raw_input() print "SO, you are %r old,%r tall and %r heavy." %( age,height,weigh) age1=raw_input("How old are you :?") height1=raw_input("How tall are you :?") weigh1=raw_input("How much do you weigh?") print "SO, you are %r old,%r tall and %r heavy." %( age1,height1,weigh1)
totalcost() if('totaltime' in command): totaltime() if ('edit' in command): edit() if ('save' in command): stats.saveToDisk() if __name__ == '__main__': inpt = Input() stats = query() print ">> Waiting for input....." while (1): command = raw_input('>> ') if (command=='quit'): break else: print 'input: ' + command inpt.translate(command)
from __builtin__ import globals, int, raw_input def declare(member, value): attr = 'a_%s' % member globals()[attr] = value print attr, value declare('foo', 'bar') declare('name', 'xyz') def print_foo(): print a_foo def print_name(): print a_name declare('p', print_foo) declare('q', print_name) #a_p() if int(raw_input('')) > 5: a_p() else: a_q()
def raw_input(prompt): """Input one line from the console and converts it to unicode as appropriate. """ printout(prompt, newline=False) return to_unicode(__builtin__.raw_input(), sys.stdin.encoding)
def remover(): cityCode1 = raw_input("Please enter departure airport code:") cityCode2 = raw_input("Please enter arrive airport code:") stats.removeRoute(cityCode1, cityCode2)
def raw_input(prompt): printout(prompt, newline=False) return to_unicode(__builtin__.raw_input(), sys.stdin.encoding)