def historicaldata(company_details): loop = True utils.cls() while loop: print( "\nPlease enter the Frequecy option for viewing Historical Data:") print("1. Daily") print("2. Weekly") print("3. Monthly") print("4. Go back to previous menu") print("5. Exit") option = input( "\nYour option : ") print("\n") if option == '1': step = timedelta(days=1), summary(step, company_details) elif option == '2': step = timedelta(days=7), summary(step, company_details) elif option == '3': step = timedelta(days=30), summary_monthly(company_details) elif option == '4': return elif option == '5': print("Thanks for coming. Please visit again...\n") loop = False exit() else: print("Wrong option. Try again...\n")
def search_by_regex(self): while_breaker = 1 while True: # This helps the testing, since these are kind of # infinite loops while testing, there's need for something # that can break them automatically if while_breaker > 100: break else: while_breaker += 1 utils.cls() regex = utils.get_input('Enter your regex here: ') if not regex: utils.pause('Error: Blank spaces are not allowed') continue else: break rows = (Task.select(Task, Employee).join(Employee).where( Task.title.regexp(regex)).naive()) return rows
def print_network_list(self): # Print table header table = ' BSSID SSID Authentication Encryption Protocol Channel Signal ' + \ NL + ' --- --- --- --- --- --- --- ' # Sort the network list sorted_network_list = sorted( self.networks.values(), key = lambda network: ( # Show active networks at the top, timed out networks at the bottom (datetime.now() - network.last_seen).total_seconds() > self.refresh_rate, # By signal strength (descending) int(network.signal_strength[:-1]) * -1, # By SSID network.SSID ), ) for network in sorted_network_list: table += NL + self.format_network_string(network) # Clear console and print all at once cls() print(NL + table) print(NL + '[Esc] Exit')
def menu2(companydata, companylist, comindex): utils.cls() print("=" * 26, "You selected", "=" * 26) print((companylist.iloc[int(comindex)])) loop = True while loop: print("\n" + "=" * 25 + "Stock Options" + "=" * 25) print("\nSelect options (1-6):") print("1. Summary") print("2. Graph") print("3. Historical Data") print("4. Future Prediction") print("5. Go back to previous menu") print("6. Exit") option = input( "\nYour option: ").lstrip() if option == '1': summary(companydata) elif option == '2': graph(companylist, comindex), elif option == '3': historicaldata(companydata), elif option == '4': prediction(companydata), elif option == '5': menu() elif option == '6': print("\nThanks for coming. Please visit again ...\n") loop = False exit() else: print("\nWrong option. Try again ...")
def ask_employee(self, inputtxt=None): """Ask the title for the task""" while_breaker = 1 while True: # This helps the testing, since these are kind of # infinite loops while testing, there's need for something # that can break them automatically if while_breaker > 100: break else: while_breaker += 1 utils.cls() name = utils.get_input(inputtxt) if not name: utils.pause('Error: Blanks spaces are not allowed') continue try: employee = Employee.get(Employee.name == name) except Employee.DoesNotExist: employee = Employee.create(name=name) return employee.id_employee
def enter(self): utils.cls() utils.print_info([["", "Platform name", self.__platform.name], ["", "Platform profile", self.__platform.profile], ["", "Platform vendor", self.__platform.vendor], ["", "Platform version", self.__platform.version], ["", "Platform extensions", self.__platform.extensions.split()]]) print("=" * 80)
def enter(self): utils.cls() utils.print_info( [["", "Device name", self.__device.name], ["", "Device type", cl.device_type.to_string(self.__device.type)], ["", "Device version", self.__device.version], ["", "Device Profile", self.__device.profile]]) print("=" * 85)
def __init__(self): cls() self.RED = "\033[1;31;10m" self.GRN = "\033[1;32;10m" self.YLW = "\033[1;32;10m" self.GRY_BLD = "\033[1;30;2m" self.WHT_BLD = "\033[1;37;2m" self.END_COLOR = "\033[0m"
def search(self): """ Search a task """ while_breaker = 1 while True: # This helps the testing, since these are kind of # infinite loops while testing, there's need for something # that can break them automatically if while_breaker > 100: break else: while_breaker += 1 utils.cls() menu = ("Do you want to search by: \n" "a) Exact Date \n" "b) Range of Dates \n" "c) Term \n" "d) Regex Pattern \n" "e) Employee \n" "f) Return to menu \n" ">") option = utils.get_input(menu).lower() # Handling the errors first if not option: utils.pause('Error: Blank spaces are not allowed') continue elif option not in 'abcdef': utils.pause("Error: {} isn't a valid option".format(option)) continue tasksearch = TaskSearch() if option == 'a': rows = tasksearch.search_by_date() elif option == 'b': rows = tasksearch.search_by_dates_range() elif option == 'c': rows = tasksearch.search_by_term() elif option == 'd': rows = tasksearch.search_by_regex() elif option == 'e': rows = tasksearch.search_by_employee() else: # Get us back to the initial menu return self.menu() self.display_results(rows)
def put(self): """ Add a row to the Task Table""" # Create the task and then call the get function # to have the data in a dict and add it to the db task = Task(True).get() # The dict needs to be unpacked self.task_table.create(**task) utils.cls() input('The entry hass been add. Press enter to return to the menu')
def run(self): print("WebCrawler >> Getting information about Available Packages... ") raw_response = urllib2.urlopen(URL_LIBS_LIST) charset = raw_response.info().get_param('charset', 'utf8') html_content = raw_response.read().decode(charset) parser = AvailablePackagesParser() parser.feed(html_content) libraries = parser.get_libs() print("WebCrawler >> Retrieving package versions information... ") count = 0 for lib in libraries: # Get info for the latest version raw_response = urllib2.urlopen(lib.url_info) charset = raw_response.info().get_param('charset', 'utf8') html_content = raw_response.read().decode(charset) parser = PackageDetailParser() parser.feed(html_content) latest_version_info = parser.get_lib_info() # The latest package version info also contains the long_description of the librari lib.long_description = latest_version_info.get( "long_description", None) latest_version = LibraryVersion() latest_version.version_number = latest_version_info.get( "version", None) latest_version.release_date = latest_version_info.get( "published", None) latest_version.depends = latest_version_info.get("depends", None) latest_version.suggests = latest_version_info.get("suggests", None) latest_version.needs_compilation = latest_version_info.get( "needscompilation", None) count = count + 1 cls() print("WebCrawler >> Retrieving package versions information... ") print(str(count) + " out of " + str(len(libraries))) # Retrieves older versions # lib.versions.append(latest_version) # older_version_infos = print("WebCrawler >> Saving data collected... ") #save the libraries library_manager = LibraryManager() library_manager.clear() library_manager.save(libraries) # save the versions print("WebCrawler >> Success! Data saved. I am done for today :D ")
def ask_title(self, inputtxt=None): """Ask the title for the task""" while True: utils.cls() title = utils.get_input(inputtxt) if not title: utils.pause('Error: Blanks spaces are not allowed') continue return title
def prediction(company_details): utils.cls() print("\n"+"="*23+"Prediction Screen"+"="*23) #get the value of from and to date from user from_dte, to_dte = utils.get_date() #intialized step as single day step = timedelta(days=1) #initializing X_train and y_train as numpy array X_train = np.array([]) y_train = np.array([]) while(from_dte <= to_dte): from_date=datetime.strftime(from_dte, '%d-%b-%y') elem = company_details[company_details['Date'].str.match(from_date, case=False)]
def disp(self): utils.cls() msg = u" " + os.path.splitext( self.DATA_FILE)[0].decode("utf-8") + u"\n\r" #msg += str(self.ROLLING) + "\n\r" #msg += str(self.menu_stack) + "\n\r" #msg += str(self.RESULT)+ "\n\r" sys.stdout.write(msg) sys.stdout.write(self.getStatusBar()) #self.getList() sys.stdout.write(self.getList()) sys.stdout.write(self.getMenuBar()) #sys.stdout.write(msg) self.hasUpdate = False
def main_menu(): while True: utils.cls() print('-------------------------------------') print("Choose action\n" " 1 Get all news\n" " 2 Get news by date") choice = input("->") if choice.isdigit() and int(choice) == 1: print_posts(requests.get('http://0.0.0.0:8023/news').json()) press_enter_to_continue() elif choice.isdigit() and int(choice) == 2: get_news_by_date() press_enter_to_continue() elif choice == QUIT: raise SystemExit
def get_news_by_date(): while True: utils.cls() print("Enter date in the following format: YYYY-MM-DD \n" "(q - for quiet or cancel)") date = input("->") if date == QUIT: return else: if is_date_correct(date): posts = requests.get( f'http://0.0.0.0:8023/news/?date={date}').json() print_posts(posts) return else: print('Incorrect date format, should be YYYY-MM-DD') press_enter_to_continue()
def menu(self): while_breaker = 1 while True: # This helps the testing, since these are kind of # infinite loops while testing, there's need for something # that can break them automatically if while_breaker > 100: break else: while_breaker += 1 utils.cls() menu = ("WORK LOG\n" "What do you want to do? \n" "a) Add new entry \n" "b) Search in existing entries \n" "c) Quit program \n" ">") option = utils.get_input(menu).lower() # Handling the errors first if not option: utils.pause('Error: Blank spaces are not allowed') continue elif option not in 'abc': utils.pause("Error: {} isn't a valid option".format(option)) continue # If nothing wrong, then go ahead with the options if option == 'a': self.put() elif option == 'b': self.search() break elif option == 'c': utils.cls() print('Au revoir!') sys.exit()
def menu(): utils.cls() loop = True while loop: print("=" * 20 + "Welcome" + "=" * 20) print("\nSearch stock using options (1-3):") print("1. Name") print("2. Ticker") print("3. Exit") option = input("\nYour option : ").lstrip() if option == '1': name() elif option == '2': ticker(), elif option == '3': print("\nThanks for coming. Please visit again ...\n") loop = False exit() else: print("\nWrong option. Try again ...")
def auto_place_ships(self): # Method to auto-place all ships self.auto_place_ship(ships.Carrier(player=self, board=self.board)) self.auto_place_ship(ships.Battleship(player=self, board=self.board)) self.auto_place_ship(ships.Cruiser(player=self, board=self.board)) self.auto_place_ship(ships.Submarine(player=self, board=self.board)) self.auto_place_ship(ships.Destroyer(player=self, board=self.board)) # Give our output of the board utils.cls() if self.bot: utils.head("Bot " + str(self.num) + " All Ships Placed!") print(" ") print("Board hidden!") else: utils.head("Player " + str(self.num) + " All Ships Placed!") print(" ") print(self.board) print(" ") if not self.game.debug: utils.get("Press [enter] to continue...")
def place_ships(self): # Method to place all ships on the board if self.place_ship(ships.Carrier(player=self, board=self.board), 1): return if self.place_ship(ships.Battleship(player=self, board=self.board), 2): return if self.place_ship(ships.Cruiser(player=self, board=self.board), 3): return if self.place_ship(ships.Submarine(player=self, board=self.board), 4): return if self.place_ship(ships.Destroyer(player=self, board=self.board), 5): return # Give our output of the board utils.cls() utils.head("Player " + str(self.num) + " All Ships Placed!") print(" ") print(self.board) print(" ") if not self.game.debug: utils.get("Press [enter] to continue...")
def ask_time_spent(self, inputtxt=None): """Ask the time spent for the task""" while True: utils.cls() timespent_input = utils.get_input(inputtxt) if not timespent_input: utils.pause('Error: Blank spaces are not allowed') continue try: time_spent = int(timespent_input) except ValueError: utils.pause( "Error: {} isn't a whole number".format(timespent_input)) continue else: return time_spent
def shot_output(self, output, player): # Prints the output in a human-readable way # Do some animation here... if self.game.quiet: return subject = "Bot " if self.bot else "Player " subject += str(self.num) target = "Bot " if player.bot else "Player " target += str(player.num) anim = 0 # 0 = miss, 1 = hit, 2 = sunk title = "MISSED!" if output["shot"][0]: anim = 1 title = "HIT!" if output["shot"][1]: anim = 2 title = "SUNK {}'s {}!".format(target, output["ship"].type) if self.game.anims: # Animate! a = animations.Animate() if anim == 0: a.miss() elif anim == 1: a.hit() elif anim == 2: a.sunk() utils.cls() utils.head(subject + " Shot!") print(" ") print(subject + " " + title) print(" ") if not self.game.debug: utils.get("Press [enter] to continue...")
def take_shot(self, player, status=None): if self.bot: return self.auto_take_shot(player) # Displays the current board and compares to the player's board for hit detection while True: utils.cls() utils.head("Player " + str(self.num) + "'s Turn") print(" ") if status: print(status) print(" ") print( self.board.mux_boards( player.board.print_board(hidden=True, title="Enemy"), self.board.print_board(title="You"))) print(" ") menu = utils.get("Where would you like to shoot? (A1, B3, etc): ") if not len(menu): continue if menu.lower() == "random": return self.shoot_random(player) coords = self.board.check_point(menu) if coords == None: # Not Valid! utils.cls() utils.head("Player " + str(self.num) + " Misfire!") print(" ") print("That is not a valid coordinate!") print(" ") utils.get("Press [enter] to try again...") continue # Valid coord - check if we already shot there if coords in player.board.shots: # Already shot here utils.cls() utils.head("Player " + str(self.num) + " Misfire!") print(" ") print("You have already fired there!") print(" ") utils.get("Press [enter] to try again...") continue # Valid - add it self.shot_output(player.board.take_shot(coords), player) return "Player {} fired at {}{}".format( self.num, list("ABCDEFGHIJ")[coords[0]], 10 - coords[1])
def delete(self, task): while_breaker = 1 while True: # This helps the testing, since these are kind of # infinite loops while testing, there's need for something # that can break them automatically if while_breaker > 100: break else: while_breaker += 1 utils.cls() confirm = utils.get_input('Are you sure? [y/n]').strip() # Handling errors if not confirm: utils.pause('Error: Blank spaces are not allowed') continue elif confirm not in 'yn': utils.pause("Error: {} isn't a valid option".format(confirm)) continue else: break # If the user changes of idea, getting them back to the # main menu if confirm == 'y': task.delete_instance() utils.cls() utils.pause('Task deleted!', 'Press ENTER to continue') return self.menu() else: utils.cls() utils.pause('The task is safe!', 'Press ENTER to continue') return self.menu()
def draw_graph(exprs): """ Draw all functions in |exprs|: each element should supply a tuple (or any iterable thing), first element being the expression to be eval'd(), second element being a color. """ utils.cls(SCREEN) draw_grid = False draw_axes = False with utils.load_tfile("settings.txt", "rU") as f: for line in f: l = line.rstrip("\n").split() if l[0] == "GRID_ON" and l[1] == "1": draw_grid = True elif l[0] == "AXES_ON" and l[1] == "1": draw_axes = True elif l[0] == "GRAPH_ANIM": GRAPH["GRAPH_ANIM"] = bool(int(l[1])) if draw_grid: draw_funcs.draw_grid(GRAPH, SCREEN, colors.white) if draw_axes: draw_funcs.draw_axes(GRAPH, SCREEN, colors.silver) pygame.display.update() for expr, col in exprs: # automatically add in multiplication signs a = re.findall(r"[0-9]+x", expr) for pattern in a: expr = expr.replace(pattern, "".join(pattern.split("x") + ["*x"])) # change ^ to ** expr = expr.replace("^", "**") draw_funcs.draw_function(GRAPH, SCREEN, expr, col) pygame.event.clear() # save a copy of the current screen for performance reasons # (extremely slow to constantly replot functions) graphed_surface = SCREEN.copy() box = gui.Container() pos_label = gui.Label(0, 0, "(0, 0)", 20, colors.lime) pos_label_pos = (0, 0) while True: if pygame.event.peek(QUIT): utils.quit() events = pygame.event.get() for event in events: if event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type == KEYUP and event.key == K_BACKQUOTE: import time t = time.strftime("%b%d %I_%M_%S") del time pygame.image.save(graphed_surface, "graph_%s.bmp" % (t)) elif event.type == MOUSEMOTION: pos_label_pos = event.pos elif event.type == MOUSEBUTTONDOWN and event.button == 1: if pos_label in box: box.remove(pos_label) else: box.add(pos_label) box.update(*events) pos_label.x, pos_label.y = pos_label_pos pos_label.text = "(%.3f, %.3f)" % (draw_funcs.to_graph( GRAPH, *pos_label_pos)) utils.cls(SCREEN) SCREEN.blit(graphed_surface, (0, 0)) box.draw(SCREEN) pygame.display.update()
def blit_background(): utils.cls(SCREEN) SCREEN.blit(BACKGROUND, (0, 0))
def main(): """ Main """ # Inital Setup load_from_file = GAMECONFIG['load_from_file'] load_from_image = GAMECONFIG['load_from_image'] dead_cells = GAMECONFIG['dead_cells'] loops = GAMECONFIG['iterations'] take_screenshot = GAMECONFIG['take_screenshot'] make_images = GAMECONFIG['make_image'] current_loop = 0 #clean up clean_up_files(make_images, take_screenshot) # Load a random board based on game config if load_from_file == load_from_image: rows = GAMECONFIG['board_size'] columns = GAMECONFIG['board_size'] screen_w_h = resize_output_window(take_screenshot, rows, columns) current_cycle_data = [[dead_cells for i in range(columns)] for j in range(rows)] randomly_populate_board(current_cycle_data) # Load from image elif load_from_image: current_cycle_data, rows, columns = load_board_from_image('image.png') screen_w_h = resize_output_window(take_screenshot, rows, columns) # Load from file elif load_from_file: current_cycle_data, rows, columns = load_board_from_file( 'input_file.csv') screen_w_h = resize_output_window(take_screenshot, rows, columns) previous_cycle_data = [[dead_cells for i in range(columns)] for j in range(rows)] save_previous_cycle_iteration(current_cycle_data, previous_cycle_data) #create_png_image(current_cycle_data, current_loop, make_images) # Begin simulation loop while current_loop <= loops: if STATS['All_Dead'] is True: everyone_died(current_cycle_data, current_loop, screen_w_h, take_screenshot) break if STATS['All_Alive'] is True: noone_died(current_cycle_data, current_loop, screen_w_h, take_screenshot) break format_and_print_output(current_cycle_data) screenshot_windows(current_loop, screen_w_h, take_screenshot) if current_loop < loops: utils.cls() create_png_image(current_cycle_data, current_loop, make_images) next_life_cycle_iteration(previous_cycle_data, current_cycle_data) current_loop += 1 STATS['Cycles'] = current_loop # Simulation complete, make an animated gif make_gifs(make_images, take_screenshot)
def enter(self): utils.cls() print("=" * 85)
def name(): utils.cls() companyName = input( "\nEnter the company name you want to search : ").lstrip() outlen = len(companylist[companylist['Name'].str.contains(companyName, case=False)])
def main(): """ Launchpoint for all experiments associated with the CGL RNA-seq recompute analysis WARNING: Some of these experiments take a rather long time to run (days / weeks) First run create_project.py (or create-project entrypoint) to create the necessary prerequisite project directory """ parser = argparse.ArgumentParser( description=main.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False) subparsers = parser.add_subparsers(dest='command') # Pairwise GTEx parser_gtex_pairwise = subparsers.add_parser( 'pairwise-gtex', help='Run GTEx Pairwise Comparison') parser_gtex_pairwise.add_argument( '--project-dir', required=True, help='Full path to project dir (rna-seq-analysis') parser_gtex_pairwise.add_argument( '--cores', required=True, type=int, help='Number of cores to utilize during run.') # Pairwise TCGA v GTEx parser_pairwise = subparsers.add_parser( 'pairwise-gtex-tcga', help='Performs pairwise comparison between GTEx and TCGA') parser_pairwise.add_argument( '--project-dir', help='Full path to project dir (rna-seq-analysis') parser_pairwise.add_argument('--cores', required=True, type=int, help='Number of cores to utilize during run.') # Pairwise TCGA Tumor vs Normal parser_pairwise = subparsers.add_parser( 'pairwise-tcga', help='Performs pairwise comparison between TCGA tumor and normal.') parser_pairwise.add_argument( '--project-dir', help='Full path to project dir (rna-seq-analysis') parser_pairwise.add_argument('--cores', required=True, type=int, help='Number of cores to utilize during run.') # TCGA Tumor Vs Normal parser_tcga = subparsers.add_parser('tcga-tumor-vs-normal', help='Run TCGA T/N Analysis') parser_tcga.add_argument('--project-dir', help='Full path to project dir (rna-seq-analysis') parser_tcga.add_argument('--cores', required=True, type=int, help='Number of cores to utilize during run.') # TCGA Matched parser_tcga_matched = subparsers.add_parser( 'tcga-matched', help='Run TCGA T/N analysis, matching T/N patients.') parser_tcga_matched.add_argument( '--project-dir', help='Full path to project dir (rna-seq-analysis') parser_tcga_matched.add_argument( '--cores', required=True, type=int, help='Number of cores to utilize during run.') # Negative controls tcga_neg = subparsers.add_parser( 'tcga-neg-control', help='Performs negative control experiment by randomizing the ' 'order of the disease vector relative to the input.') tcga_neg.add_argument('--project-dir', help='Full path to project dir (rna-seq-analysis') tcga_neg.add_argument('--cores', required=True, type=int, help='Number of cores to utilize during run.') tcga_match_neg = subparsers.add_parser( 'tcga-matched-neg-control', help='Performs negative control experiment by randomizing disease' 'and patient vector relative to the input.') tcga_match_neg.add_argument( '--project-dir', help='Full path to project dir (rna-seq-analysis') tcga_match_neg.add_argument('--cores', required=True, type=int, help='Number of cores to utilize during run.') # Tissue Pair Clustering parser_tissue_clustering = subparsers.add_parser( 'tissue-clustering', help='Run PCA / t-SNE clustering to examine similarity between' ' TCGA tumor, normal, and GTEx samples.') parser_tissue_clustering.add_argument( '--project-dir', required=True, help='Full path to project dir (rna-seq-analysis') # DeSeq2 Time Test parser_deseq2 = subparsers.add_parser( 'deseq2-time-test', help='Runs DeSeq2 with increasing number of samples and ' 'records how long it takes to run') parser_deseq2.add_argument( '--project-dir', required=True, help='Full path to project dir (rna-seq-analysis)') parser_deseq2.add_argument('--cores', required=True, help='Number of cores to utilize during run.') # If no arguments provided, print full help menu if len(sys.argv) == 1: cls() parser.print_help() sys.exit(1) # Execution params = parser.parse_args() cls() if params.command == 'tissue-clustering': log.info('Tissue Clustering') runner(TissueClustering(params.project_dir)) elif params.command == 'tcga-matched': log.info(title_tcga_matched()) runner(TcgaMatched(params.project_dir, params.cores)) elif params.command == 'pairwise-gtex-tcga': log.info(title_pairwise_gtex_tcga()) runner(PairwiseTcgaVsGtex(params.project_dir, params.cores)) elif params.command == 'tcga-tumor-vs-normal': log.info('TCGA Tumor Vs Normal') runner(TcgaTumorVsNormal(params.project_dir, params.cores)) elif params.command == 'tcga-neg-control': log.info('TCGA Tumor vs Normal Negative Control') runner(TcgaNegativeControl(params.project_dir, params.cores)) elif params.command == 'tcga-matched-neg-control': log.info('TCGA Matched Negative Control') runner(TcgaMatchedNegativeControl(params.project_dir, params.cores)) elif params.command == 'gtex-pairwise': log.info('GTEx Pairwise Tissue Experiment') runner(PairwiseGTEx(params.project_dir, params.cores)) elif params.command == 'pairwise-tcga': log.info('Pairwise TCGA Tumor vs Normal') runner(PairwiseTCGA(params.project_dir, params.cores)) elif params.command == 'deseq2-time-test': log.info('DESeq2 Time Test') runner(DESeq2TimeTest(params.project_dir, params.cores))
def draw_graph(exprs): """ Draw all functions in |exprs|: each element should supply a tuple (or any iterable thing), first element being the expression to be eval'd(), second element being a color. """ utils.cls(SCREEN) draw_grid = False draw_axes = False with utils.load_tfile("settings.txt", "rU") as f: for line in f: l = line.rstrip("\n").split() if l[0] == "GRID_ON" and l[1] == "1": draw_grid = True elif l[0] == "AXES_ON" and l[1] == "1": draw_axes = True elif l[0] == "GRAPH_ANIM": GRAPH["GRAPH_ANIM"] = bool(int(l[1])) if draw_grid: draw_funcs.draw_grid(GRAPH, SCREEN, colors.white) if draw_axes: draw_funcs.draw_axes(GRAPH, SCREEN, colors.silver) pygame.display.update() for expr, col in exprs: # automatically add in multiplication signs a = re.findall(r"[0-9]+x", expr) for pattern in a: expr = expr.replace(pattern, "".join(pattern.split("x") + ["*x"])) # change ^ to ** expr = expr.replace("^", "**") draw_funcs.draw_function( GRAPH, SCREEN, expr, col) pygame.event.clear() # save a copy of the current screen for performance reasons # (extremely slow to constantly replot functions) graphed_surface = SCREEN.copy() box = gui.Container() pos_label = gui.Label(0, 0, "(0, 0)", 20, colors.lime) pos_label_pos = (0, 0) while True: if pygame.event.peek(QUIT): utils.quit() events = pygame.event.get() for event in events: if event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type == KEYUP and event.key == K_BACKQUOTE: import time t = time.strftime("%b%d %I_%M_%S") del time pygame.image.save(graphed_surface, "graph_%s.bmp" % (t)) elif event.type == MOUSEMOTION: pos_label_pos = event.pos elif event.type == MOUSEBUTTONDOWN and event.button == 1: if pos_label in box: box.remove(pos_label) else: box.add(pos_label) box.update(*events) pos_label.x, pos_label.y = pos_label_pos pos_label.text = "(%.3f, %.3f)" % ( draw_funcs.to_graph(GRAPH, *pos_label_pos)) utils.cls(SCREEN) SCREEN.blit(graphed_surface, (0, 0)) box.draw(SCREEN) pygame.display.update()