dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_or_create_session(chat_id: int) -> UserSession: """ Get or create a user session for the given chat ID. Args: chat_id (int): The ID of the chat. Returns: UserSession: The existing or newly created user session. """ if chat_id not in user_sessions: user_sessions[...
The function handles a user's weekend selection via a callback, updates their session with the chosen option, processes the data, and prompts the user to generate an AI lineup with a keyboard. It retrieves the chat ID, stores the selection, triggers processing, sends a typing action, and asks for lineup generation.
def handle_weekend_selection(call: telebot.types.CallbackQuery) -> None: chat_id = call.message.chat.id user_session = get_or_create_session(chat_id) user_session.selected_weekend = call.data bot.answer_callback_query(call.id) process_weekend_data(chat_id, user_session) typing_action(chat_id) ...
def get_or_create_session(chat_id: int) -> UserSession: """ Get or create a user session for the given chat ID. Args: chat_id (int): The ID of the chat. Returns: UserSession: The existing or newly created user session. """ if chat_id not in user_sessions: user_sessions[...
This function handles a user's selection of both weekends, updates their session data, processes the weekend information, and prompts the user to generate an AI lineup with a customized keyboard.
def handle_all_weekends(call: telebot.types.CallbackQuery) -> None: chat_id = call.message.chat.id user_session = get_or_create_session(chat_id) bot.answer_callback_query(call.id) user_session.selected_weekend = 'both' process_weekend_data(chat_id, user_session) typing_action(chat_id) bot.se...
def prim_deal_merge_manual_data_w_linktable(UPDATED=False): """ Merges the main dataset with the link table for primary dealer identification. Returns: - tuple: A tuple containing two DataFrames: merged_main (the merged dataset) and link_hist (the link table). Note: This functio...
The main task of the code is to execute a data processing pipeline that merges datasets, generates comparison groups, pulls and prepares data, creates summary statistics and ratios, formats a final table, and exports it to LaTeX. The function returns a formatted pandas DataFrame containing the analysis results, with op...
def main(UPDATED=False): """ Main function to execute the entire data processing pipeline. Returns: - formatted_table (pandas.DataFrame): DataFrame containing the formatted table. """ db = wrds.Connection(wrds_username=config.WRDS_USERNAME) merged_main, link_hist = prim_deal_merge_manual_da...
def main(UPDATED=False): """ Main function to execute the entire data processing pipeline. Returns: - formatted_table (pandas.DataFrame): DataFrame containing the formatted table. """ db = wrds.Connection(wrds_username=config.WRDS_USERNAME) merged_main, link_hist = prim_deal_merge_manual_da...
The main task of the code is to set up test data by connecting to a WRDS database, merging datasets with link tables, creating comparison group mappings, pulling relevant data, preparing datasets, and generating a table of financial ratios for analysis. This prepares structured data for subsequent testing or processing...
def setUpClass(cls): cls.formatted_table = main() # Mimic the main method's workflow to get datasets cls.db = wrds.Connection(wrds_username=config.WRDS_USERNAME) merged_main, link_hist = prim_deal_merge_manual_data_w_linktable() cls.comparison_group_link_dict = create_comparison_...
def checkKeyboardInput(): keys=pygame.key.get_pressed() if keys[pygame.K_UP]: up() if keys[pygame.K_DOWN]: down() if keys[pygame.K_RIGHT]: right() if keys[pygame.K_LEFT]: left() if keys[pygame.K_SPACE]: player.slowDown(0.06) if keys[pygame.K_r]: ...
The code processes a game action by updating the player's movement, checking for collisions, managing rewards, and returning the environment state. It increments time, handles user input or AI actions, slows down the player if not accelerating, checks wall collisions, updates position, constructs a state vector with di...
def step(self, action): self.time += 1 for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: crashed = True # print(event) ...
def drawWalls(wallWidth): for w in walls: pygame.draw.line(gameDisplay, black, (w.x1, w.y1), (w.x2, w.y2), wallWidth) def debugBorder(): pygame.draw.line(gameDisplay, black, player.corners[0], player.corners[1], 2) pygame.draw.line(gameDisplay, black, player.corners[1], player.corners[2], 2) pyg...
The function `debugMode()` is designed to visualize debugging elements in a game. It draws walls, marks the player's corners with circles, renders the game border, and checks for collisions between the player and walls. This aids in troubleshooting visual elements, player positioning, and collision detection logic duri...
def debugMode(): drawWalls(2) for cor in player.corners: pygame.draw.circle(gameDisplay, (0,0,0), cor, 3) debugBorder() checkForCollision(player, walls)
def inCheck(self): if self.whiteToMoveOn: return self.squareUnderAttack(self.whiteKingCord[0], self.whiteKingCord[1]) else: return self.squareUnderAttack(self.blackKingCord[0], self.blackKingCord[1]) def getKingsideCastleMoves(self, r, c, moves): # second rule is are the...
The function `getCastleMoves` generates valid castling moves for a king if the king is not in check and the corresponding castling rights (kingside or queenside) are available, by calling specialized methods to add these moves to the list.
def getCastleMoves(self, r, c, moves): if self.inCheck(): # first step is whether the king is under attack nor return # can't castle while we are under attack by if (self.whiteToMoveOn and self.currentCastlingRight.wks) or (not self.whiteToMoveOn and self.currentCastlingRight.bks): ...
def CheckPossibleMoves(self): moves = [] for r in range(len(self.board)): # rows of board for c in range(len(self.board[r])): # colums of board in given row turn = self.board[r][c][0] # it gives first letter of the word if (turn == 'w' and self.whiteToMoveOn) o...
The function generates valid chess moves by checking each potential move for legality, including castling and en passant, while ensuring the king isn't left in check. It removes invalid moves, determines checkmate/stalemate, and restores original game state before returning the list of valid moves.
def getValidMoves(self): tempEnpassantPossible = self.enpassantPossible tempCastlingMove = CastlinRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs) # copy current castling moves = self.CheckPossibl...
def show_plot(frame): print('Preparing frame.\n') plt.pcolormesh(frame) plt.show() def build_static_frame(t): return [[f(t, x, y) for y in range(Y)] for x in range(X)] def show_movie(frames, target): print('Preparing animation.\n\ttarget:', target, '\n') fig = plt.figure() ims = [] for frame in frames: im ...
The main task of the code is to generate and display visual plots or movies based on the input `plot_type` and parameters. It prepares data by calling `build_static_frame()` for 'frame' type or `build_movie_frames()` for 'movie' type, converts the output to a float array, and uses `show_plot()` or `show_movie()` to vis...
def main(plot_type, param): print('Preparing data to plot.\n\tplot_type:', plot_type, '\n\tparam:', param, '\n') if plot_type == 'frame': show_plot(np.array(build_static_frame(param), dtype=float)) elif plot_type == 'movie': show_movie(np.array(build_movie_frames(), dtype=float), param) print('Complete.\n')
def wishme(): Speak("Welcome back sir!") cur_time() hour = dt.datetime.now().hour if hour >= 6 and hour < 12: Speak("Good Morning...") elif hour >= 12 and hour < 17: Speak("Good Afternoon...") elif hour >=17 and hour <= 24: Speak("Good Evening...") else...
The code defines a voice assistant function that executes tasks based on voice commands. It handles basic queries like date/time, introduces itself, opens apps/websites, searches Google/YouTube, tells jokes, fetches Wikipedia info, checks weather, monitors system stats, manages a to-do list, switches windows, and exits...
def TaskExecution(): wishme() while True: command = take_commands() # Basic Tasks if "introduce yourself" in command: introduction() elif "date" in command: date() elif "time" in command: cur_time() # Openin...
def moves(self): all_moves = [] for i in range(8): for j in range(8): if self.turn == True and self.board[i][j][0] == 'w': if self.board[i][j] == 'wp': mv = self.pawn_moves(i, j, "white") for m in mv: ...
The main task of the code is to filter valid moves by simulating each move, checking if it results in a check, and removing invalid moves from the list. It toggles the turn, performs the move, checks for checks, undoes the move, and repeats this process for all generated moves before returning the filtered list of vali...
def valid_moves(self, square1, square2): if square1 == [0, 0] and square2 == [0, 0]: self.history.pop() vm = self.moves() for i in range(len(vm)-1, -1, -1): self.real_move(square1, square2) self.turn = not self.turn if self.checking_checks(): ...
def valid_moves(self, square1, square2): if square1 == [0, 0] and square2 == [0, 0]: self.history.pop() vm = self.moves() for i in range(len(vm)-1, -1, -1): self.real_move(square1, square2) self.turn = not self.turn if self.checking_checks(): ...
This method executes a chess move by validating the move based on the current turn, updating the board if valid, and adjusting castling rights for kings and rooks. It checks if the move is in the list of valid moves, performs the move, and disables corresponding castling options if a rook or king is moved. If invalid, ...
def move(self, square1, square2): piece = self.board[square1[0]][square1[1]] square = self.board[square2[0]][square2[1]] print(f'Move to make {[square1, square2]}') if self.board[square1[0]][square1[1]][0] == 'w' and self.turn == True or self.board[square1[0]][square1[1]][0] == 'b' and s...
def next_screen(self): if self.state == "welcome": self.state = "create_profile" elif self.state == "create_profile": if self.text.strip(): # Ensure name field is not empty self.user_data["name"] = self.text.strip() self.text = '' # Clear the tex...
This code runs a Pygame application that handles user input through a GUI interface. It manages different states (welcome, profile creation, symptom entry, result display) by processing keyboard and mouse events. The app collects user data (name, symptoms), transitions between screens, and displays results using a data...
def run(self, data_class_instance): while not self.done: for event in pygame.event.get(): if event.type == pygame.QUIT: self.done = True if event.type == pygame.KEYDOWN: if self.active: if event.key == py...
def reset_conversation(user_id): # resets conversation for user logger.debug(f'Reset conversation for user {user_id}') if user_id not in conversations: conversations[user_id] = {'query': None, 'displayed_questions': None, 'similar_questions': None, 'displayed_msgs_id': None, ...
The main task of the code is to parse user interactions (callback queries or messages) in a chatbot, determine the user's intent (e.g., navigation, reset, question input), and trigger corresponding actions like handling navigation commands (/next, /prev, /end), resetting conversations, asking questions, or scraping ans...
def parse_response(result): if 'callback_query' in result: user_id = result['callback_query']['from']['id'] user_query = result['callback_query']['data'] if user_id not in conversations: reset_conversation(user_id) if 'displayed_msgs_id' not in conversations[user_id]: # probably leftover ...
def _get_occupied_row(self): occupied_cells = [s for s in self.get_occupied_dimension().split(":")] cell = occupied_cells[1] occupied_row = int(''.join([d for d in cell if d.isdigit()])) return occupied_row def _get_worksheet(self): return self.ws def check_record_type(self, reco...
This function calculates the total amount by iterating through worksheet rows, checking if each row's record type matches the given 'record_type', and optionally filtering by a specified 'option' value in column C. It sums the amounts from matching rows based on the criteria provided.
def calculate_amount_by_record_type_and_option(self, record_type, option): total = 0 for i in range(1, self._get_occupied_row()+1): cell = f'B{i}' cell_content = self._get_worksheet()[cell].value if self.check_record_type(record_type, cell_content): if...
def _get_input_row(self): return self._get_occupied_row() + 1 def _input_date(self, input_row): input_cell = f'A{input_row}' self._get_worksheet()[input_cell] = datetime.datetime.now() def _input_type(self, input_row, type): assert type in RecordType.get_list() input_cell = f'B{...
The main task of the code is to record an expense by populating a structured data row with the provided amount, expense category, current date, and predefined expense type. It retrieves an input row, sets its date, marks it as an expense, inputs the amount, and assigns the expense category, likely preparing the data fo...
def input_expense( self, amount, expense_category, ): input_row = self._get_input_row() self._input_date(input_row) self._input_type(input_row, RecordType.EXPENSE) self._input_amount(input_row, amount) self._input_category(input_row, expens...
def _get_input_row(self): return self._get_occupied_row() + 1 def _input_type(self, input_row, type): assert type in RecordType.get_list() input_cell = f'B{input_row}' self._get_worksheet()[input_cell] = type def _input_date(self, input_row): input_cell = f'A{input_row}' ...
The main task of the code is to create a deposit record by populating an input row with the specified amount, setting its type as DEPOSIT, and recording the current date. The method constructs a structured data entry for a deposit transaction, leveraging helper functions to assign record type, date, and amount to the i...
def input_deposit( self, amount, ): input_row = self._get_input_row() self._input_type(input_row, RecordType.DEPOSIT) self._input_date(input_row) self._input_amount(input_row, amount)
def create_features(df): # Property Type-specific Features if 'terraceSurface' in df.columns and 'surface' in df.columns: df['terrace_per_sqm'] = df['terraceSurface'] / df['surface'] # Income-related Features if 'cadastralIncome' in df.columns and 'surface' in df.columns: df['cadast...
(The function processes a DataFrame by creating features, cleaning data, splitting into training/test sets, imputing missing values, encoding categorical variables, and standardizing features. It returns the processed training/test data along with imputation models, encoder, and scaler for future predictions.)
def get_clean_training_test_data(df, type): create_features(df) df = cleaning_data(df) X_train, X_test, y_train, y_test = split_into_test_and_training(df) X_train, X_test, num_imp, cat_imp = impute_missing_values(X_train, X_test,type) X_train, X_test, ohe = encode_data(X_train, X_test) X_train, ...
def champion_select(self, client_number): try: chosen_champion = pickle.loads(self.client_sockets[client_number].recv(BUFFER_SIZE)) if chosen_champion == CLIENT_QUIT: return LEFT_CHAMPION_SELECT if self.server_status == SERVER_IS_CLOSING: sel...
This code handles a client's lifecycle in a multiplayer game by managing champion selection, lobby interactions, and game execution. It maintains connection status, transitions between game phases (champion select → lobby → game), and performs cleanup tasks like freeing client resources, closing sockets, and updating g...
def handle_client(self, client_number): connection = CONNECTION_IS_ACTIVE game_start = GAME_IS_NOT_STARTED while connection: champion_select_result = self.champion_select(client_number) if champion_select_result == CHAMPION_SELECT: continue e...
def opening_view(): print(HANGMAN_OPENING_FILE) print(MAX_TRIES) def choose_word(file_path, index): """ :param file_path: a string representing a path to a text file containing spaces separated by words :param index: integer representing a particular word's placement in the file. :return: a tup...
The main task of the code is to initiate a hangman game by prompting the user for a file path and index, retrieving a secret word from the specified file, and launching the game with that word. It first displays an opening view, then collects user inputs to select a word from the file, extracts the secret word, and sta...
def main(): opening_view() file_path = input("Enter file path: ") index = int(input("Enter index: ")) tuple_words = choose_word(file_path, index) secret_word = tuple_words[0] hangman_game(secret_word)
def init(): signal.signal(signal.SIGINT, handle_system_signal) signal.signal(signal.SIGTERM, handle_system_signal) parser = argparse.ArgumentParser() parser.add_argument("--file", type=str, help="Path to the json file with saved contacts", default="./data...
The main task of the code is to create a console-based assistant bot that processes user commands in a loop. It initializes resources, welcomes the user, parses input commands, executes corresponding actions via handle_command(), and exits gracefully when receiving an exit command. The bot provides feedback for unrecog...
def main(): init() print("Welcome to the assistant bot!") while True: user_input = input("console bot >>> ") command = parse_command(user_input) if command is None: print("No command was entered. Try again") elif command["command"] in ("exit", "q", "quit", "clos...
def get_coords(self): ''' returns the location of the entity ''' return self.position def in_range(self, target): ''' Determines if self is in range of target Inputs: - target: an entity ''' if self.distance(target) < self.rng: ...
The main task of the code is to move an entity toward a target by calculating directional movement based on coordinate differences. If the target is out of range, the entity adjusts its position along the x and y axes using its speed values, applying negative or positive movement depending on the direction of the targe...
def move(self, target): ''' Moves the entity towards a target location Inputs: - target: an entity ''' tar_coords = target.get_coords() curr_coords = self.get_coords() movement = [] if not self.in_range(target): if tar_coords[...
def get_coords(self) -> Vector2: ''' returns the top left position of Monkey as a vector ''' return self.position def update_coords(self, pos:Vector2) -> None: ''' Updates the position of Monkey to pos ''' self.position = pos def jump_height(self, platform...
This function updates the Monkey's coordinates to simulate jumping motion when the player presses the jump key (W). If the Monkey is not already airborne, it initiates a jump by setting internal flags and calculating vertical movement using `jump_height()`. If already jumping, it continues the motion by incrementing ju...
def jump(self, keys:list, platforms:list, dt:int) -> None: ''' Updates the coordinates of Monkey in jumping motion if player jumps, does nothing otherwise Inputs: - keys, a list of booleans representing player key input - platforms, a list of containing all Platform obje...
def get_coords(self) -> Vector2: ''' returns the top left position of Monkey as a vector ''' return self.position def update_coords(self, pos:Vector2) -> None: ''' Updates the position of Monkey to pos ''' self.position = pos def on_platform(self, platform...
This function updates the Monkey's horizontal movement based on key inputs and adjusts its vertical position using falling physics. It checks for platform collisions, calculates falling motion via kinematics, and resets the position if the Monkey falls below a platform. The function also updates facing direction and ma...
def move(self, keys:list, platforms:list, dt:int) -> None: ''' **Needs rework: falling motion** Updates the coordinates of Monkey if player moves horizontally. If Monkey falls off a platform, the coordinates of Monkey are updated Inputs: - keys, a list of booleans repr...
def read_message(self): if len(self.__messages) > 0: message = self.__messages.pop() msg_data = (message.veh_id, message.priority, message.data, message.position, message.direction) if msg_data not in self.received: self.received.append...
The main task of the code is to update an object's state in a simulation by reading messages, adjusting direction, calculating acceleration and speed (unless overridden), updating position, tracking events, and broadcasting the updated state. This step method orchestrates sequential updates to ensure accurate movement ...
def step(self): self.read_message() self.update_direction() if not self.override_acceleration: self.update_acceleration() if not self.override_speed: self.update_speed() self.update_position() self.event_tracker() self.broadcast()
def x_or_o(): choice = "" print("So, you wanna be X or O?") choice = input("Your choice: ").lower() if choice == "x": return ["X", "O"] elif choice == "o": return ["O", "X"] else: print("That's not a valid choice! Just type 'x' or 'o'.") return x_or_o() def first_...
The main task of this code is to implement a Tic-Tac-Toe game where a user plays against an AI (Calicobot). It initializes the game board, determines player turns via a coin flip, alternates between user and AI moves, checks for win/tie conditions, displays results, and allows replay. The game includes delays, messages...
def ttt(): # Empty board current_board = [" "] * 10 # Fetch the letters user_letter, calico_letter = x_or_o() # Decide who goes first turn = first_player() print("Let's flip a coin to decide who goes first.") time.sleep(2) print("If it's heads, I go first. If it's tails, you go first. Deal?") ...
def detectLanesImg(self, debug=False, display=False): # Reading the File and cropping the image original = cv2.imread(self.NAME); if (debug): if (not os.path.exists(debug_dir)): os.makedirs(debug_dir); cv2.imwrite(debug_dir + "/original.png", original); if (original is None): print("ERROR! Unable...
This function detects lanes in input media (image, video, or frame) based on the specified type. It calls appropriate methods for processing images, videos, or individual frames, saves outputs if a file path is provided, and returns the processed result. Error handling is included for invalid input types.
def detectLanes(self, frame=None, debug=False, display=False): if (self.TYPE == self.FRAME_PROCESS_FILE_IMAGE): self.detectLanesImg(debug, display); elif (self.TYPE == self.FRAME_PROCESS_FILE_VIDEO): self.detectLanesVid(debug, display); elif (frame.any() != None and self.TYPE == self.FRAME_PROCESS_IMAGE_FRA...
def define_train_data(): '''Creates train data in data folder''' train_data = pd.DataFrame(data = X) train_data['class'] = y if not os.path.exists(DATA_PATH): os.makedirs(DATA_PATH) train_data_path = os.path.join(DATA_PATH,"train_data.csv") train_data.to_csv(train_data_path,index=False) ...
The main task of the code is to train a machine learning model by defining training and inference data, then saving the trained model. It executes three key steps: preparing training data, configuring inference data, and persisting the model after training.
def main(): '''Main Function''' define_train_data() define_inference_data() save_trained_model()
def create_account(self): email = self.gen_email() if self.email is None else self.email password = self.gen_password() if self.password is None else self.password result = kite_api.create_account(email, password) self.session_cookie = result.get("cookie", "") self.account = resu...
The code automates account creation, initiates a pro trial, updates the Kite session, and instructs the user to restart Kite. It sequentially executes these tasks with print statements for progress tracking.
def automate(self): print("Creating account...") self.create_account() print("Starting pro trial...") self.start_trial() self.update_kite_session() print("You have to completely restart Kite now!")
def checkFields(self): congruence.checkPositiveNumber(self.source_plane_distance, "Distance from Source") congruence.checkPositiveNumber(self.image_plane_distance, "Image Plane Distance") congruence.checkStrictlyPositiveNumber(self.input_diameter, "Input Diameter") congruence.checkStrict...
This function traces an optical element by validating the input beam, initializing UI elements, creating a screen slit optical element, populating fields, applying settings, and executing operations. It handles errors by logging exceptions, displaying alerts, and updating progress bars. If the beam is invalid or empty,...
def traceOpticalElement(self): try: self.error(self.error_id) self.setStatusMessage("") self.progressBarInit() if ShadowCongruence.checkEmptyBeam(self.input_beam): if ShadowCongruence.checkGoodBeam(self.input_beam): sys.stdout ...
def init_frame(self): """ this function initialized the frame for the widget that added :return: """ for i in range(5): self.frame.append(Frame(self.main_window, height=60, width=400, pady=15, padx=15)) self.frame[0].grid(row=0, sticky='ew', columnspan=2) ...
This code initializes a GUI window with specified configurations, sets up logging, and initializes data structures and UI components for managing products, buyers, suppliers, and transactions. It prepares the application's interface and backend variables for a retail or inventory management system.
def __init__(self, main_window, title, window_geo, perant, store, icon=None): setup_logger(title, print_to_screen=False) self.main_window = main_window self.main_window.title(title) self.main_window.geometry(window_geo) self.perant = perant self.store = store glob...
def getSelectedShipPlacement(self): """ Returns a 2 tuple of an array of grid positions that hold the selected ship, starting from the position of the selector, and a boolean determining the validity of the ship placement. """ if not self.current_mouse_over_grid or self.selected_ship_index == None: return No...
This method redraws the game board by calculating grid block sizes, rendering grid cells as rectangles, and overlaying colored circles to represent game states like boat placements, hits, misses, and mouse interactions. It distinguishes between setup and battle phases, highlights selected cells, and draws a central div...
def draw(self): self.canvas.delete(ALL) # print("GAME_SIZE: {}, GRID_SIZE: {}".format(GAME_SIZE, GRID_SIZE)) # print("canvas size: {}".format((self.canvas.winfo_width(), self.canvas.winfo_height()))) self.grid_block_height = int(self.canvas.winfo_height() / 2 / GRID_SIZE) self.grid_block_width = int(self.canv...
def getSelectedShipPlacement(self): """ Returns a 2 tuple of an array of grid positions that hold the selected ship, starting from the position of the selector, and a boolean determining the validity of the ship placement. """ if not self.current_mouse_over_grid or self.selected_ship_index == None: return No...
This code handles grid click events in a game, managing two phases: "setup" for placing ships and "battle" for attacking. During setup, it validates and places selected ships, transitions to battle phase when all ships are placed, and triggers AI setup. In battle, it processes attacks, executes game turns, checks for a...
def onGridClick(self, event): if self.game_phase == "setup": # place boat boat_placement, isValid = self.getSelectedShipPlacement() if isValid: for pos in boat_placement: self.setGridSpaceContent(*pos, "boat") del self.boat_placement_queue[self.selected_ship_index] if self.selected_ship_inde...
def is_huffman_leaf(tree): """Whether this Huffman tree is a Huffman leaf.""" return not is_leaf(tree) and is_leaf(branches(tree)[0]) def letter(leaf): """The letter of a Huffman leaf.""" return label(branches(leaf)[0]) def branches(tree): return tree[1:]
The function `letters` extracts all unique characters encoded in a Huffman tree by recursively traversing its structure. If the tree is a leaf node, it returns the character stored there. For internal nodes, it combines results from all branches, aggregating characters from every leaf node. This collects all encoded le...
def letters(tree): """Return a list of all letters encoded in Huffman encoding TREE. >>> letters(example_tree) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] """ if is_huffman_leaf(tree): return [letter(tree)] else: lst = [] [lst.extend(letters(t)) for t in branches(tree)] ...
def branches(tree): return tree[1:] def is_huffman_leaf(tree): """Whether this Huffman tree is a Huffman leaf.""" return not is_leaf(tree) and is_leaf(branches(tree)[0]) def letter(leaf): """The letter of a Huffman leaf.""" return label(branches(leaf)[0])
The function `decode_one` decodes the first character from the binary code using a Huffman tree, then removes the corresponding bits from the code. It traverses the tree by popping bits from the code: moving left for 0 and right for 1. When a leaf node is reached, it returns the character and removes the used bits from...
def decode_one(tree, code): """Decode and remove the first letter in CODE, using TREE. >>> code = [1, 0, 0, 0, 1, 1, 1, 1] >>> decode_one(example_tree, code) 'b' >>> code # The initial 1, 0, and 0 are removed by decode_one [0, 1, 1, 1, 1] """ l = None while l is None: num = ...
def letter(leaf): """The letter of a Huffman leaf.""" return label(branches(leaf)[0]) def is_huffman_leaf(tree): """Whether this Huffman tree is a Huffman leaf.""" return not is_leaf(tree) and is_leaf(branches(tree)[0]) def branches(tree): return tree[1:]
This function recursively traverses a Huffman tree to build a dictionary mapping letters to their binary codes. It starts at node `t`, tracks the current path via `parent`, and when a leaf node matches the target letter `l`, stores the path in `dic[l]`. The recursion explores both branches, appending '0' or '1' to the ...
def encode(t, parent, l): if letter(t) == l: dic[l] = parent if is_huffman_leaf(t): return None elif parent == None: b = [b for b in branches(t)] encode(b[0], [0], l) encode(b[1], [1], l) else: b = [b for b in branch...
def buildHttpHeader(self, mountPoint: str, username: str, password: str): header = "GET /" + mountPoint + " HTTP/1.0\r\n" \ + "User-Agent: NTRIP Client/1.0\r\n" \ + "Accept: */*\r\n" \ + "Connection: close\r\n" \ + "Authorization: Basic " \ ...
The code establishes a TCP connection to a server, sends an HTTP authentication header with credentials, and continuously receives/data streams. It processes incoming data, handles disconnections by updating status flags, and raises exceptions on errors, maintaining a loop for stream parsing until the connection is inv...
def runServer(self): self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.conn.connect((self.ip, self.port)) self.conn.settimeout(self.connTimeout) self.conn.send(self.buildHttpHeader(self.mountPoint, self.username, self.password).encode('ascii')) print('Run') ...
def train_loop(self, phase): if phase == "train": dataset = self.dataloader.get_dataset("train") self.model.trainable = True else: dataset = self.dataloader.get_dataset("valid") total_step = len(dataset) if phase == "valid": se...
The main task of the code is to train a model for a specified number of epochs, validate it after each training epoch, track the validation loss, and implement early stopping if the validation loss does not improve for 20 consecutive epochs. It also saves the model when the validation loss improves and prints the best ...
def start(self): total_epoch = self.config["max_epoch"] min_valid_loss = 9999 save_valid_hr = None not_update_count = 0 for epoch in range(total_epoch): print("\n# Epoch {} #".format(epoch+1)) print("## Train Start ##") self....
def set_url_params(page, start, end, site_url): url = f"{site_url}?page={str(page)}&start={start}&end={end}&sort=DESC" print("URL:", url) return url def convert_date(date): year = date.split("-")[0] month = date.split("-")[1] new_formart = f"{month}{year}" print(new_formart) return new_f...
The code scrapes documents from specified websites based on date ranges and document types, extracts PDFs from search results, logs success/failure of requests, and generates a JSON output with metadata and extracted data. It iterates through pages, processes HTML content, and stores results in a global variable.
def run_scrape(start, end, document_types): global result result["metadata"]["query_start_date"] = start result["metadata"]["query_end_date"] = end print(document_types) site_lists = [] for type in document_types: site_lists += DOCUMENT_TYPE[type] for site in site_lists: prin...
def _check_event(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown(event) elif event.type == pygame.KEYUP: self._check_keyup(e...
The main task of the code is to run a game loop that continuously checks for events, updates the player's ship, manages bullets, and renders the game screen in real-time, creating an interactive gaming experience.
def rungame(self): while True: self._check_event() self.ship.update() self._update_bullet() self._updating_screen()
def VictoriasSecret(): check_time() print("You are in Victoria's Secret. Assistan come to you and ask if you need help. Do you need help or not?") choice_1 = input() if choice_1.lower()== "yes": print("The assistant was really helpful and you finaly found a perfume that you really like, but the ...
The code presents a narrative scenario where the user decides to explore one of four locations (Victoria's Secret, Lego store, Sephora, Macy's) in Pentagon City after gaining extra time. It prompts input to determine the user's choice and directs them to corresponding functions, with fallback responses for invalid inpu...
def start(): print("Welcome! You have a meeting with your best friend in Pentagon city near elevetors, but she is going to be late and now you have extra 30 minets. Do you want go somewhere?") choice = input() if choice.lower() == "yes": print("You are near entrance") move = input("\nWhere ...
def index_url(url: str) -> Resource | None: from . import db from . import resources import rich valid = validate_url(url) if not valid: return None try: resource: Resource = resources.create_resource(url) db.save_resource(resource) except Exception as e: ric...
The main task of the code is to index resources (e.g., articles, YouTube videos) into a vector search index. It accepts inputs via URL, file path, or YouTube playlist ID, validates required parameters like API keys for playlists, processes the resources, and updates the index. The function ensures either a URL or file ...
def index(url: str = typer.Option(None, help="URL of the resource to index."), file: Path = typer.Option(None, help="Path to a file with URLs of the resources to index."), playlist: str = typer.Option(None, help="YouTube playlist ID to index."), apikey: str = typer.Option(None, help="YouTu...
def UpdateState(self, lastAction, percept, game_over=False): X = self.agentLocation[0] Y = self.agentLocation[1] orientation = self.agentOrientation if (lastAction == Action.TURNLEFT): self.agentOrientation = (orientation + 1) % 4 if (lastAction == Action.TURNRIGHT): ...
The code processes environmental perceptions to guide an agent in a Wumpus world, making decisions to collect gold, navigate safely, avoid hazards, and escape. It checks conditions like gold presence, agent location, and wumpus threats, appending actions like GRAB, CLIMB, or movement paths. If blocked by dangers, it fi...
def Process (self, percept): actionList2 = [] self.UpdateState(self.lastAction, percept) if (self.actionList == []): if (percept.glitter): # HW5.4: If there is gold, then GRAB it print("Found gold. Grabbing it.") self.actionList.append(...
def makeIntro(self, subMis): print(f"Making intro!") title = subMis.title # query_string = self.kw_extrator.extract_keywords(title)[0][0] # downloader.download(query_string, limit=1, output_dir=SUB_BACKGROUND, adult_filter_off=False, force_replace=False, timeout=60, verbose=False, filt...
The code generates a list of videos based on a Reddit submission by retrieving the post, creating an intro, populating a video list, removing unusable content, and compiling final videos, then logging completion.
def generateVideoList(self): subMis = self.prawSession.submission(id=self.subId) print(f"Generating Videos for {subMis.title}") self.cmtsUrl = "https://www.reddit.com" + subMis.permalink self.makeIntro(subMis) self.populateList(subMis) self.removeUnusable() self...
def count_bombs(self, board): count=0 for i in range(self.rows): for j in range(self.columns): if board[i][j] == 'f': count+=1 return count def list_free(self, board): free_tiles = [] for i in range(self.rows): for j in ...
The code determines valid tile flags and clicks by evaluating all combinations of free spaces to meet the required bomb count. It generates subsets of free cells, tests each as potential flags, and retains only those combinations that produce a valid board. The result identifies tiles to flag (safe) and click (unsafe) ...
def combinatorics(self, board, total_bombs): current_bombs = self.count_bombs(board) free_spaces = self.list_free(board) x = len(free_spaces) if x == 0: return [] print('Combinatorics: n = '+str(x)+', b = '+str(total_bombs-current_bombs)) if x>=15: ...
def find_coborder(self, board): coborder = [] for i in range(self.rows): for j in range(self.columns): if self.is_coborder(board, (i, j)): coborder.append((i,j)) return coborder def list_neighbors(self, board, coords, tile_type): neighbors ...
This code uses set theory and neighbor analysis on a board to identify cells to open or flag based on coborder relationships, calculating potential safe moves by comparing neighbor counts and flag states, then appending these decisions to a click list for automated gameplay.
def set_theory(self, board): positions_open = set() positions_flag = set() coborders = self.find_coborder(board) for (first, second) in itertools.combinations(coborders, 2): first_neighbors = self.list_neighbors(board, first, '') second_neighbors = self.list_neigh...
def find_border(self, board): border = [] for i in range(self.rows): for j in range(self.columns): if self.is_border(board, (i, j)): border.append((i,j)) return border def powerset(self,full_set): x = len(full_set) subsets = {} ...
This code tests all possible subsets of border tiles on a board to determine valid flagging and clicking strategies. It generates power sets of border tiles, simulates flagging/clicking combinations, validates board states, and records optimal moves. The core task is to identify safe clicks and flags by exhaustively ch...
def test_borders(self, board): border = self.find_border(board) x = len(border) if x==0: return [] print('Borders: n = '+str(x)) if x>=15: print("Would take too long, skipping") return [] subsets = self.powerset(border) flag = (...
def flag_and_open(self, board): for i in range(self.rows): for j in range(self.columns): if board[i][j]!='' and board[i][j]!='f' and board[i][j]!=0: if board[i][j]-self.count_neighbors(board,(i,j),'f')==self.count_neighbors(board, (i,j),''): ...
The code solves a Minesweeper-like puzzle by applying strategies: flagging/opening cells, set theory, border testing, and combinatorial logic to identify safe moves. It returns a set of coordinates representing safe clicks to clear the board while avoiding bombs based on the given board state and total bomb count.
def solve(self,board,total_bombs): self.click = [] self.rows = len(board) self.columns = len(board[0]) self.flag_and_open(board) if self.click: return set(self.click) if self.click: return set(self.click) self.set_theory(board) if s...
def mouseDown(eX, eY, dragObj): if dragObj.active: if pointInRect(eX, eY, dragObj.outRect.x - dragObj.sBlk, dragObj.outRect.y - dragObj.sBlk, dragObj.sBlk * 2, dragObj.sBlk * 2): dragObj.TL = True return if pointInRect(eX, eY, dragObj.outRect.x + dragObj.outRect.w - dragObj.sBlk, drag...
This function handles mouse events to constrain dragging within a defined rectangular boundary. It adjusts coordinates to stay within specified limits and triggers actions like mouse down, up, move, or double-click on a drag object, using additional parameters for eye-related processing.
def dragrect(event, x, y, flags, param): dragObj, eyes = param if x < dragObj.keepWithin.x: x = dragObj.keepWithin.x if y < dragObj.keepWithin.y: y = dragObj.keepWithin.y if x > (dragObj.keepWithin.x + dragObj.keepWithin.w - 1): x = dragObj.keepWithin.x + dragObj.keepWithin.w - 1 if y > (dragObj.keepWithin...
def get_assignment(self): """Get user to choose canvas assignment""" headers = {'Authorization': f'Bearer {self.CANVAS_TOKEN}'} print('Getting assignments...') assignments = requests.get(f'https://learn.vccs.edu/api/v1/courses/{self.COURSE_ID}/assignments?per_page=1000', headers=headers).json() homeworks = ...
The main task of the code is to automate homework submission by sequentially retrieving the assignment, writing it to the school system, uploading the file, submitting it, and finalizing the process. This method orchestrates all necessary steps for seamless homework delivery.
def autorun(self): """Run all functions needed to submit homework""" self.get_assignment() self.write_assignment_to_school() self.upload_file() self.submit_assignment() self.finalize()
def generateGrass(player, heights): # generate Grass and Sand at Top layer takes the player, to add collision actors and the randomly generated height list for x in range(20): y = 19 - heights[x] if y < 9: block = Grass(str(str(absPath))+'Grass.png') addActor(block, Location(...
The code generates a procedurally created 2D terrain with varying heights, placing blocks (grass, gravel, etc.) with collision detection. It ensures terrain smoothness by limiting height changes to ±1 per step, differentiates gravel (falling blocks) from static blocks, and adds grass, trees, and water elements. The mai...
def generateGround(player): # Generate basic terrain print(' Generate World') heights = [] for i in range(20): if i == 0: heights.append(randint(7,13)) # initial block else: availHeights = [] for j in [-1,0,1]: # these are all "jumpable" heights ...
def generate_permutations(digits): permutations = list(it.product([0, 1], repeat=len(digits))) permutations = permutations[1:-1] return permutations def filter_valid_permutations(perms, digits): return [perm for perm in perms if is_valid_permutation(perm, digits)] def replacement_primes(perms, digits, p...
The main task of the code is to identify numbers between 10 and 999,999 that yield the maximum count of "replacement primes" through digit permutations. It generates primes up to 999,999, iterates through numbers, checks valid permutations of their digits, and tracks the highest prime count achievable by replacing digi...
def main(): prime_generator = PrimeGenerator() max_num = 999999 primes = prime_generator.generate_prime_list(max_num) max_prime_counts = [0]*len(primes) max_perm_dict = {} max_seen = 0 for i in range(10, max_num): if not primes[i]: continue digits = get_digits_from_num(i) ...
def load_model_from_config(config, ckpt, verbose=False, device="cuda"): print(f"Loading model from {ckpt}") pl_sd = torch.load(ckpt, map_location="cpu") if "global_step" in pl_sd: print(f"Global Step: {pl_sd['global_step']}") sd = pl_sd["state_dict"] model = instantiate_from_config(config.mo...
The code defines a worker function that processes jobs from an input queue in batches using a preloaded diffusion model. It loads model configurations, wraps the model for inference, and continuously checks for incoming jobs. When jobs are received, it batches them if they fit size constraints, processes them with the ...
def worker(in_queue: multiprocessing.Queue, out_queue: multiprocessing.Queue): print("Loading config") config = OmegaConf.load("/workspace/honkies-worker/v1-inference.yaml") print("Loading model") model = load_model_from_config(config, "/weights/sd.ckpt") print("Loading model wrap") model_wrap ...
def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ turn = player(board) result = [] for i in range(3): for j in range(3): if board[i][j] == EMPTY: result.append((i, j)) return result def player(board): """ ...
The code implements a minimax algorithm to determine the optimal move for the current player on a game board. It evaluates all possible moves, simulates resulting game states, and prioritizes moves leading to an immediate win. If no winning move exists, it selects the best move by maximizing/minimizing scores based on ...
def minimax(board): """ Returns the optimal action for the current player on the board. We need to make a treee that gets all of the game states possible that go through the possible next stages of the game. the best moves will be if it leads to a win """ #First we need to see if the result of ...
def load_yaml_file(filepath: Path) -> Dict[str, Any]: log.debug("Reading file {}", filepath) if filepath is None or not filepath.exists(): log.warning("Failed to read YAML file {}: File does not exist", filepath) return {} with open(filepath) as fh: try: docs = list(y...
The code checks and updates dependencies across Docker images, Python packages, and Angular projects. It parses configuration files, filters out specific versions, and checks for available updates using timeouts. The function skips checks based on parameters and logs filtered or removed dependencies.
def check_versions( skip_angular: bool = False, skip_docker: bool = False, skip_python: bool = False, npm_timeout: int = 1, dockerhub_timeout: int = 1, ) -> None: dependencies: Dependencies = {} if not skip_docker: backend = load_yaml_file(Path("controller/confs/backend.yml")) ...
def calc_kmeans(X, dataset): """ fit_predict KMeans algorithms for each k in k_values Calculate the five metrics for each k value, log in wandb and plot the score vs number for clusters for each metric """ sse_arr, davis_arr, silhouette_arr, vrc_arr, bic_arr = [], [], [], [], [] print("Working o...
The function `calc_scores_for_all` executes clustering algorithms (KMeans, DBSCAN, OPTICS, Agglomerative Clustering) on input data `X`, logs their performance metrics using Weights & Biases (wandb), and associates results with the specified dataset name. It initializes wandb, iterates through each algorithm, and record...
def calc_scores_for_all(X, dataset): """ Run the specified algorithms on the dataset and log metric scores in wandb :param X: Dataset feature values - dataframe or np array :param dataset: name of the dataset to log """ wandb.login() calc_kmeans(X, dataset) calc_dbscan(X, dataset) ca...
def lead_bias(art_sents, summ_sent_num, max_sent_len): """ Create leave-one-out articles and summaries. Args: art_sents (list[str]) : article sentences summ_sent_num (int) : number of sentences to be summary Returns: new_art (str) : new article new_summ (str) : new summary ...
The function processes an input dataset to evaluate the quality of a summary by generating new article and summary texts, computing ROUGE scores (1, 2, L), compression ratio, coverage, density, and novel word ratio, then updating the dataset with these metrics for analysis.
def _lead_bias_dataset(data): # NOTE: handle NaN input if not isinstance(data[art_column], str): data[art_column] = " " if not isinstance(data[summ_column], str): data[summ_column] = " " # Sentence tokenize art_sents = nltk.sent_tokenize(data[art_column]...
def recv(s): buffer = s.recv(32).decode("utf-8").replace("buffer: ", "") new_buffer = 1025 buffer = int(buffer) + 1 send(s, "ok") times_to_recieve = buffer / new_buffer output = "" while len(output) != buffer: output = output + s.recv(buffer).decode("utf-8") return ...
The main task of the code is to recursively download files and directories from a client. It identifies the type of data (file or directory), creates directories if needed, and processes each file by recursively calling itself. The function handles file transfers, directory creation, and metadata exchange to ensure pro...
def download2(all_files, client): filetype = recv(client) send(client, "ok") if filetype == "file\n": downloadfile(all_files, client) send(client, "done") recv(client) elif filetype == "dir\n": folder_name = recv(client)[:-1] try: os.mkdir(folder_name...
def create_socket(ip, port): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((ip,port)) sock.listen(5) set_socket(sock) return sock def connect(sock): s, address = sock.accept() return s, address def recv(s): buffer = s.recv(32).decode("utf...
This code starts a server on a specified IP address, authenticates a client via password verification, and if successful, allows file downloads from a shared directory. It writes "ok" or "no" to a temporary file based on authentication success and continuously lists files for download in an infinite loop.
def start_server(ip): temp = get_temp() print("Starting server") sock = create_socket(ip,65022) client, address = connect(sock) password = (recv(client))[:-1] send(client,get_pass()) if pass_check(password) == True: with open(temp, "w") as f: f.write("ok") ...
def clear_screen(): ''' Run the clear screen command based on the user's OS. ''' os.system('cls' if os.name=='nt' else 'clear') def get_timetable_json(startTime, endTime): ''' Fetches timetable from UofG servers and refactors them for grouping with itertools. ''' s = retrieve_session() ...
The main task of the code is to fetch a user's timetable from the University of Glasgow for a specified number of days, group events by date, and display each day's schedule with course names and time slots in the local timezone using formatted output.
def show_timetable(days): ''' Fetch your timetable from UofG. After which, display them in your local timezone. ''' clear_screen() startTime = int(time.time()) endTime = startTime + (86400 * days) timetable = get_timetable_json(startTime, endTime) timetable = itertools.groupby(timet...
def _get_spec(self): args_packages = [] yaml_file = [] for spec in self.args.packages: if isfile(spec): yaml_file.append(spec) else: args_packages.append(spec.strip('"\'')) if len(yaml_file) > 2: raise CondaValueError("n...
This code creates a Conda environment by checking if the target directory already exists as a Conda environment or regular directory. If so, it prompts the user to confirm removal of existing data. It then validates the prefix, forces reinstallation, installs the environment, marks it as a Conda environment, and prints...
def create(self): self._get_spec() if is_conda_environment(self.prefix): if paths_equal(self.prefix, context.root_prefix): raise CondaValueError( "The target prefix is the base prefix. Aborting.") if self.args.dry_run: raise Con...
def condition(stats, name): if stats['health'] >= stats['health_max'] - (stats['health_max'] / 3): print(f"{name} still in good condition, {stats['health']} Health remaining.") chance = 0 elif stats['health'] < (stats['health_max'] / 3): print(f"{name} in bad condition, {stats['health']}...
This function simulates a turn-based combat between a player and an opponent, handling attack choices, stamina management, and health checks. It determines if the opponent misses, processes player attack options (retreating, reserved swing, regular attack, aggressive strike), adjusts endurance and health values, and re...
def arena_fight(p_stats, o_stats, p_equip, o_equip): stumble_chance = condition(o_stats, f"{o_stats['name']} is") time.sleep(1) miss = stumble(stumble_chance) if miss == True: print(f"{o_stats['name']} misses!\n") else: ai_attack(o_stats, p_stats, o_equip, p_equip) if p_stats['he...
def usesavecon(num):#uses last saved connection credentials to login if os.path.exists("savecon.log"):#opens savecon.log file if already exists and grabs host,user, and password from last connection savefile = os.path.join(os.getcwd(),"savecon.log") save = open(savefile, "r") credlines= save...
The code's main task is to prompt the user to reuse saved login credentials or input new ones to establish a connection. It checks for the existence of a "savecon.log" file, offers to use saved details if available, and connects using either the retrieved saved credentials or newly provided ones via the 'creds()' funct...
def ask():#requests user to use saved connection to login or continue to login with new credentials if os.path.exists("savecon.log"): print("Would you like to use your previously saved login details?(y/n)") descision=input()#takes descision if descision == 'y': response=usesaveco...
def get_LR_and_trunk_it_before_start_date(self, fnombre, start_date): return self.__get_data_and_trunk_it_before_start_date( fnombre, self.__LR_DATA_FOLDER,"LR", start_date) def get_TI_and_trunk_it_before_start_date(self, fnombre, start_date): return self.__get_data_and_trunk_it_before_start_date(fnombr...
The main task of the code is to generate feature dataframes for each industry by combining lagged returns (LR) and technical indicators (TI), validate data consistency, save non-empty results to CSV, track empty/valid industries, and return unique feature names. It ensures data alignment, checks dataframe validity, and...
def create_feature_dataframe(self, **kwargs): print('Building features dataframe') print_info('TRUNCATE BEFORE {0}'.format(self.__parameters["start_date"]), file="stdout", flush=True ) dates = [] feature_names = [] feature_names2=[] non_empty_industries = [] ...
def try_ex(func): """ Call passed in function in try block. If KeyError is encountered return None. This function is intended to be used to safely access dictionary. Note that this function would have negative impact on performance. """ try: return func() except KeyError: re...
The code handles restaurant reservation requests by extracting and validating user inputs (location, cuisine, date, time, etc.), managing dialog flow with session attributes, and fulfilling the request by sending data to a queue. It uses slot validation to re-prompt users for missing/incomplete info and returns confirm...
def make_restaurant_reservation(intent_request): """ Performs dialog management and fulfillment for booking a hotel. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass informa...
def make_restaurant_reservation(intent_request): """ Performs dialog management and fulfillment for booking a hotel. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass informa...
The main task of the code is to route user intents to corresponding handler functions. The `dispatch` function checks the intent name from the request and calls specific functions like `make_restaurant_reservation` or `greeting_intent` based on the intent. If the intent is unsupported, it raises an exception, ensuring ...
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot...
def initialize_elements(self): self.explorer_button = tk.Button(self, text='BROWSE FILES',command=lambda: self.browse_files('./sudokus'), font=("Helvetica", 16), **self.button_setting) self.image_label = tk.Label(self, text='No Image Chosen', font=('Helvetica', 16), bg='#F9E4D4', fg='#9C0F48', border=0)...
This code initializes a Tkinter GUI frame with a custom background, defines button styles, loads a placeholder image, and sets up UI elements. It prepares the interface for image display and interaction, using methods to initialize components and position them, while storing the chosen image path and applying predefine...
def __init__(self, master): tk.Frame.__init__(self, master) self.config(bg = '#F9E4D4') self.button_setting = { 'bg': '#9C0F48', 'fg': '#F9E4D4', 'border': 0, 'highlightthickness': 1, 'activebackground': '#470D21', 'wid...
def parse_message_for_tickets(self, message): """ Parse a message and create an integer list of ticket numbers. """ message_split = message.split(" ") ticket_list = [] for word in message_split: if not word: continue if word[0] == '#': ...
The code processes incoming messages in a bot to handle specific commands related to ticket tracking and updates. It parses messages for ticket numbers, retrieves ticket details, and sends formatted responses. It supports commands like `!response` (to update tickets from a certain date), `!update` (to refresh cache), `...
def on_message(self, ctx): try: # Don't exit the bot when an error happens. if ctx.command and ctx.command[0] != '!': # Ticket linker. try: ticket_list = self.parse_message_for_tickets(ctx.message) response = "" ...
def getinfo(box, srcpath): mx, my, Mx, My = bigbox(srcpath) width = Mx - mx height = My - my return width, height def bigbox(location): rows, cols = [], [] for fname in glob.glob( location + "/*.bundle"): row, col = rcfromname(path.basename(fname)) rows.append(row) cols.a...
This code converts geospatial cache files (e.g., .bundle) into a .pjp data file and .idx index file, supporting version 1/2 formats. It reads input files, extracts data blocks, writes them to the output, and records offsets/sizes in the index. The function handles platform-specific configurations, processes tiles in ba...
def cache2mrf(srcpath, dst, version = 2): #if sys.platform != "win32": # with open(dst + "mrf_info", "w") as infofile: # startx = -20050000 # starty = 30200000 # res = 0.26458386250105836 * 256 # ox = startx + mx * res # oy = starty - my * res # ...
def initialize_model(model_type, train_data, config, custom_bottom, seed): """ Initialize batch generator and model from config """ inp_shape = (None, train_data['x'].shape[1]) # initialize batch generator dg = DataGenerator(x=train_data['x'], y=train_data['y'], ...
The main task of the code is to train a machine learning model (base, binary, or contrastive) using provided data, save training/validation loss histories, and output predictions. It initializes the model, executes type-specific training with optimizers, records loss metrics in a DataFrame, and stores results in CSV an...
def train_save(args, train_data, val_data, config, seed): # initialize model if args['verbose'] == 1: print("Initialize model...") data_gen, model = initialize_model(args['model_type'], train_data, config, custom_bottom, seed) # train model if args['verbose'] == 1: print("Train mode...
def _find(root, sec): if sec == '': return root else: curr_sec = sec.split('/')[0] rest_of_sec = '/'.join(sec.split('/')[1:]) for n in root.children: if n.value == root.value + '/' + curr_sec: return _find(n, rest_of_sec) return None def _get_LCA(r...
The code calculates the distance between two nodes in a tree using their distances from the root and their lowest common ancestor (LCA). It verifies the root's existence, locates the nodes for given sections, checks their validity, computes the LCA, and applies the formula: distance = d(root, p1) + d(root, p2) - 2*d(ro...
def get_distance(p1_sec, p2_sec, root): # d(p1, p2) = d(r, p1) + d(r, p2) - 2*d(r, lca(p1, p2)) if root is None: print('Root not found!') return -1 n1 = _find(root, p1_sec) if n1 is None: print(p1_sec + ' is not in the section tree') return -1 n2 = _find(root, p2_sec)...
def get_section_tree(sections_in_page): root = Node(sections_in_page[0].split('/')[0]) for s in sections_in_page: _insert(root, s) return root def print_nodes(r): print(r) for n in r.children: print_nodes(n) def _get_LCA(root, n1, n2): if not _is_reachable(root, n1) or not _is_re...
The code reads a QREL file to group Wikipedia article sections by parent pages, constructs a section tree for a specific article, computes the Lowest Common Ancestor (LCA) of two subsections, and calculates their hierarchical distance.
def main(): q = "D:\\wikimarks_data\\en-wiki-01012022\\benchmarks\\good-articles\\good-articles.train\\train.pages.cbor-hierarchical.qrels" sections = {} with open(q, 'r') as f: for l in f: s = l.split(' ')[0] p = s.split('/')[0] if p in sections.keys(): ...
def Create_Generator(): model = keras.Sequential() model.add(keras.layers.Dense(7 * 7 * 256, use_bias=False, input_shape=(100,))) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.LeakyReLU()) model.add(keras.layers.Reshape((7, 7, 256))) model.add(keras.layers.Conv2DTranspose(...
The code trains a Generative Adversarial Network (GAN) on the MNIST dataset, continuing from epoch 20 to 70. It loads and preprocesses MNIST data, initializes generator and discriminator models with Adam optimizers, and uses `continue_train_GAN` to resume training for 50 epochs. The task involves generating handwritten...
def main(): # Load the MNIST dataset (x_train, y_train), (_,_) = keras.datasets.mnist.load_data() print(x_train.shape, y_train.shape) x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 175.5 - 1 dataset = tf.data.Dataset.from_tensor_slices(x_train).shuffle(60000).batch(BATCH_SIZE) ...
def build_prejoin_tables(database_name, table_1_name, table_1_var, table_2_name, table_2_var, tokens): table_1_args, table_2_args, join_on_args = helper.three_arg_lists(tokens, table_1_var, table_2_var) table_1 = load_and_whereselect(database_name, table_1_name, table_1_args) table_2 = load_and_whereselect...
The function `binary_join` performs a binary join operation between two tables in a database based on specified join type (inner, left outer) and tokens. It determines the join strategy by analyzing input parameters, constructs intermediary tables using `build_prejoin_tables`, and executes the join (inner or outer) wit...
def binary_join(database_name, table_names, tokens): table_1_name = table_names[0] table_1_var = table_names[1] if(len(table_names) == 4): #strategy here is to perfrom the independent table evaluations # by generating intermediary token interverls to check for each table # then to j...
def gen_cities(n, max_xy, threshold=float("inf")): min_xy = max_xy / 200.0 def coord(): return min_xy + random.uniform(min_xy, max_xy) cities = [(coord(), coord()) for i in range(n)] points = [] for i, p in enumerate(cities): points.append((p[0], p[1], i)) return points def exact...
The function `exact_trial(n)` generates a set of `n` cities, solves the Traveling Salesman Problem (TSP) exactly to find the optimal path, measures the computation time, calculates the total distance of the optimal path, and returns the number of cities, runtime, and distance. It uses `gen_cities` to create city coordi...
def exact_trial(n): cities = gen_cities(n,500) #cities = read_cities() start_time = datetime.datetime.now() path = exact_tsp(cities) print(path) runtime = (datetime.datetime.now() - start_time).total_seconds() distance = total_distance(cities, path) return len(cities), runtime, dis...
def quiesce( alpha, beta, board ): stand_pat = evaluate_board(board) if( stand_pat >= beta ): return beta if( alpha < stand_pat ): alpha = stand_pat for move in board.legal_moves: if board.is_capture(move): make_move(move, board) score = -quiesce( -beta, ...
This code implements the alpha-beta pruning algorithm for game tree search, recursively evaluating legal moves on a board. It uses quiesce() for depth-0 evaluation, iterates through possible moves, and updates the best score while pruning branches where the current score exceeds beta. The function returns the optimal s...
def alphabeta( alpha, beta, depthleft, board ): bestscore = -9999 if( depthleft == 0 ): return quiesce( alpha, beta, board ) for move in board.legal_moves: make_move(move, board) score = -alphabeta( -beta, -alpha, depthleft - 1, board ) unmake_move(board) if( score >=...
def make_move(mov, board): update_eval(mov, board.turn, board) board.push(mov) return mov def alphabeta( alpha, beta, depthleft, board ): bestscore = -9999 if( depthleft == 0 ): return quiesce( alpha, beta, board ) for move in board.legal_moves: make_move(move, board) sc...
The function `selectmove` selects the best chess move using either a pre-defined opening book (from "bookfish.bin") or a depth-limited alpha-beta pruning algorithm. It prioritizes book moves when available; otherwise, it evaluates all legal moves recursively, applying alpha-beta pruning to determine the optimal move ba...
def selectmove(depth, board): try: move = chess.polyglot.MemoryMappedReader("bookfish.bin").weighted_choice(board).move() # movehistory.append(move) return move except: bestMove = chess.Move.null() bestValue = -99999 alpha = -100000 beta = 100000 f...
def read_cities(file_name): """ Read in the cities from the given `file_name`, and return them as a list of four-tuples: [(state, city, latitude, longitude), ...] Use this as your initial `road_map`, that is, the cycle Alabama -> Alaska -> Arizona -> ... -> Wyoming -> Alabama. """...
The main task of the code is to read city data from a file, display the cities, compute the optimal traveling salesman cycle using `find_best_cycle`, and print the resulting route. It sequentially executes reading, displaying, optimizing, and outputting the city data in a cycle.
def main(): """ Reads in, and prints out, the city data, then creates the "best" cycle and prints it out. """ road_map=read_cities('city-data.txt') print_cities(road_map) best_map = find_best_cycle(road_map) print_map(best_map)
def queryloop(messages): while True: resp = gptquery(messages) if re.match("\[QUERYRESPONSE\] (.+)", resp): print(re.match("\[QUERYRESPONSE\] (.+)", resp).groups()[0]) return resp[len("[QUERYRESPONSE] "):] else: for command in sample_config["commands"]: ...
The main task of the code is to process a user's query by formatting it with "[USERQUERY] " and passing it to `queryloop` alongside starter messages, enabling further dialogue or processing in a chatbot or messaging system.
def userquery(query_text): return queryloop(add_message("user", f"[USERQUERY] {query_text}", generate_starter_messages()))
def handTotal(self): self.player_total = 0 for i in self.player_hand: if i == 1: ace = tkMessageBox.askquestion("Aces","You have an Ace! Do you want it to be worth 1?", ) if ace == "no": i = 11 self.player_total += i if ...
The code's main task is to determine the game outcome by comparing player and dealer totals. It checks for busts, blackjack, and total values to set `self.win` to True or False, then triggers the end screen.
def totalCheck(self): self.handTotal() self.compHandTotal() if self.dealer_total > 21: self.win = True if self.player_total == 21: self.win = True elif self.dealer_total == 21: self.win = False elif self.player_total > self.dealer_total...
def load_openai_gpt(n_special=1, n_ctx=512): text_encoder = TextEncoder("pytorch-openai-transformer-lm/model/encoder_bpe_40000.json", "pytorch-openai-transformer-lm/model/vocab_40000.bpe") encoder = text_encoder.encoder n_vocab = len(text_encoder.encoder) vocab = n_vocab +...
The main task of the code is to evaluate a GPT model's text generation quality by calculating perplexity, comparing generated sentences with reference corpora (TBC/Wiki103) using BLEU scores, and analyzing n-gram uniqueness. It writes results to files, including generated text, perplexity metrics, BLEU scores, and n-gr...
def evaluate_gpt(output_file_path:str): settings.write_debug("Loading and Generating GPT model") gpt_model, gpt_text_encoder = load_openai_gpt(n_special=1) openai_sents = generate_openai(gpt_model, gpt_text_encoder, ...
def load_img(self, img_load_path: str) -> np.ndarray: img = Image.open(img_load_path) self.logger.info(f"Loaded image from path '{img_load_path}'.") return np.array(img) def connect_the_dots( self, img: np.ndarray, algorithm: str, line_color: np.ndarray ) -> np.ndarray: # mak...
The main task of the code is to process an input image by connecting dots using a specified algorithm and line color, then saving the modified image. It loads the image, applies the dot-connection algorithm with the given parameters, and stores the result at the specified output path, logging progress and completion.
def process_img( self, img_load_path: str, img_save_path: str, algorithm: str, line_color: np.ndarray, ) -> None: img = self.load_img(img_load_path) self.logger.info("Connecting the dots ...") img = self.connect_the_dots(img, algorithm, line_color) ...
def del_mod(self): del self.mod gc.collect() def set_up_energy(self): self.nbins = self.log10MeV.shape[0] delta_e = self.log10MeV[1] - self.log10MeV[0] delta_p = delta_e / self.ppb log_e_space = np.linspace(self.log10MeV[0], self.log10MeV[-1] + delta_e, num=self.nbins * s...
The function `fractured_propagation` processes energy data in chunks by dividing the `log10MeV` array into 20-element segments. For each segment, it sets up energy parameters, runs propagation simulations using the `propagation` method, and stores results in a numpy array `p`. The process manages memory by loading and ...
def fractured_propagation(self, seed=None, weights=None, index=-2): try: self.del_mod() except AttributeError: pass print('seed:', seed) if seed is None: raise UnphysicalError log10MeV = self.log10MeV.copy() length = log10MeV.shape[0] ...
def get_startArticle(self): try: articleDetails = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "article-details"))) except: print('No Starting Article Found') heading = articleDetails.find_element_by_id('full-view-heading') ...
The code performs multi-layer web scraping starting from a given article. It navigates to the initial article, extracts its ID, and scrapes cited-by articles. It iteratively opens new links across specified layers, collecting data into a database. The process handles exceptions, waits before quitting the browser, and r...
def runScraping(self, total_layers, startArticle): self.total_layers = int(total_layers) self.startArticle = startArticle self.driver.get(self.startArticle) try: self.get_startArticle() startID = self.startArticle[-10:] self.population = 1 ...
def edge_detection_canny(cv2image: Image): """ Perform edge detection on the given image using the Canny algorithm. Returns the image with edges highlighted. """ img = cv2.flip(cv2image, 1) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.GaussianBlur(img, (7, 7), 1, 1) img = cv2.Ca...
The function generates a path through an image by detecting edges via Canny, converting edge pixels to points, planning a path, and straightening it. It returns the smoothed path and "jump" points (discontinuities >2 units apart).
def get_path(cv2image: Image) -> Tuple[List[Point2D], List[Point2D]]: """ Generates a path through an image. Returns the path as a list of points and a list of "jump" points (points more than 2 units away from their nearest neighbor). """ corners_detected = edge_detection_canny(cv2image) poi...
def edge_detection_canny(cv_image): img = cv2.flip(cv_image, 1) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.GaussianBlur(img, (3, 3), 0) # img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) img = cv2.Canny(img, 10, 200) # cv2.imshow("canny",...
The main task of the code is to process an input image by detecting edges using Canny, converting detected edges into coordinate points, planning a path with potential jumps, and then straightening the path to return refined coordinates and jump points for navigation or analysis.
def get_path(cv2image) -> Tuple[List[Point2D], List[Point2D]]: corners_detected = edge_detection_canny(cv2image) points = path_pixels_to_points(corners_detected) path, jumps = path_planning(points) path = straighten_lines(path, jumps) return path, jumps
def go_to_point(p, z=238): go_to(p[0], p[1], z) def jump(p1, p2): go_to_point(p1, z=245) go_to_point(p2, z=245) go_to_point(p2) def go_to(x: float, y: float, z: float, a: float = -180.0, b: float = 0.0, c: float = 135.0): target_p1 = f"{x:.2f}, {y:.2f}, {z:.2f}, {a:.2f}, {b:.2f}, {c:.2f}" script...
The code navigates through a series of path nodes, moving to each point while checking if the previous node requires a jump (via `jump_nodes`). It starts at the first node, processes each path node with jumps or direct movement, and returns to the initial position. The task involves ensuring `calculate_path()` returns ...
def draw(path_nodes, jump_nodes): # TODO: Modify return type in calculate_path() # such that `if prev_node in jump_nodes` is valid path_nodes = np.array(path_nodes) jump_nodes = np.array(jump_nodes) prev_node = path_nodes[0] # Go to the first node go_to_point(prev_node, z=300) go_to_po...
def resize(img: Image, dim_limit=720) -> Image: """ Resizes an image so that the maximum dimension (either width or height) does not exceed a given limit. Returns the resized image. """ max_dim = max(img.shape) if max_dim > dim_limit: resize_scale = dim_limit / max_dim img = cv2....
The function transforms a path from a template image into world or pixel coordinates on a canvas image using perspective transformation. It resizes the template, determines orientations, calculates corner mappings, applies perspective transformation, and returns transformed path and jump points as lists of coordinates.
def calculate_path(canvas, template, to_world=True) -> Tuple[List[Point2D], List[Point2D]]: """ Transforms a path from a template image to world coordinates or pixel coordinates on a canvas image. Returns the transformed path as a list of points. If to_world is True, the path is scaled to world coordina...
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Document detector") parser.add_argument('-i', '--input', help="Path to image") parser.add_argument('-i2', '--input2', help="Path to image 2") parser.add_argument('-o', '--output', help="split, marked, face or prod", de...
This code processes an input image using OpenCV, offering multiple modes: marking detected rectangles with contours, splitting the image into sheets, generating patterns, or detecting faces. It resizes images, draws annotations, and displays/saves results based on command-line arguments. The core tasks involve image se...
def main(): args = parse_args() # I/O and resize image if it's pretty large for GrabCut img = cv2.imread(args.input) assert img is not None # img = resize(img) if args.output == "marked": rectangles = get_rectangles(img, draw_contours=True) # Displaying the contours and corne...
def go_to(x: float, y: float, z: float, a: float = -180.0, b: float = 0.0, c: float = 135.0): target_p1 = f"{x:.2f}, {y:.2f}, {z:.2f}, {a:.2f}, {b:.2f}, {c:.2f}" script1 = "PTP(\"CPP\"," + target_p1 + ",100,200,0,false)" send_script(script1) def take_picture(job=2): send_script(f"Vision_DoJob(job{job})"...
The code captures two face images, processes them to compute a path, and draws the path. It takes a picture, waits for a second image, then uses image comparison to generate path nodes for drawing.
def draw_face_loop(): """ Draw Face """ # Take a picture of the face go_to(450, 250, 650, 90, 0, 45) take_picture() start = time.time() filename = f'images/IMG.png' images = [] while True: if exists(filename): time.sleep(1) image = cv2.imread(...
def get_sheets(cv2image: np.ndarray, n: int) -> List[Rectangle]: """ Return n largest rectangles in image """ # Find candidate contours and calculate corner if it can be approximated to rectangle contours = find_contours(cv2image) rectangles = [] for contour in contours: corner = ap...
The function generates a path to copy an image from a canvas to a template, returning lists of 2D points in either pixel or world coordinates based on the `to_world` parameter. It identifies canvas and template regions from input sheets, then computes the transfer path between them.
def copy_image(cv2image: Image, to_world=True) -> Tuple[List[Point2D], List[Point2D]]: """ Generates a path for copying an image from a canvas onto a template. Returns the path as a list of points. If to_world is True, the path is scaled to world coordinates. Otherwise, it is left in pixel coordinates. ...
def get_sheets(cv2image: np.ndarray, n: int) -> List[Rectangle]: """ Return n largest rectangles in image """ # Find candidate contours and calculate corner if it can be approximated to rectangle contours = find_contours(cv2image) rectangles = [] for contour in contours: corner = ap...
The function generates a path to draw a face from a source image onto a canvas, returning lists of 2D points. It uses a template from the source image and scales coordinates to world units or keeps them in pixel coordinates based on the `to_world` parameter.
def draw_face(cv2image_face: Image, cv2image_canvas: Image, to_world=True) -> Tuple[List[Point2D], List[Point2D]]: """ Generates a path for drawing a face from a source image onto a canvas. Returns the path as a list of points. If to_world is True, the path is scaled to world coordinates. Otherwise, it ...
def go_to(x: float, y: float, z: float, a: float = -180.0, b: float = 0.0, c: float = 135.0): target_p1 = f"{x:.2f}, {y:.2f}, {z:.2f}, {a:.2f}, {b:.2f}, {c:.2f}" script1 = "PTP(\"CPP\"," + target_p1 + ",100,200,0,false)" send_script(script1) def take_picture(job=2): send_script(f"Vision_DoJob(job{job})"...
The code initializes a ROS2 node, deletes an existing image file, moves to a specified 3D coordinate, captures an image, and enters a loop to draw a face on the image. It then shuts down the ROS2 node.
def main(args=None): rclpy.init(args=args) filename = f'images/IMG.png' if exists(filename): time.sleep(1) remove(filename) # Take a picture go_to(350, 350, 730) take_picture() # set_io(1.0) # go_to(326.5, 400, 100, b=0, c=0) # Enter into the main loop draw_fac...
def parse_args() -> argparse.Namespace: """ Parses command line arguments using argparse. Returns an object with the parsed arguments as attributes. """ parser = argparse.ArgumentParser(description="Document detector") parser.add_argument('-i', '--input', help="Path to image") parser.add_arg...
The code processes an input image by resizing it if necessary. Depending on the 'output' argument, it either copies the image or overlays a face from a second image. It then visualizes the result by drawing detected points and displaying the image using OpenCV. The task involves image manipulation, conditional processi...
def main(): """ Main function that reads an input image, processes it, and displays the result. If the output command line argument is "copy", the function generates a path for copying the input image. If the output command line argument is "face", the function generates a path for drawing a face from a...
def generate_start_population(population_size, demands): start_population = [] for _ in range(population_size): start_population.append(random_chromosome(demands)) return start_population def find_objective_functions_dap(chromosomes, demands, links, module_capacity): funs = [] for chromosom...
This function implements a genetic algorithm to optimize a multi-objective problem (DAP) by evolving a population of solutions through selection, crossover, mutation, and elitism. It iteratively improves the population by generating offspring, evaluating their fitness, retaining the best solutions, and discarding the w...
def calculate_dap(demands, links, module_capacity, population_size, simulation_limit, offsprings_size, crossover_probability, mutation_occur_probability, mutation_probability): iter_without_improvement = 0 current_generation_number = 0 parents_generation = generate_start...
def load_balances(self): """ Get all balances # sample at data-samples/client-account.py { "ETH": { "free": 6.85e-05, "locked": 99.99 }, "USDT": { "free": 0.102321, "locked": 0.0 }...
The main task of the code is to automate trading by buying a randomly selected asset and placing multiple sell orders at increasing price levels, ensuring compliance with exchange rules to avoid errors. It checks for sufficient funds, executes a purchase, then creates structured sell orders with precise quantity and pr...
def run(self): """ Run the bot """ self.load_balances() now = datetime.now() current_time = now.strftime("%Y-%m-%d %H:%M:%S") if not self.have_money_to_invest(): self.notify(f'NOT ENOUGH MONEY TO INVEST {current_time}') return self.no...
def calculate_entropy(x: pd.Series) -> float: """Entropy of column (single feature X). Args: x (pd.Series): Single column. Returns: float: Entropy value """ count = x.value_counts() probabilities = count / len(x) entropy = -sum(probabilities * np.log2(probabilit...
The function calculates the maximum Information Theoretic Predictive Relevance (ITPR) of Y over X by iterating through unique values of Y, computing weighted conditional entropy for each, and returning the highest ITPR value, which quantifies how much information Y provides about X's distribution.
def calculate_ITPR(X: pd.Series, Y: pd.Series) -> float: """ITPR. Args: X (pd.Series): _description_ Y (pd.Series): _description_ Returns: float: _description_ """ unique_values_Y = Y.unique() omega_Y_size = len(Y.unique()) # H(X)) H_X = calculate_entropy(X) ...
def start_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False keys = pygame.key.get_pressed() if keys[pygame.K_UP]: self.colorState = 'startYellow' if keys[pygame.K_DOWN]: ...
This code runs a game loop managing different states ('start', 'playing', 'gameOver'). It updates, handles events, and draws game elements based on the current state, maintaining a set FPS. The loop exits when 'running' is False, then quits Pygame and exits the program.
def run(self): while (self.running): self.clock.tick(FPS) if (self.state == 'start'): self.l = 0 self.start_events() self.start_update() self.start_draw() elif (self.state == 'playing'): self.pla...
def create_random_list(length, max_value): return [random.randint(0, max_value) for _ in range(length)] def quicksort(L): copy = quicksort_copy(L) for i in range(len(L)): L[i] = copy[i] def mergesort(L): if len(L) <= 1: return mid = len(L) // 2 left, right = L[:mid], L[mid:] ...
The code compares the performance of quicksort, mergesort, and heapsort by measuring their execution times on randomly generated lists of increasing sizes. It runs each algorithm $n$ times, generating lists of sizes from 0 to $n-1$ (with maximum element value $m$), records the time taken for each sort, and returns the ...
def exp4(n,m): quick_times=[] merge_times=[] heap_times=[] for i in range(n): L=create_random_list(i,m) L2 = L.copy() L3 = L.copy() start= timeit.default_timer() quicksort(L) end=timeit.default_timer() quick_times.append(end-start) ...
def create_random_list(length, max_value): return [random.randint(0, max_value) for _ in range(length)] def insertion_sort(L): for i in range(1, len(L)): insert(L, i) def bubble_sort(L): for i in range(len(L)): for j in range(len(L) - 1): if L[j] > L[j+1]: swap(L,...
The code `exp1(n, m)` compares the performance of insertion sort, bubble sort, and selection sort by measuring their execution times on randomly generated lists of increasing sizes (from 0 to n-1 elements). For each list size, it creates three copies, sorts them using each algorithm, records the time taken, and stores ...
def exp1(n,m): insert_times=[] bubble_times=[] select_times=[] for i in range(n): L=create_random_list(i,m) L2 = L.copy() L3 = L.copy() start= timeit.default_timer() insertion_sort(L) end=timeit.default_timer() insert_times.append(end-start) ...