def select_option(self, options, find_arg=None): if self.serv_name: self.choices[self.state] = options[self.serv_path[self.state]] self._next_state() return print(f'Select your {self.state} from below choices:') if self.state == 'continent': choice = get_choice(options, find_arg, None) if choice == -1: print_quit() else: choice = get_choice(options, find_arg) if choice == -1: if self.state in self.choices: del self.choices[self.state] self._prev_state() if self.state in self.cache: self.select_option(**self.cache[self.state]) else: self.choices[self.state] = options[choice] self.serv_path[self.state] = choice name = options[choice].select_one(find_arg).text print(f"You have selected {name}.") self.cache[self.state] = {'options': options, 'find_arg': find_arg} self._next_state()
def modify_product( self, index: int, new_name: str = "", new_price: Optional[int] = None ): if not isinstance(index, int): print(f"Invalid index ({index})") return if not (0 <= index and index < self.count): print(f"Index out of range ({index})") return print(f"Chosen product: {self.products[index]}") choices = [ ("r", "Update name"), ("p", "Update price"), ("b", "Update name and price"), ("d", "Delete this product"), ] choice = get_choice(choices) if choice == "r": self.change_product_name(index, new_name) elif choice == "p": self.change_product_price(index, new_price) elif choice == "b": self.change_product_name(index, new_name) self.change_product_price(index, new_price) elif choice == "d": self.remove(index) else: print("Skipped")
def admin_flow(self): choice_list = [ 'Add Category', 'Add Product', 'Show cart of the user', 'Orders of User', 'exit' ] choice = get_choice(choice_list) if choice == 1: self.add_category() return self.admin_flow() elif choice == 2: self.add_product() return self.admin_flow() elif choice == 3: self.view_cart() return self.admin_flow() elif choice == 4: self.get_all_bill_from_user() return self.admin_flow() else: exit()
def test_choice_field(self): msg_choice = 'get_choice failed for choice key `%s`.' self.assertEqual(get_choice(self.choices, None), None) self.assertEqual(get_choice(self.choices, u'Non-existent-key'), u'Non-existent-key') for key, display in self.choices: for kwarg in ('initial', 'data'): form = self._test_form()(**{kwarg: {'choice_field': key}}) self.assertEqual(get_choice(self.choices, key), display, msg_choice % key) self.assertEqual(get_field_data(form['choice_field']), key, self.msg_field_data % ( form.is_bound and 'bound ' or '', key)) self.assertEqual(get_field_display(form['choice_field']), display, self.msg_field_display % ( form.is_bound and 'bound ' or '', display.encode('utf8')))
def select_categories(cur_route, eng_name): cur_engine = [ eng for eng in shared.ENGINES_DATA if eng["name"] == eng_name ][0] categories = cur_engine["categories"] cat_names = [c["name"] for c in categories] print("Following categories are available") print(cat_names) chosen_cat = utils.get_choice(inp_string="Choose category: ", validator=lambda c: c in cat_names) return path_join(cur_route, chosen_cat)
def load_from_file(self, filename: str = DEFAULT_PRICELIST_PATH): """ Load products' information from `filename` to this instance """ try: with open(filename, "r") as price_list: self.products = json.load(price_list, object_hook=decode_product) print(f"Data loaded from {filename}") except FileNotFoundError: choices = construct_poll(["y", "n"], [f"Create {filename}", "Abort"]) choice = get_choice(choices) if choice == "y": self.save_to_file(filename)
def get_exclude(): exclude = [] options = ['current', 'minutely', 'hourly', 'daily', 'alerts', 'Return'] while options: print( '\nSelect any types of weather data to exclude from the API call.\n' 'Choose the Return option once you are done.') choice = utils.get_choice(options) if choice == 'Return': break exclude.append(choice) options.remove(choice) # separate choices by comma except last one exclude_str = '' for data in exclude: exclude_str += data + ',' exclude_str = exclude_str[:-1] if exclude_str == '': return None else: return exclude_str
def add_product(self, name: str, price: int): """Add product to the database""" similar_product_indices = self.search(name) if len(similar_product_indices) == 0: self.products.append(Product(name, price)) return similar_products = self.get_products(similar_product_indices) similar_product_names = list(map(lambda p: p.name, similar_products)) choices = construct_poll( [*similar_product_indices, "n"], [*similar_product_names, "Add as new product"], ) choice = get_choice(choices, "Similar products") if choice == "n": self.products.append(Product(name, price)) elif isinstance(choice, int): self.modify_product(choice, name, price) else: print("Skipped")
def get_engines_route_input(cur_route="", route_key=""): engines_data = api.make_authenticated_request(url="engine") shared.ENGINES_DATA = engines_data utils.colorprint("The following types are available:", foreground=Fore.BLUE) print("1. Credentials \n2. AWS \n3. SSH") choice = utils.get_numerical_choice("Enter choice: ", start=1, end=3) chosen_type = "" if choice == 1: chosen_type = "kv" elif choice == 2: chosen_type = "aws" elif choice == 3: chosen_type = "ssh" utils.colorprint("The Following Engines are available:", foreground=Fore.BLUE) chosen_type_engines = [e for e in engines_data if e["type"] == chosen_type] eng_names = [e["name"] for e in chosen_type_engines] print(eng_names) chosen_eng = utils.get_choice(inp_string="Enter Engine Name: ", validator=lambda ee: ee in eng_names) if chosen_type == "kv": chosen_type = "creds" return f"{chosen_type}/{chosen_eng}"
def main(): while True: options = ['Use PyOWM module', 'Standard HTTP request', 'Exit program'] print('\nHow do you want to use the API?') choice = utils.get_choice(options) if choice == options[0]: use_module = True elif choice == options[1]: use_module = False elif choice == options[2]: sys.exit() # get a module or json response from api response = api_call(use_module) if response == None: continue # using module to parse data if use_module: print("\nThe current weather at the given coordinates:") print('Status: ' + str(response.detailed_status)) print('Temperature: ' + str(response.temperature('fahrenheit')['temp']) + ' degrees Fahrenheit') print('Cloud coverage: ' + str(response.clouds) + '%') print('Wind: ' + str(response.wind()['speed']) + 'm/s at ' + str(response.wind()['deg']) + ' degrees') print('Humidity: ' + str(response.humidity) + '%') # using json to parse data else: # write json response to a file with open('results.json', 'w') as results_file: # converts the response dictionary to a json object formatted_json = json.loads( json.JSONEncoder().encode(response)) json.dump(formatted_json, results_file, indent=4)
def get_coords(): options = ['Latitude & Longitude', 'City Name'] print('\nChoose a method for entering a location.') choice = utils.get_choice(options) # latitude/longitude entry if choice == options[0]: lat = input('Enter latitude: ') lon = input('Enter longitude: ') try: lat = float(lat) lon = float(lon) except ValueError: print('Invalid coordinates.') return None return [lat, lon] # try to obtain latitude/longitude by a unique city name elif choice == options[1]: city_name = input('Enter city name: ') locations = cities.locations_for(city_name) # city name is not unique if len(locations) > 1: # print coordinates of cities with the given name print('Too many cities have this name. Choose a different option.') print('Here are the locations found:') print('id, latitude, longitude') for city in locations: print(f'{city.id}, {city.lat}, {city.lon}') return None # city not found elif len(locations) == 0: print('No cities found by this name. Choose a different option.') return None # exact city match found else: city = locations[0] return [city.lat, city.lon]
def create_character(): utils.clear_screen() print( "Chose your culture by typing it. You can view information on a culture by choosing the appropriate number option.\n" ) print("+-------------+") print("| 1. Svec |") print("| 2. Baeskens |") print("| 3. Thurber |") print("| 4. Dueck |") print("| 5. Obeng |") print("| 6. Bostian |") print("+-------------+\n") choice = input() attribute = "" octave2 = 0 octave1 = 2 try: choice = int(choice) # if no error, show description of culture and ask if they want to chose if (choice == 1): print( "\nThe Svec\n\nRuthless Vikings descendants of adventurers from Norway. Known for their ruthless\nstyle of war, they prefer bloodshed over diplomacy for peace.\n\n+20% Strength\n" ) time.sleep(2.5) choice = utils.get_choice( "Do you want to chose this culture? (y,n) ") if (choice): octave2 += 1 octave1 += 3 attribute = utils.Attribute("Svec", "strength", 20) else: utils.clear_screen() return create_character() elif (choice == 2): print( "\nThe Baesken\n\nPeaceful fisherman from the rivers of the Northwest. Prideful of their vast\ndelicacies, they strive to be better than everyone else at cooking.\n\n+20% Cooking\n" ) time.sleep(2.5) choice = utils.get_choice( "Do you want to chose this culture? (y,n) ") if (choice): octave2 += 2 octave1 += 1 attribute = utils.Attribute("Baeskens", "cooking", 20) else: utils.clear_screen() return create_character() elif (choice == 3): print( "\nThe Thurber\n\nHardened blacksmiths from the mountains, they are strong and persevere.\nBe sure to know they won't back down without a fight, as they will always be ready.\n\n+20% Strength\n" ) time.sleep(2.5) choice = utils.get_choice( "Do you want to chose this culture? (y,n) ") if (choice): octave2 += 3 octave1 += 1 attribute = utils.Attribute("Thurber", "strength", 20) else: utils.clear_screen() return create_character() elif (choice == 4): print( "\nThe Dueck\n\nFarmers from the hills of Italy, they are steadfast towards their religion.\nThey will fight to protect their faith, by any means, at any cost.\n\n+20% Charisma\n" ) time.sleep(2.5) choice = utils.get_choice( "Do you want to chose this culture? (y,n) ") if (choice): octave2 += 2 octave1 += 2 attribute = utils.Attribute("Dueck", "charisma", 20) else: utils.clear_screen() return create_character() elif (choice == 5): print( "\nThe Obeng\n\nMasters of building, they come from the valleys of China. Skilled craftsman, they\nconstruct the most engineered buildings to date.\n\n+20% Intelligence\n" ) time.sleep(2.5) choice = utils.get_choice( "Do you want to chose this culture? (y,n) ") if (choice): octave2 += 1 octave1 += 4 attribute = utils.Attribute("Obeng", "intelligence", 20) else: utils.clear_screen() return create_character() elif (choice == 6): print( "\nThe Boastian\n\nComing from the foothills of Spain, these folk love dancing and well, showing off.\nBut when the time is right, they'll be as strong as giants.\n\n+20% Tactics\n" ) time.sleep(2.5) choice = utils.get_choice( "Do you want to chose this culture? (y,n) ") if (choice): octave2 += 5 octave1 += 3 attribute = utils.Attribute("Boastian", "tactics", 20) else: utils.clear_screen() return create_character() else: print("\nPlease supply a valid choice.") time.sleep(3) utils.clear_screen() return create_character() return ((octave1, octave2), attribute) except ValueError: print("\nPlease supply a valid choice.") time.sleep(2) utils.clear_screen() return create_character()
def get_units(): options = ['imperial', 'metric', 'standard'] print('\nChoose the type of measurement units to use.') choice = utils.get_choice(options) return choice
def customer_flow(self): choice_list = ['Buy(Show category list)', 'Show Cart', 'exit'] choice = get_choice(choice_list) if choice == 1: self.list_all_categories() choice_list = ['Show Products', 'Main Menu', 'exit'] choice = get_choice(choice_list) if choice == 1: category_id = click.prompt(click.style( 'Enter category id to see list of products', fg='yellow'), type=int) self.list_all_products(category_id) choice_list = ['Detail of product', 'Main Menu', 'exit'] choice = get_choice(choice_list) if choice == 1: product_id = click.prompt(click.style( 'Enter product id to see its details', fg='bright_blue'), type=int) self.detail_product(product_id) choice_list = [ 'Do you want to add this item to the cart', 'Main Menu' ] choice = get_choice(choice_list) if choice == 1: self.add_to_cart(product_id) self.view_cart() choice_list = [ 'Buy', 'Remove item from the cart', 'Main Menu' ] choice = get_choice(choice_list) if choice == 1: self.buy_from_cart() elif choice == 2: self.remove_from_cart() self.view_cart() return self.customer_flow() else: return self.customer_flow() else: return self.customer_flow() elif choice == 2: return self.customer_flow() else: exit() elif choice == 2: return self.customer_flow() else: exit() elif choice == 2: self.view_cart() choice_list = ['Buy', 'Remove item from the cart', 'Main Menu'] choice = get_choice(choice_list) if choice == 1: return self.buy_from_cart() elif choice == 2: self.remove_from_cart() self.view_cart() return self.customer_flow() else: return self.customer_flow() else: exit()