def handle(self, text): if text == '': return if text == 'clear': clear_screen() return try: key = text.split(' ')[0].lower() if key in self.handler: self.handler[key](text) else: self.handler['others'](text) except KeyError as e: print('[%s] command fail' % text) logger.exception(e) except TypeError as e: logger.exception(e) except CommandError as e: logger.exception(e) except FireExit as e: pass # if e.code is not 0: # logger.exception(e) except BaseException as ex: logger.exception(ex) pass
def change_password(korisnik): while True: clear_screen() print(' === PROMENA LOZINKE === ') try: new_password = getpass.getpass('Unesite novu lozinku: ').strip() KorisnikLogic.validate_password(new_password) while True: password_confirmation = getpass.getpass( 'Potvrdite lozinku: ').strip() if new_password == password_confirmation: break else: print('Unete lozinke se ne poklapaju, pokusajte ponovo') success = KorisnikLogic.change_password(korisnik, new_password) if success: print('Uspesno ste promenili lozinku') else: print( 'Doslo je do greske prilikom promene lozinke, pokusajte kasnije' ) input() return except InvalidKorisnikInfoError as e: print(' * Greska:', e) if not try_again(): return
def player_turn(self, player, opposition): # a players turn # # Keyword arguments: # player - the current player instance # opposition - the opposing player instance # ### utils.clear_screen() print("%s, it's your turn:" % player.player_name) input("Press Enter to continue...") utils.clear_screen() print("\n") print("Your shots") player.board.print_opp_board(opposition.ship_coordinates, player.player_shots) print("Your board") player.board.print_player_board(player.ship_coordinates, opposition.player_shots) print("\n") print("%s has %i hits, and %s has %i hits" % (self.player_1.player_name, self.player_1.number_of_hits, self.player_2.player_name, self.player_2.number_of_hits)) player.pew_pew(opposition.ship_coordinates) if player.number_of_hits > 5: self.game_won = True self.is_winner = player.player_name else: player.is_turn = False opposition.is_turn = True
def game(): ''' The game ''' sticks = 21 while sticks != 1: clear_screen() print(f'Currently there are {sticks} sticks') # ensure user enters an integer try: user_choice = int(input('Choose from 1 to 4 sticks\n>>> ')) except ValueError: print('You have entered a non integer value') return 'Game Aborted' # ensure user choice is valid try: assert user_choice in (1, 2, 3, 4) except AssertionError: print('You can choose only between 1 to 4 sticks') return 'Game Aborted' # calculate remaining no. of sticks sticks -= user_choice print(f'Now we have {sticks} sticks left. Its my turn now') # strategy to win computer_choice = 5-user_choice sticks -= computer_choice print(f'I have picked {computer_choice} sticks') print('\nThere is only one stick left. By the rule, you loose 😔') print('Better Luck next time !\n') return 'Game Ended'
def main(self): db_connection = MyCart.get_db_credentials() self.create_db_connection(**db_connection) self.create_all_table_if_not_exists() authentication_token = self.login() if authentication_token: self.user_id = authentication_token['user_id'] self.is_admin = authentication_token['is_admin'] user_name = authentication_token['user_name'] print_successful_login_message(user_name) cart = Cart() if self.is_admin: self.admin_flow() else: self.customer_flow() else: print_unsuccessful_login_message() if retry(): clear_screen() return self.main() else: quit()
def search_by_date_range(cls): """ List tasks in date range """ utils.clear_screen() print("Please enter start and end dates to search for a date range:\n") total = 0 while total == 0: start_date = None end_date = None while not start_date: print("Start Date:") start_date = utils.get_date() while not end_date: print("End Date:") end_date = utils.get_date() tasks = Task.select().where((Task.date > start_date) & (Task.date < end_date)).order_by( Task.date.desc()) print("No results found... Please retry.") total = len(tasks) else: return { 'tasks': tasks, 'start_date': start_date, 'end_date': end_date, }
def game_init_menu(num_players): selected_characters = [] index = 1 player_index = 1 available_characters = [Bookworm, Worker, Whatsapper, Procrastinator] clear_screen() print("***********\tAVAILABLE CHARACTERS\t***********") for character in available_characters: p = character() print(str(index) + ".- " + "The " + str(p)) index += 1 print("********************************************************\n") while player_index <= num_players: option_menu = sanitize_inputs(message="Player " + str(player_index) + ". Please, choose a character(1-4): ", valid_input=[1, 2, 3, 4], valid_cast=int) player = available_characters[option_menu - 1] selected_characters.append(player()) player_index += 1 index = 1 for character in selected_characters: print(str(index) + ".- " + str(character)) index += 1 return selected_characters
def action_exit(): clear_screen() print("Thank you for using Delegate Helper!") print("Have a great day :)") print("\n") print(bold("Exited successfully!")) exit(0)
def search_by_date(self): """Prompt for selection of valid date & display associated entries""" # Using set comprehension to eliminate duplicates, # but converting to list for sorting dates = list({entry.date for entry in self.entries}) dates.sort() print("*** Lookup by Date ***\n") print("Select a date the view all entries on that date...") for i in range(len(dates)): print(f'[{i}] {dates[i]}') print("[B] <--BACK---") while True: try: selection = input(">>> ") if selection.upper() == "B": break selection = int(selection) if int(selection) not in range(len(self.entries)): raise ValueError except ValueError: print("Invalid input. Please choose from the menu.") else: clear_screen() selected_date = dates[selection] print(f"*** All tasks for {selected_date} ***\n") for entry in self.entries: if entry.date == selected_date: print(f'{entry}\n') break
def start_game_loop(pb1, pb2, pb1_shiplocs, pb2_shiplocs, players): keep_going = True play_again = True ship = '' message = '' clear_screen() tracking_board_player1 = Board('TRACKER') tracking_board_player2 = Board('TRACKER') pb1.append(tracking_board_player1.build_blank_board()) pb2.append(tracking_board_player2.build_blank_board()) while keep_going == True: for player_pos, player in enumerate(players): play_again = True while play_again == True: start_coords = get_coordinates(ship, player, message) if player_pos == 0: h_o_m = check_hit_or_miss(start_coords, player, pb2[0], pb1[1], pb2_shiplocs) pb2[0], pb1[1], play_again = h_o_m display_board(player, 'PRIMARY', pb1[0]) display_board(player, 'TRACKER', pb1[1]) else: h_o_m = check_hit_or_miss(start_coords, player, pb1[0], pb2[1], pb1_shiplocs) pb1[0], pb2[1], play_again = h_o_m display_board(player, 'PRIMARY', pb2[0]) display_board(player, 'TRACKER', pb2[1])
def edit_entry_view(entry, password): # pylint: disable=inconsistent-return-statements clear_screen() title_string = "Title (press {} when finished)".format(FINISH_KEY) print(title_string) print("=" * len(title_string)) readline.set_startup_hook(lambda: readline.insert_text(entry.title)) try: title = sys.stdin.read().strip() finally: readline.set_startup_hook() if title: entry_string = "\nEnter your entry: (press {} when finished)".format( FINISH_KEY) print(entry_string) readline.set_startup_hook(lambda: readline.insert_text(entry.content)) try: data = sys.stdin.read().strip() finally: readline.set_startup_hook() if data: if input("\nSave entry (y/n) : ").lower() != 'n': edit_entry(entry, title, data, password) else: print("No title entered! Press Enter to return to main menu") input() clear_screen() return False
def store_username(username): """Add the username to the database.""" user = User.create(username=username) clear_screen() __ = input("{}, welcome to the Work Log program. ".format(username) + "Press 'Enter' to continue. ") return user
def get_player_guess(self, player, opponent): """Prompt player for guess.""" while True: user_input = input("\n{}, enter a location: ".format( player.name)).strip() guess = user_input.upper() # Validate guess if guess in player.guesses: clear_screen() print("\nERROR: {} has already been guessed! Please try again." "".format(guess)) print("Here are the guesses you have made so far: " + ", ".join(player.guesses)) player_view = opponent.board.get_player_view(opponent.ships) opp_view = player.board.get_opp_view(player.ships) # Print both boards with name labels self.print_all_boards(player, opponent, player_view, opp_view) elif self.validate_coord(guess): return guess else: clear_screen() print( "\nERROR: {} is not a valid guess. Please enter the LETTER" " and NUMBER as one word. Spaces before or after input, and " "both upper and lowercase characters are allowed.".format( guess)) player_view = opponent.board.get_player_view(opponent.ships) opp_view = player.board.get_opp_view(player.ships) # Print both boards with name labels self.print_all_boards(player, opponent, player_view, opp_view)
def date_search(): """Seach for past entries based on a date range""" utils.clear_screen() print("========== Find a Worklog Entry by Date Range ==========") # Get date ranges from user print("\nEnter dates in the MM/DD/YYYY Format\n") while True: try: start_date = input("Enter a start date: ") utc_start_date = utils.utc_date(start_date) except ValueError: print("Please enter a valid date as MM/DD/YYYY") else: break while True: try: end_date = input("Enter an end date: ") utc_end_date = utils.utc_date(end_date) except ValueError: print("Please enter a valid date as MM/DD/YYYY") else: break # Find rows that have dates within the date rangen result = [] with open("tasklogs.csv") as csvfile: reader = csv.DictReader(csvfile) for row in reader: date_utc = utils.utc_date(row["Task Date"]) if utc_start_date <= date_utc <= utc_end_date: result.append(row) if result == []: failed_search() else: success_search(result)
def delete_row(row_to_del): """Deletes a row from the csv log based on user's request""" filename = "tasklogs.csv" temp_file = "task_temp.csv" with open(filename) as csvin, open(temp_file, "w") as csvout: reader = csv.DictReader(csvin) fieldnames = ["Task Name", "Task Date", "Task Date UTC", "Task Time", "Task Note", "Task Timestamp"] writer = csv.DictWriter(csvout, fieldnames=fieldnames) writer.writeheader() for row in reader: if row == row_to_del: break else: writer.writerow(row) writer.writerows(reader) os.remove(filename) os.rename(temp_file, filename) utils.clear_screen() print("========= Log Has Been Deleted =========\n\n") print("[M]ain Menu [A]dd log [S]earch log [Q]uit program\n") get_choice = input("Choose an option: ") if get_choice.upper() == "M": work_log.main_menu() elif get_choice.upper() == "A": add_task.Task() elif get_choice.upper() == "S": search_options() elif get_choice.upper() == "Q": utils.quit_program()
def action_cross_degrees(): clear_screen() degrees = api.get_degrees() degs = sorted( [d for d in degrees if d.acronym[0] == 'M' or d.acronym[0] == 'L'], key=lambda d: d.acronym) degree_menu = SelectMenu({}, message='Degree Selection Menu') opt = 0 choices = [] for deg in degs: opt += 1 choices.append(f"{opt}. {deg}") choices.append("0. Confirm Selection") degree_menu.add_choices(choices) selections = [] result = degree_menu.select() while result != "0. Confirm Selection": index = choices.index(result) if degs[index].id not in selections: selections.append(degs[index].id) degree_menu.choices[index] += "«" else: selections.pop(selections.index(degs[index].id)) degree_menu.choices[index] = degree_menu.choices[index][:-1] result = degree_menu.select() change_selected_degrees(selections) return cross_menu.select_action()
def log_entry(self, task_object): task_data = vars( task_object ) # represents a dictionary of all Task instance attributes duplicated = test_duplicate_entry( task_data ) # tests the dictionary against each entry in the csv file if duplicated: user_decision = input( "That task is already recorded. Would you like to enter a new task (Y/N): " ).upper() else: write_entry(task_data) user_decision = input( "\nWould you like to enter a new task (Y/N): ").upper() while user_decision not in ['Y', 'N']: user_decision = input( "\nCannot read input. To add a new entry press [ Y ]; to go back to the main menu press [ N ]: " ).upper() if user_decision == "Y": clear_screen() add_new_task = Task() self.log_entry(add_new_task) else: clear_screen() return # go back to the main menu
def search_by_string(self): """Search within 'name' and 'note' for all entries, by string Prompts the user to input a string. The user's input will be used as the search criterion. Searching is case-sensitive. Partial matches are considered hits. This actually re-uses regex search, since a string is just a very specific regex match criterion. """ print("*** String Search ***\n") print("Enter a search string.\n") print("- NAME and NOTE will be searched for all tasks -") print( "- Searching IS case-sensitive, but partial matches will be returned -\n" ) while True: try: search_string = input(">>> ") results = self.regex_entry_search(search_string) except re.error: print("Couldn't parse search query. Please try again.") else: clear_screen() print( f"Found {len(results)} matches for string \"{search_string}\"...\n" ) self.print_selected_entries(results) break
def exact_date(self): clear_screen() search_item = "date" while True: date_object, log_entries = Task.store_date(self), compile_log() provided_date = date_object.strftime("%Y-%m-%d") matched_dates = list( filter(lambda x: x['date'] == provided_date, log_entries)) #filters tasks if not matched_dates: empty_results = no_results(search_item) if empty_results: continue # prompt for a new date input if 0 results are generated from the previous date break # prompt the user for a new search; N - Main Menu; Y - Search Menu else: date_criteria = display_results( matched_dates, search_item ) # iterates over the entries that meet user's criteria if not date_criteria or date_criteria: break # prompt the user for a new search; N - Main Menu; Y - Search Menu
def view_entry(entry, password): # pylint: disable=inconsistent-return-statements title = entry.title data = crypto.decrypt(entry.content, password) if entry.sync: clear_screen() print("Checking for updates on note with Google Drive......") download_drive(entry, title, data, password) # entry = m.Note.get(m.Note.title == title) # data = decrypt(entry.content, password) clear_screen() puts(colored.yellow(title)) puts(colored.blue("=" * len(title))) puts(colored.yellow(data)) puts(colored.cyan('e) edit entry')) puts(colored.cyan('d) delete entry')) puts(colored.cyan('v) view previous versions')) puts(colored.cyan('q) to return to view entries')) next_action = input('Action: [e/d/v/q] : ').lower().strip() if next_action == 'd': return delete_entry(entry) if next_action == 'e': return edit_entry_view(entry, password) if next_action == 'v': return view_previous_versions(entry, password) if next_action == 'q': return False
def loop(self): while True: clear_screen() entity = self.entity_load_funcion() if entity is None: print('Objekat se ne moze ucitati') input() entity_info = self.entity_info_function.__func__(entity) print(f'''\ {self.heading} {entity_info} __________ Akcije __________ ''') for counter, akcija in enumerate(self.ACTION_DICTIONARY): print(f' {counter + 1}) {akcija[0]}') print(' X) Vrati se nazad') print('____________________________') akcija = input('Akcija: ').strip().upper() if akcija == 'X': return elif akcija.isdigit(): self.process_action(entity, int(akcija) - 1) else: print(' * Nevalidna vrednost akcije') input()
def _main_menu(first_time): utils.clear_screen() mygame = None if first_time: print("Welcome to {}".format(con.GAME_NAME)) choices = ', '.join(con.MAIN_MENU_CHOICES) print("Here are your choices: {}".format(choices)) user_input = input("main loop > ").lower().strip() while not user_input in con.MAIN_MENU_CHOICES: print("Sorry, I didn’t recognize that: {}".format(user_input)) user_input = input("> ").lower().strip() # --------------------------------------------- print("user input: {}".format(user_input)) if user_input == "new": char_name, char_kind = utils.get_player_info() utils.save_char_info(char_name, char_kind) s = "{} the {}".format(char_name.upper(), char_kind.upper()) print("You have created a character: {}".format(s)) print("Now let's set up a world for you ...") utils.copy_directory(char_name, char_kind) mygame = Game(char_name, char_kind, zone_name="world") elif user_input == "load": print("LOAD needs to be implemented.") elif user_input == "quit": return False else: s = "Sorry, I don't recognize that: {}".format(user_input) raise ValueError(s) input("Press <Enter> to continue.") utils.clear_screen() mygame.game_loop() return True
def edit_log(log_to_edit): """Allows user to edit a log entry""" utils.clear_screen() lookup = list(log_to_edit.values()) logger.info("Lookup list = {}".format(lookup)) # Present user with a menu of options for the edit print(""""You have chosen to edit the following tasK:\n [A] Task Name: {}\n [B] Task Date: {}\n [C] Task Time: {}\n [D] Task Note: {}\n """.format(lookup[0], lookup[1], lookup[3], lookup[4])) # Get user's edit value get_choice = input("Enter an option to edit: ") try: if get_choice.upper() == "A": get_name = input("Enter a new task name: ") lookup[0] = get_name elif get_choice.upper() == "B": get_date = input("Enter a new task date as MM/DD/YYYY: ") lookup[1] = get_date elif get_choice.upper() == "C": get_time = int(input("Enter a new time: ")) lookup[3] = get_time elif get_choice.upper() == "D": get_note = input("Enter a new task note: ") lookup[4] = get_note else: raise ValueError except ValueError: print("Whoops! Please enter a valid option to edit.") logger.info("After edits, log will be: {}".format(lookup)) # Write user edit to log in csv file filename = "tasklogs.csv" temp_file = "task_temp.csv" with open(filename) as csvin, open(temp_file, "w") as csvout: reader = csv.DictReader(csvin) fieldnames = ["Task Name", "Task Date", "Task Date UTC", "Task Time", "Task Note", "Task Timestamp"] writer = csv.DictWriter(csvout, fieldnames=fieldnames) writer.writeheader() for row in reader: if row["Task Timestamp"] == lookup[5]: writer.writerow({ "Task Name": lookup[0], "Task Date": lookup[1], "Task Time": lookup[3], "Task Note": lookup[4] }) break else: writer.writerow(row) writer.writerows(reader) os.remove(filename) os.rename(temp_file, filename) display_edit(lookup)
def gen_clue(self, turn, swap_teams, send_clue): try: if swap_teams: self.switch_teams() cover_locs = [] for cover in self.driver.find_elements_by_class_name('coverToken'): cover_locs.append(cover.location) words = [] for tile in self.driver.find_elements_by_class_name('card'): if not tile.text: continue classes = tile.get_attribute('class') tag = WebDriver.get_tag_from_classes(classes) if tag == Tags.EMPTY: classes = tile.find_elements_by_class_name( 'cardImage')[0].get_attribute('class') tag = WebDriver.get_tag_from_classes(classes) words.append(Word(tile.text, tag)) for cover_loc in cover_locs: if does_intersect(cover_loc, tile.location): words[-1].guessed = True break words = words[::-1] board = Board(board=words) clear_screen() print(board.to_string()) print('\nThinking...') word, amnt = engine.gen_word(board.get_summary(turn)) print(f'\nYour clue is: {word}, {amnt}') print(f'given clues: {engine.given_clues}') if not send_clue: return input_boxes = self.driver.find_elements_by_name('clue') if len(input_boxes) == 0: print('input box not found') return input_boxes[0].send_keys(word) amount_box = self.driver.find_element_by_class_name( 'numSelect-wrapper') amount_box.click() time.sleep(1.0) [ b for b in amount_box.find_elements_by_class_name('option') if b.text == str(amnt) ][0].click() time.sleep(0.5) self.driver.find_element_by_class_name('jsx-1785461593').click() except Exception as ex: print(f'Exception occured in generating a clue -> {ex}')
def search_choice(user_choice): """Launch search method based on user's choice""" while True: try: if user_choice.upper() == "A": date_search() elif user_choice.upper() == "B": date_counter() elif user_choice.upper() == "C": time_search() elif user_choice.upper() == "D": exact_search() elif user_choice.upper() == "E": pattern_search() elif user_choice.upper() == "F": work_log.main_menu() elif user_choice.upper() == "G": utils.quit_program() else: raise ValueError except ValueError: logger.warning("Exception. User typed {} for a search method." .format(user_choice)) print("\nYou entered an invalid option") repeat = input("Press 'any key' to try again or type QUIT to leave: ") if repeat.upper() == "QUIT": utils.clear_screen() utils.quit_program() else: utils.clear_screen() search_options() logger.info("User selected {} to fix search error.".format(repeat))
def add_entry_ui(): """Add a note""" title_string = "Title (press {} when finished)".format(FINISH_KEY) print(title_string) print("=" * len(title_string)) title = get_input() if title: entry_string = "\nEnter your entry: (press {} when finished)".format( FINISH_KEY) print(entry_string) data = get_input() if data: if input("\nSave entry (y/n) : ").lower() != 'n': while True: password = getpass.getpass("Password To protect data: ") if not password: print("Please input a valid password") else: break password_to_store = key_to_store(password) encryped_data = encrypt(data, password) add_entry(encryped_data, title, password_to_store) print("Saved successfully") else: print("No title entered! Press Enter to return to main menu") input() clear_screen() return
def update_score(self, facedown, faceup, guess): if self.guesser_won(facedown, faceup, guess): self.player.add_point() else: self.dealer.add_point() if not self.player.isRobot: clear_screen()
def delete_entry(self): clear_screen() read_data = compile_log() string_query = input( "\nProvide the task that you want to remove from the log: ").title( ).strip() while not string_query: string_query = input("Cannot delete a task with an empty query: ") entries_present = filter(lambda x: x['task'] == string_query, read_data) if not entries_present: print( "The provided information doesn't exist in the log. You will be redirected to the Main Menu." ) return remove_entry = None for _task in entries_present: delete_row = input( "Do you want to delete the following: {date} / {task} / {details}\n\n>>>" .format(**_task)).upper() while delete_row != "Y": delete_row = input( "To select this row to be deleted please press [ Y ]: " ).upper() remove_entry = _task clear_screen() break if not remove_entry: print( "No entry was selected to be deleted. You will be redirected to the Main Menu." ) return else: with open("worklog_entries.csv", 'r') as read_log, open("updated_entries.csv", 'w') as write_log: fieldnames = ["date", "task", "details", "minutes"] data_writer = csv.DictWriter(write_log, fieldnames=fieldnames) data_reader = csv.DictReader(read_log, fieldnames=fieldnames) for unique in data_reader: if unique != _task: data_writer.writerow(unique) shutil.copyfile("updated_entries.csv", "worklog_entries.csv") os.remove("updated_entries.csv")
def print_options(self, clear=False): """Print each Menu option key/value pair to the terminal in the format "[key]) [value]" """ if clear: clear_screen() for key, value in self.options.items(): print(f"[{key}] {value}")
def main_menu(): """Displays the beginning main menu for the application""" utils.clear_screen() print("============= Welcome to the Company Worklog! =============\n") print("This program tracks events by name, date, time, and notes.\n" + "As an employee of Dunder Mifflin, please enjoy tracking every\n" + "aspect of your life.\n") utils.footer_menu()
def create_session(): sys.stdout = SlowPrinter() sys.stdout.set_mode(1) session = Session() if session.loop: clear_screen() return session exit('\nGoodbye...\n')
def login_interface(print_error): utils.clear_screen() if print_error: print(print_error) name = input("Name: ") password = input("Password: "******"name": name, "password": password }
def WIP(): utils.clear_screen() print( '' ) print( ' +-------------------------------------------------+' ) print( ' | WIP |' ) print( ' +-------------------------------------------------+' ) print( '' ) fdfdsjfs=0 input(fdfdsjfs) utils.clear_screen() return False
def print_stuff(grep): # function to choose between pretty and ugly printing sys.stdout.set_mode(0) results_begin = '\nSearch results from %s to %s:' % (start.strftime('%B %d, %Y'), end.strftime('%B %d, %Y')) + \ "\n\nStories on these days have the word '%s' in them...\n" % word if grep: # pretty printing the output (at the cost of decrypting time) try: timer_start = timer() print results_begin for i, (n, word_count, indices) in enumerate(occurrences): colored = [] date = start + timedelta(n) content = Story(session, date).decrypt() numbers = str(i + 1) + '. ' + date.strftime('%B %d, %Y (%A)') text, indices = mark_text(content, indices, jump) # precisely indicate the word in text for idx in indices: # find the word occurrences left_bound = find_line_boundary(text, idx, grep, -1) right_bound = find_line_boundary(text, idx, grep, 1) sliced = '\t' + '... ' + text[left_bound:right_bound].strip() + ' ...' colored.append(sliced) print numbers, '\n%s' % '\n'.join(colored) # print the numbers along with the word occurrences timer_stop = timer() except (KeyboardInterrupt, EOFError): sleep(CAPTURE_WAIT) grep = 0 # default back to ugly printing clear_screen() print "Yep, it takes time! Let's go back to the good ol' days..." if not grep: # Yuck, but cleaner way to print the results sys.stdout.set_mode(0) print results_begin for i, (n, word_count, _indices) in enumerate(occurrences): date = session.birthday + timedelta(n) numbers = ' ' + str(i + 1) + '. ' + date.strftime('%B %d, %Y (%A)') spaces = 40 - len(numbers) print numbers, ' ' * spaces, '[ %s ]' % word_count # print only the datetime and counts in each file sys.stdout.set_mode(1, 0.015) msg = fmt_text('Found a total of %d occurrences in %d stories!' % (total_count, num_stories), 'yellow') print '\n%s %s\n' % (SUCCESS, msg) print fmt_text(' Time taken for searching: ', 'blue') + \ fmt_text('%s seconds!' % timing, 'green') if grep: print fmt_text(' Time taken for pretty printing: ', 'blue') + \ fmt_text('%s seconds!' % (timer_stop - timer_start), 'green')
def main(): utils.clear_screen() server = ThreadedTCPServer((HOST, int(sys.argv[1])), ThreadedTCPRequestHandler, int(sys.argv[2]), sys.argv[3]) # server_thread = threading.Thread(target=server.serve_forever) # server_thread.daemon = True # server_thread.start() # server_thread.join() try: server.serve_forever() except KeyboardInterrupt: server.shutdown()
def choose_game( x ): utils.clear_screen() print ( globals.igrice[x] ) igra = globals.igrice[x] print ( '==+' + '='*100 + '+==' ) print ( ' |' + ' '*100 + '| ' ) print ( ' |' + igra['ime'].center( 100, ' ' ) + '| ' ) print ( ' |' + ' '*100 + '| ' ) print ( ' |' + ('*'*int(igra['ocjena'])).center( 100, ' ' ) + '| ' ) print ( ' |' + ' '*100 + '| ' ) print ( '==+' + '='*20 + '+' + '='*79 + '+==' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( ' |' + 'ZANR'.center( 20, ' ' ) + '|' + igra['zanr'].center( 79, ' ' ) + '| ' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( '==+' + '-'*20 + '+' + '-'*79 + '+==' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( ' |' + 'MINIMALNI CPU'.center( 20, ' ' ) + '|' + (str(igra['min_cpu']) + ' MHz').center( 79, ' ' ) + '| ' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( '==+' + '-'*20 + '+' + '-'*79 + '+==' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( ' |' + 'MINIMALNI GPU'.center( 20, ' ' ) + '|' + (str(igra['min_gra_cpu']) + ' MHz').center( 79, ' ' ) + '| ' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( '==+' + '-'*20 + '+' + '-'*79 + '+==' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( ' |' + 'MINIMALNI GPU_RAM'.center( 20, ' ' ) + '|' + (str(igra['min_gra_ram']) + ' MB').center( 79, ' ' ) + '| ' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( '==+' + '-'*20 + '+' + '-'*79 + '+==' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( ' |' + 'MINIMALNI RAM'.center( 20, ' ' ) + '|' + (str(igra['min_ram']) + ' MB').center( 79, ' ' ) + '| ' ) print ( ' |' + ' '*20 + '|' + ' '*79 + '| ' ) print ( '==+' + '-'*20 + '+' + '-'*79 + '+==' ) print ( ' |' + ' '*100 + '| ' ) print ( ' |' + ('Cijena: ' + str(igra['cijena']) + ' kn').center( 100, ' ' ) + '| ' ) print ( ' |' + ' '*100 + '| ' ) print ( '==+' + '='*100 + '+==' ) print ( '' ) print ( ' 1) Benchmark') print ( ' 0) Izlaz') choice = 0; int( input( choice ) ) if choice == 0: return False if choice == 1: print("TADAAAAA") input(x)
def display_email_wait(which_email): """ Displays a given email and waits for action on it (delete/go back). """ utils.clear_screen() print("[Subject] {0}".format(which_email["subject"])) print("[Content]") print(which_email["content"]) action = input("Would you like to [D]elete this email or go [B]ack? ") # let's delete the email if action == "D": return which_email
def main_menu(): utils.clear_screen() print( '' ) print( ' +-------------------------------------------------+' ) print( ' | Benchmark |' ) print( ' +-------------------------------------------------+' ) print( '' ) print( ' 1) Pregled igrica' ) print( ' 0) Izlaz' ) print( '' ) choice = int( input() ) if choice == 1: games_list() return True else: return False
def main(): """Run the console-based python game""" # start with a clear screen clear_screen() show_banner() # ask for players names name1 = ask_player_name("Player 1") name2 = ask_player_name("Player 2") # initiate player instances player1 = Player(name1) player2 = Player(name2) input("\nNext you'll each add your ships. {} first. (No peeking {})\n\n" "Hit ENTER to continue....".format(name1, name2)) # placing ships clear_screen() # defind player1's fleet and add to board define_fleet(player1) show_banner() input("Time to add {}'s ships. Hit ENTER to continue....".format(name2)) # define player2's fleet and add to board define_fleet(player2) # commense game play show_banner() input("Game Time! {} goes first. Hit ENTER to continue....".format(name1)) game_continue = True while game_continue: take_turn(player1, player2) if not player2.ships_left(): show_banner() input("{} WINS!!! Hit ENTER to see final boards....\n" "".format(player1.name)) game_continue = False continue take_turn(player2, player1) if not player1.ships_left(): show_banner() input("{} WINS!!! Hit ENTER to see final boards....\n" "".format(player2.name)) game_continue = False # Display final boards print_all_boards(player1.name, player2.name, player1.board.get_player_view(), player2.board.get_player_view())
def list_wait(email_list): """ Displays a list of emails and allows the user to pick one. """ utils.clear_screen() if len(email_list) == 0: print("No emails to read. Press Return to go back to the menu.") input() return for index, email in enumerate(email_list): print("[{0}] {1}".format(index + 1, email["subject"])) email_index = int(input("Which email would you like to read? ")) return display_email_wait(email_list[email_index - 1])
def view(self, return_text = False): '''View the entire story''' date_format = self._date.strftime('\nYour story from %B %d, %Y (%A) ...\n') try: if not self.get_path(): return data = self.decrypt() except AssertionError: print ERROR, "Baaah! Couldn't decrypt the story!" return clear_screen() count = simple_counter(data) start = "%s\n<----- START OF STORY -----> (%d words)\n\n" % \ (fmt_text(fmt_text(date_format, 'violet'), 'bold'), count) end = "<----- END OF STORY ----->" if return_text: return (data, start, end) sys.stdout.set_mode(2, 0.01) print start, data, end
def define_fleet(player): """Define player's ships and place on board""" # place each ship for ship_spec in SHIP_INFO: ship_name = ship_spec[0] ship_size = ship_spec[1] # display top banner clear_screen() show_banner() print("Placing Ships for {}:\n".format(player.name)) # display board print_board(player.name, player.board.get_player_view()) # display ship info print("Placing {} (size:{})\n".format(ship_name, ship_size)) # get ship placement details while True: # 1. ask if vertical or horizontal direction = get_vert_or_horiz() # 2. ask for top or left starting coordinate anchor = get_anchor_coord() # 3. validate input (explain why input rejected) coords = gen_ship_coords(anchor, ship_size, direction) # 4. validate ship placement if not coords: print("Error: ship coordinates not all on the board\n") continue if not player.board.verify_empty(coords): print("Error: ship coordinates collide with other ships. " "Try again\n") continue # input valid; last while loop break # create ship from input ship = Ship(ship_name, ship_size, coords, direction) # add ship to players list player.add_ship(ship) # place ship on game board player.board.place_ship(ship) # 5. redraw screen for next ship (at top of loop) # display top banner clear_screen() show_banner() # display board print("Placing Ships for {}:\n".format(player.name)) print_board(player.name, player.board.get_player_view()) input("All ships placed for {}. Hit ENTER to continue...." "".format(player.name)) clear_screen()
def take_turn(player, opponent): """Take a turn""" clear_screen() show_banner() input("It's {}'s turn. Hit ENTER to continue....".format(player.name)) clear_screen() show_banner() print("It's {}'s turn:\n".format(player.name)) # print boards for guessing opp_view = opponent.board.get_opponent_view() player_view = player.board.get_player_view() # stitch together board views for display print_all_boards(opponent.name, player.name, opp_view, player_view) coord = get_guess(player) # remember guessed coordinates player.guesses.append(coord) # process guess response = opponent.board.guess(coord) # update board and display response opp_view = opponent.board.get_opponent_view() # reprint boards clear_screen() show_banner() print("It's {}'s turn:\n".format(player.name)) # print both boards print_all_boards(opponent.name, player.name, opp_view, player_view) print(response) input("Hit ENTER to clear screen and end your turn....") clear_screen()
def write(self): '''Write an event to the story''' clear_screen() input_loop, reminder = True, False keystroke = 'Ctrl+C' sys.stdout.set_mode(2, 0.03) if sys.platform == 'win32': print WARNING, "If you're using the command prompt, don't press %s while writing!" % keystroke keystroke = 'Ctrl+Z and [Enter]' # Step 1: Pre-writing stuff - check whether the story exists and whether there's a reminder in it, decrypt it! if self.get_path(): try: # "Intentionally" decrypting the original file self.decrypt(overwrite = True) # an easy workaround to modify your original story using editors prev_data = self.read_data() if prev_data.strip().endswith(REMINDER): # find the reminder (if any) while True: try: stamp_idx = prev_data.rfind('[') if stamp_idx == -1: break time = datetime.strptime(prev_data[stamp_idx:(stamp_idx + 21)], '[%Y-%m-%d] %H:%M:%S') raw_msg = '\n(You were to write something about this day on %B %d, %Y at %H:%M:%S %p)' msg = time.strftime(raw_msg) reminder = True break except ValueError: pass print '\nStory already exists! Appending to the current story...' print '(filename hash: %s)' % self.get_hash() if reminder: print fmt_text(msg, 'yellow') except AssertionError: print ERROR, "Bleh! Couldn't decrypt today's story! Check your password!" return # Step 2: Writing the first paragraph... try: data = [datetime.now().strftime('[%Y-%m-%d] %H:%M:%S\n')] stuff = raw_input("\nStart writing... (Once you've written something, press [Enter] to record it \ to the buffer. Further [RETURN] strokes indicate paragraphs. Press %s when you're done!)\n\n\t" % keystroke) if not stuff: # quitting on empty return raise KeyboardInterrupt data.append(stuff) except (KeyboardInterrupt, EOFError): # quitting on Ctrl-C sleep(CAPTURE_WAIT) print "\nAlright, let's save it for a later time then! Quitting..." input_loop = False data.append(REMINDER) # If the user quits before writing, then add a reminder # Step 3: Writing input loop if input_loop and reminder: # user has written something at this point, remove the reminder (if any) self.write_data(prev_data[:stamp_idx]) # this is necessary, or else we'll ignore the "event" that should be written on top of the reminder reminder = False while input_loop: try: stuff = raw_input('\t') # auto-tabbing of paragraphs (for each [RETURN]) data.append(stuff) except (KeyboardInterrupt, EOFError): sleep(CAPTURE_WAIT) break # Step 4: Write the data to file and encrypt it if not reminder: self.write_data('\n\t'.join(data) + '\n\n', 'a') # because the user could've written something manually self.encrypt(echo = False) if input_loop and raw_input(SUCCESS + ' Successfully written to file! Do you wanna see it (y/n)? ') == 'y': self.view()
def menu(self, menu): utils.clear_screen() for i in range(len(menu)): menu_option = menu[i] print("{0}: {1}".format(i + 1, menu_option[0]))
def games_list(): utils.clear_screen() way = 0 choice = 1 choice2 = -100 while choice2 != 0: print( ' Stranica ' + str( choice ) + '/' + str( num_page() ) + ' ' ) print( '' ) fro = (choice - 1) * 10 igrica_list = globals.igrice[fro:fro + 10] print(' ==+====================================================+=================+============+========+==') print(' | | | | | ') print(' | IME | ZANR | CIJENA | OCJENA | ') print(' | | | | | ') print(' ==+====================================================+=================+============+========+==') z = 0 for igrica in igrica_list: z += 1 table = ' ' table += '| ' table += '{0:{width}}'.format(igrica['ime'], width = 50) table += ' | ' table += '{0:{width}}'.format(igrica['zanr'], width = 15) table += ' | ' table += '{0:{width}}'.format(igrica['cijena'], width = 10) table += ' | ' table += '{0:{width}}'.format(igrica['ocjena'], width = 6) table += ' |' if z < 10: table += '\n ' table += '+----------------------------------------------------+-----------------+------------+--------+' print(table) print(' ==+====================================================+=================+============+========+==') print( '' ) print( ' 1) - ' + str( num_page() ) + ') Stranice liste' ) print( ' -1) - -10) Izabiranje igrice' ) print( ' 100) Sortiranje liste') print( ' 0) Izlaz') print( '' ) choice2 = int( input() ) if choice2 == 100: utils.clear_screen() print(' Kako zelite sortirati igrice? ' ) if way != 0: print( ' 0) Po rednom broju ' ) if way != 1: print( ' 1) Po imenima ' ) if way != 2: print( ' 2) Po zanru ' ) if way != 3: print( ' 3) Po cijeni ' ) if way != 4: print( ' 4) Po ocjeni ' ) print( '' ) way = int( input() ) sort_list( way ) utils.clear_screen() choice = 1 elif choice2 < 0: if choice2 < -10: utils.clear_screen() print( ' Pogreska! Ta igrica ne postoji na ovoj stranici! ' ) print( ' Pritisnite bilo koju tipku za povratak na stranicu. ' ) print( '' ) afajlfja = input() utils.clear_screen() else: games.choose_game( 10*(choice-1)-choice2-1 ) utils.clear_screen() WIP() elif choice2 != 0: if choice2 > num_page(): utils.clear_screen() print( ' Pogreska! Prekoracen broj stranica! ' ) print( ' Pritisnite bilo koju tipku za povratak na prethodno gledanu stranicu. ' ) print( '' ) afalkjfa = input() utils.clear_screen() else: utils.clear_screen() choice = choice2 sort_list( 0 )
def search(session, word = None, lang = None, start = None, end = None, grep = 7): '''Invokes one of the searching functions and does some useful stuff''' clear_screen() now = datetime.now() def check_date(date): if date in ['today', 'now', 'end']: return now elif date in ['start', 'birthday']: return session.birthday try: return datetime.strptime(date, '%Y-%m-%d') except (TypeError, ValueError): return None sys.stdout.set_mode(1, 0.01) # Phase 1: Get the user input required for searching through the stories word = force_input(word, "\nEnter a word: ", ERROR + ' You must enter a word to continue!') lang = get_lang(lang) start, end = map(check_date, [start, end]) while not all([start, end]): try: print WARNING, 'Enter dates in the form YYYY-MM-DD (Mind you, with hyphen!)\n' if not start: lower_bound = session.birthday start_date = raw_input('Start date (Press [Enter] to begin from the start of your diary): ') start = datetime.strptime(start_date, '%Y-%m-%d') if start_date else session.birthday assert (start >= lower_bound and start <= now), 'S' if not end: lower_bound = start end_date = raw_input("End date (Press [Enter] for today's date): ") end = datetime.strptime(end_date, '%Y-%m-%d') if end_date else now assert (end > lower_bound and end <= now), 'E' except AssertionError as msg: print ERROR, '%s date should be after %s and before %s' % \ (msg, lower_bound.strftime('%b. %d, %Y'), now.strftime('%b. %d, %Y')) if str(msg) == 'S': start = None else: end = None except ValueError: print ERROR, 'Oops! Error in input. Try again...' # Phase 2: Send the datetimes to the respective searching functions print "\nSearching your stories for the word '%s'..." % word search_function = rusty_search if lang == 'r' else py_search try: occurrences, timing = search_function(session, start, end, word) except AssertionError: print ERROR, 'There are no stories in the given location!' return def print_stuff(grep): # function to choose between pretty and ugly printing sys.stdout.set_mode(0) results_begin = '\nSearch results from %s to %s:' % (start.strftime('%B %d, %Y'), end.strftime('%B %d, %Y')) + \ "\n\nStories on these days have the word '%s' in them...\n" % word if grep: # pretty printing the output (at the cost of decrypting time) try: timer_start = timer() print results_begin for i, (n, word_count, indices) in enumerate(occurrences): colored = [] date = start + timedelta(n) content = Story(session, date).decrypt() numbers = str(i + 1) + '. ' + date.strftime('%B %d, %Y (%A)') text, indices = mark_text(content, indices, jump) # precisely indicate the word in text for idx in indices: # find the word occurrences left_bound = find_line_boundary(text, idx, grep, -1) right_bound = find_line_boundary(text, idx, grep, 1) sliced = '\t' + '... ' + text[left_bound:right_bound].strip() + ' ...' colored.append(sliced) print numbers, '\n%s' % '\n'.join(colored) # print the numbers along with the word occurrences timer_stop = timer() except (KeyboardInterrupt, EOFError): sleep(CAPTURE_WAIT) grep = 0 # default back to ugly printing clear_screen() print "Yep, it takes time! Let's go back to the good ol' days..." if not grep: # Yuck, but cleaner way to print the results sys.stdout.set_mode(0) print results_begin for i, (n, word_count, _indices) in enumerate(occurrences): date = session.birthday + timedelta(n) numbers = ' ' + str(i + 1) + '. ' + date.strftime('%B %d, %Y (%A)') spaces = 40 - len(numbers) print numbers, ' ' * spaces, '[ %s ]' % word_count # print only the datetime and counts in each file sys.stdout.set_mode(1, 0.015) msg = fmt_text('Found a total of %d occurrences in %d stories!' % (total_count, num_stories), 'yellow') print '\n%s %s\n' % (SUCCESS, msg) print fmt_text(' Time taken for searching: ', 'blue') + \ fmt_text('%s seconds!' % timing, 'green') if grep: print fmt_text(' Time taken for pretty printing: ', 'blue') + \ fmt_text('%s seconds!' % (timer_stop - timer_start), 'green') # Phase 3: Print the results (in a pretty or ugly way) using the giant function below jump, num_stories = len(word), len(occurrences) total_count = sum(map(lambda stuff: stuff[1], occurrences)) print SUCCESS, 'Done! Time taken: %s seconds! (%d occurrences in %d stories!)' \ % (timing, total_count, num_stories) if not total_count: print ERROR, "Bummer! There are no stories containing '%s'..." % word return print_stuff(grep) # Phase 4: Get the user input and display the stories while occurrences: try: sys.stdout.set_mode(2) print '\nEnter a number to see the corresponding story...' print "\r(Enter 'pretty' or 'ugly' to print those search results again, or press [Enter] to exit)" ch = raw_input('\nInput: ') if ch == 'pretty': clear_screen() print_stuff(grep = 7) # '7' is default, because it looks kinda nice elif ch == 'ugly': clear_screen() print_stuff(grep = 0) elif not ch: return elif int(ch) <= 0: raise ValueError else: n_day, word_count, indices = occurrences[int(ch) - 1] date = start + timedelta(n_day) (data, top, bottom) = Story(session, date).view(return_text = True) sys.stdout.set_mode(3) print top, mark_text(data, indices, jump, 'skyblue')[0], bottom except (ValueError, IndexError): print ERROR, 'Oops! Bad input! Try again...'
def reconfigure(self): # FIXME: Could take arguments via command-line? '''Reset the diary's configuration''' try: self._reset() self.delete_config_file() clear_screen() print "\nLet's start configuring your diary...\n", \ '\nEnter the location for your diary...', \ "\n(Note that this will create a foler named 'Diary' if the path doesn't end with it)" self.location = os.path.expanduser(raw_input('\nPath: ')) while not write_access(self.location): self.location = os.path.expanduser(raw_input('\nPlease enter a valid path: ')) if not self.location.rstrip(os.sep).endswith('Diary'): # just put everything in a folder for Diary self.location = os.path.join(self.location, 'Diary') print '(Reminding you that this will make use of %r)' % self.location if not os.path.exists(self.location): os.mkdir(self.location) self.location = self.location.rstrip(os.sep) + os.sep while True: try: # 'birthday' of the diary is important because random stories and searching is based on that birth = raw_input('''\ \nWhen did you start writing this diary? (Press [Enter] for today)\ \nDate should be of the form YYYY-MM-DD (Mind you, with hyphen!) \nDate: ''') # FIXME: just ask the year and 'infer' from the location if not birth: self.birthday, life_time = datetime.now(), 'new' break else: self.birthday, life_time = datetime.strptime(birth, '%Y-%m-%d'), 'old' first_story_exists, date = self.find_stories() if first_story_exists: break elif date: print ERROR, "Your 'first' story doesn't exist!", \ date.strftime('However, a story exists on %B %d, %Y (%A)\n') if raw_input('Do you wanna begin from there (y), or go for another date (n)? ') == 'y': self.birthday = date break else: print ERROR, "A story doesn't exist (in the given path) on that day!" continue except ValueError: print ERROR, 'Oops! ERROR in input. Check the date format and try again...' while True: self.get_pass(life_time = life_time) first_story = Story(self, self.birthday) try: if first_story.get_path(): _data = first_story.decrypt() break elif (datetime.now() - self.birthday).days: # 'unreachable' because this should've already been handled raise Exception, 'Entered unreachable code!' else: # first-timer... break except AssertionError: print ERROR, "Couldn't decrypt your 'first' story with the given password! Try again..." self.write_to_config_file() self.loop = True print "\nIf you plan to reconfigure it manually, then it's located here (%s)" % self.config_location print "And, be careful with that, because invalid configuration files will be deleted during startup!" raw_input('\nPress [Enter] to continue...') except (KeyboardInterrupt, EOFError): sleep(CAPTURE_WAIT) if not all([self.location, self.key, self.birthday, self.loop]): print '\n', ERROR, "Failed to store the login credentials!" if os.path.exists(self.config_location): os.remove(self.config_location) self._reset()