dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def setClock(self): self.timeM = self.time//60 self.timeS = self.time%60 self.updateClock() def newImage(self): self.completedImages+=1 if(self.completedImages>=self.images): self.endSession() else: self.addMaxIndex() self.nextImage() d...
This code implements a countdown timer that decrements seconds every second, resets seconds to 59 when reaching zero, decrements minutes accordingly, and updates the clock display. It uses a recursive timer to maintain the countdown loop, calling itself after 1 second.
def reduceSecond(self): self.cancelid = self.activeSession.after(1000,self.reduceSecond) self.timeS-=1 if(self.timeS<0): self.timeS=59 self.timeM-=1 if(self.timeM<0): self.setClock() self.newImage() self.updateClock()
def _run_command(command: list[str]) -> Response: """ Run a command against docker. Args: command: LIst of command parts to run Returns: Response data class """ result = subprocess.run(command, stderr=PIPE, stdout=PIPE) if result.returnco...
The main task of the code is to process binary files by analyzing their dependencies using `ldd` inside a Docker container, determining their origin, defining save paths, and copying them to a specified directory structure. It iterates through each binary, executes dependency checks, parses results, and handles file co...
def _process_binaries(self, binaries: list[str]): """ Process and copy binary files. Args: binaries: List of binary files to process """ for binary in binaries: command: list[str] = [ 'docker', 'exec', self....
def choose_action(self): # return best action out of a list of possible ones actions = self.get_actions() (self.prev_q, self.prev_feats), action = max([(self.evaluate(v), v) for v in actions], key=lambda a: a[0][0]) return action def update(self, reward): # update weights based on current, pre...
The code's main task is to train a model by first selecting an action using `choose_action()`, then updating the model with a reward calculated via `get_reward()` based on the selected action. This process iteratively improves the model's performance by learning from the reward feedback, typical in reinforcement learni...
def train(self): # train model once self.net = self.choose_action() self.update(self.get_reward(self.net))
def _validate_varchar(self, s, l=255): s = str(s) if len(s) > l: raise ValueError("String \"" + s + "\" too large for VARCHAR size " + l) return s def _validate_ip_address(self, addr, version): version = str(version) if version is not N...
The main task of the code is to create a new server entry in a database by validating input parameters, inserting a record into the "Server" table, retrieving the generated server ID, and updating server attributes using that ID. It handles database operations with error checking and returns the newly created server's ...
def create_server(self, name=None, ip_addr=None, ip_v=None, lid=None): name = self._validate_varchar(name) if name is not None else None ip_addr, ip_v = self._validate_ip_address(ip_addr, ip_v) lid = self._validate_int(lid) if lid is not None else None q...
def generate_CLI(self): print("\t" + "-------------") for i in range(3): print("\t" + "|", end=" ") for j in range(3): if self.state[i][j] == -1: print("X", end=" | ") elif self.state[i][j] == 1: print("O", e...
This code runs a game loop where a player and computer take turns making moves on a grid. It handles user input for row/column selection, updates the game state, checks for terminal conditions (win/loss/draw), and displays results. The loop continues until the game ends, with the computer responding after each valid pl...
def start(self): game_start = True round = 0 a = 0 while a == 0: round = round + 1 print("\n") print("\t" + "Round " + str(round).center(20)) self.generate_CLI() col = int(input("\tColumn (1-3): ")) row = int(inpu...
def choose_version(words): """ (list) -> list Function that accepts the list of words and prompts the user for the version of hangperson he/she wants to play and returns the modified/unmodified list of words (according to the version chosen) """ valid=False while not valid: ...
The main task of the code is to initialize and execute a Hangperson game. It selects a subset of words using `choose_version`, picks a secret word from the list with `choose_secret_word`, and then launches the game loop via `play_hangperson` with the chosen word. The code structures the game setup and execution流程, rely...
def main(): '''() -> () main function for playing hangperson ''' words = ['APPLE', 'PUMPKIN', 'SCARECROW', 'BAT', 'GHOST','CROQUET','CRYPT','IVORY','COLGATE','JUKEBOX','KIOSK','QUAD','ZIGZAG','ZOMBIE','ALPHA','BETA','GAMMA','RHYTHM','MELODY','GUITAR','PIANO','FORTISSIMO'] words=choose_version(words...
def user_turn(user_moves,places_taken,dictionary,user_symbol): user=user_input(places_taken,dictionary) user_moves.append(user) places_taken.append(user) draw_pattern(user_symbol,user,dictionary) return user def win_or_block(computer_moves, user_moves): win = [['1', '2', '3'], ['4', '5', '6'], [...
This function simulates a free-play game where the user and computer take turns making moves on a board. The computer prioritizes winning or blocking the user's win, otherwise selects a random move. The game continues until a player wins or the board is full (draw). It returns updated user/computer moves and occupied p...
def freeplay(first_in_free_play,user_moves,computer_moves,places_taken,dictionary,user_symbol,computer_symbol): if first_in_free_play=="user": user=user_turn(user_moves,places_taken,dictionary,user_symbol) while True: if win_or_block(computer_moves,user_moves)!=-1: ...
def check_win(current_list): win = [["1","2","3"],["4","5","6"],["7","8","9"],["1","4","7"],["2","5","8"],["3","6","9"],["1","5","9"],["3","5","7"]] for win_move_list in win: cnt = 0 for win_move in win_move_list: if win_move in current_list: cnt += 1 if cnt ...
This function implements a computer's strategic response in a Tic-Tac-Toe game, prioritizing blocking user wins, creating winning opportunities, and selecting optimal moves based on corner positions. It uses lookup dictionaries to determine midpoints and corners, handles specific turn scenarios, and falls back to rando...
def user_corner(user_symbol,computer_symbol,user_moves,computer_moves,dictionary,places_taken,user1): check_corner_dict = {'1':['6', '8'], '3':['4', '8'], '9':['2', '4'], '7':['2', '6']} corner_mid_dict = {'16' : '4', '18' : '2', '38' : '2', '34' : '6', '92' : '8', '94' : '6', '72' : '8', '76' : '4'} cnt = ...
def check_win(current_list): win = [["1","2","3"],["4","5","6"],["7","8","9"],["1","4","7"],["2","5","8"],["3","6","9"],["1","5","9"],["3","5","7"]] for win_move_list in win: cnt = 0 for win_move in win_move_list: if win_move in current_list: cnt += 1 if cnt ...
The function manages a game loop where a user and computer take turns making moves. It checks for wins/draws, and the computer uses strategic logic to either block the user, aim for a win, or make random moves. The loop continues until the computer wins, with the user's moves and game state tracked through parameters l...
def user_center(user_symbol,computer_symbol,user_moves,computer_moves,dictionary,places_taken,user1): cnt = 0 while not(check_win(computer_moves)): cnt +=1 user = user_turn(user_moves, user_moves + computer_moves, dictionary,user_symbol) if not(check_draw(user_moves+computer_mov...
def check_win(current_list): win = [["1","2","3"],["4","5","6"],["7","8","9"],["1","4","7"],["2","5","8"],["3","6","9"],["1","5","9"],["3","5","7"]] for win_move_list in win: cnt = 0 for win_move in win_move_list: if win_move in current_list: cnt += 1 if cnt ...
The function determines the computer's optimal move in a Tic-Tac-Toe game by evaluating user moves, edge positions, and potential winning/blocking strategies. It uses predefined position mappings and conditional logic to select moves that prioritize blocking the user, securing corners/edges, or making random choices wh...
def user_edge(user_symbol,computer_symbol,user_moves,computer_moves,dictionary,places_taken,user1): edge_dict_check = {'24':'9', '42':'9', '26':'7', '62':'7', '68':'1', '86':'1', '48':'3', '84':'3'} edge_dict = {'2':['7', '9'], '4':['3', '9'], '6':['1', '7'], '8':['1', '3']} edge_corner= {'61' : '3', '67' :...
def computer_first_turn(): return random.choice(["1","3","5","5","5","7","9"]) def computer_turn(computer,computer_moves,places_taken,dictionary,computer_symbol): computer_moves.append(computer) places_taken.append(computer) coordinates=dictionary[computer] draw_pattern(computer_symbol,compute...
The code implements a Tic-Tac-Toe AI strategy where the computer plays first, responding to user moves by prioritizing winning moves, blocking user threats, and selecting optimal positions (center, corners, edges) based on the user's choices. It dynamically adapts its strategy through conditional checks and random sele...
def computer_first(user_symbol,computer_symbol,user_moves,computer_moves,dictionary,places_taken): while True: #computer goes first computer=computer_first_turn() computer_turn(computer,computer_moves,places_taken,dictionary,...
def user_turn(user_moves,places_taken,dictionary,user_symbol): user=user_input(places_taken,dictionary) user_moves.append(user) places_taken.append(user) draw_pattern(user_symbol,user,dictionary) return user def check_corner(move): return move in ["1","3","7","9"] def computer_turn(computer,com...
This function determines the computer's response to the user's first move in a Tic-Tac-Toe game. It checks if the user's initial move is a corner, center, or edge, then applies specific strategies: placing in the center if the user took a corner, randomizing a corner if the user took the center, or placing in the cente...
def user_first(user_symbol,computer_symbol,user_moves, computer_moves, dictionary,places_taken): user = user_turn(user_moves, places_taken, dictionary,user_symbol) if check_corner(user) and len(user_moves) == 1: comp = '5' computer_turn(comp,computer_moves,places_taken,dictionary,compu...
def _process_page(self, page, find_details=True): texts = sorted(self._get_texts(page), key=cmp_to_key(self._cmp_position)) ymin, ymax = self._get_table_boundaries(texts) if ymin == 0: return None, [] content = self._find_content(texts, ymin, ymax) cols = self._find_...
The main task of the code is to parse a PDF file by processing each page to extract details and transactions, merging them across pages, and returning structured data containing aggregated details and transactions.
def parse(self, f): details = None transactions = [] pages = PDFPage.get_pages(f, caching=False) for i, page in enumerate(pages): d, t = self._process_page(page, find_details=i==0) details = self._merge_details(details, d) transactions = self._merge_t...
def preprocess_image(self, img): # print("Preprocess image") original_img = img.copy() # Cut image in the ROI img_roi = original_img[self.configs_.px_min:self.configs_.px_max-1, self.configs_.py_min:self.configs_.py_max-1,:] # Apply hsv mask to e...
The main task of the code is to detect a board in an image by preprocessing it, identifying the board's contour and corners, computing its pose (position and orientation), visualizing the detected board with markers, and outputting the computed board pose for further processing or analysis.
def detect_board(self, original_img): img = original_img.copy() preprocessed_img = self.preprocess_image(img) self.show_image(2, 'Preprocessed image', preprocessed_img) (board_min_area_rect, board_corners) = self.get_board(preprocessed_img) cv2.drawContours(img, [board_corners],...
def set_monitors_source(computer: Computer): """ Set the input source of all monitors for the given computer. """ for monitor in get_monitors(): with monitor: name = monitor.get_vcp_capabilities()["model"] monitor.set_input_source(CONF_SCREENS[name][computer]) def resourc...
The code sets up hotkeys to switch monitor sources between two computers and creates a system tray icon with a menu for monitor/computer selection and exit. It initializes monitors, registers keyboard shortcuts, loads an icon, and runs a context menu for managing monitor sources and quitting the application.
def main(): monitors = [Monitor(monitor) for monitor in get_monitors()] keyboard.add_hotkey( HOTKEY_SET_SOURCES_COMPUTER_ONE, lambda: set_monitors_source(Computer.One) ) keyboard.add_hotkey( HOTKEY_SET_SOURCES_COMPUTER_TWO, lambda: set_monitors_source(Computer.Two) ) image = Ima...
def copy(self): new_grid = Grid(self.x_len, self.y_len, self.z_len, self.default_value) for z, slc in enumerate(self.grid): for y, row in enumerate(slc): for x, cell in enumerate(row): logical_x = x - self.x_len//2 logical_y = y - self...
The main task of the code is to compute the next state of a 3D grid in a cellular automaton simulation (e.g., 3D Conway's Game of Life). It creates a copy of the current grid, iterates through all cells, counts active neighbors, and updates the new grid based on rules: active cells with 2-3 neighbors survive, inactive ...
def cycle(self): new_grid = self.copy() for z in range(-(self.z_len//2) - 1, -(self.z_len//2) + self.z_len + 1): for y in range(-(self.y_len//2) - 1, -(self.y_len//2) + self.y_len + 1): for x in range(-(self.x_len//2) - 1, -(self.x_len//2) + self.x_len + 1): ...
def int2str4(k): return chr((k>>24) & 0xff) + chr((k>>16) & 0xff) + chr((k>>8) & 0xff) + chr((k>>0) & 0xff) def _send(self, raw): # print(len(raw)) # print(raw.encode('ascii')) # raw = bytearray(raw, encoding='latin1') raw = raw.encode('latin1') # print(raw) self.soc...
This function opens a socket connection to a host/port, establishes FINS communication by sending an address request command, processes the response to extract client/server node addresses, and executes a test command (MRC=0x05) to retrieve PLC type data, returning the first 20 bytes of the result. It handles errors du...
def openn(self): if self.open : #close if already open self.sock.close() self.open = False #open socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout( 5.0) self.sock.connect((self.host, self.port)) ...
def loginCheck(username, password): for user in userRecords(): if user[0] == username and user[1] == password: return 'loginsuccess;' + user[0] + ';' + user[2] return 'loginfailure' def orderReceived(orderList): discountCode = orderList[0] baristaName = orderList[1] orderPrice =...
This code handles client requests via a socket connection by processing commands like login, order, and reports. It verifies login credentials, confirms orders, generates reports (e.g., popular items, barista performance), and sends responses. If login fails, it retries until successful. The loop terminates on 'close' ...
def run(self): while True: receive = self.clientsocket.recv(1024).decode() temp = re.split(";", receive) if (temp[0] == 'login'): response = loginCheck(temp[1], temp[2]) self.clientsocket.send(response.encode()) while re.split(...
def build_domtree(self): tree_dict = nx.algorithms.dominance.immediate_dominators(self.G, self.superseed_index) self.domtree = nx.DiGraph() self.domtree.add_node(self.superseed_index) self.domtree.add_edges_from([(edge[1],edge[0]) for edge in tree_dict.items() if edge[0] != edge[1]]) ...
The main task of the code is to iteratively or rapidly select the top k "best" nodes from a DOM tree structure, depending on the "fast" parameter. It measures execution time, excludes time spent on statistical logging, and stores the selected nodes in `blocked` for later use. The algorithm builds the DOM tree, evaluate...
def run(self): t1 = time.time() blocked = [] extra_time = 0 if not self.params.get("fast", False): for iteration in range(self.params["k"]): self.build_domtree() if iteration == 0: extra_time += self.save_tree_stats_return_...
def load_csv(csv_path): bydates = defaultdict(list) bynames = defaultdict(list) bymonths = defaultdict(lambda: defaultdict(list)) bymonthnames_groupedby_applicants = defaultdict(lambda: defaultdict(list)) csv_f = csv.reader(open(csv_path)) next(csv_f) for row in csv_f: daterange, app...
The main task of the code is to generate GitHub Wiki reports by processing annual leave data. It loads historical and current-year data, organizes upcoming leaves by month, and renders templates into `Home.md` and `_Sidebar.md` files with structured content like today's leaves, monthly leave forecasts, and historical y...
def gen_ghwiki_reports(): for year, path in leaves_csv_paths.items(): yr_data = load_csv(leaves_csv_path_pat.format(YYYY=year)) gen_for_year(year, yr_data) if year == today.year: c_yr_data = yr_data # current year data today_leaves = c_yr_data['bydates'][datetime.date.today...
def displayBoard(): print(board[1] + "|" + board[2] + "|" + board[3]) print("-----") print(board[4] + "|" + board[5] + "|" + board[6]) print("-----") print(board[7] + "|" + board[8] + "|" + board[9]) print() def isThereWinner(board, le): return (board[1] == le and board[2] == le and board[3]...
This code implements a Tic-Tac-Toe game where a human player (X) and a computer (O) take turns. It checks for a winner after each move, handles invalid inputs by prompting again, and declares a tie if the board fills without a winner. The game loop alternates between human and computer moves, updating the board display...
def main(): displayBoard() while True: if isThereWinner(board, "X"): print("X won") break else: temp = int(input("player X enter pos ")) if isSpaceFree(temp): userInput(temp) displayBoard() if isThere...
def get_features(inp, oup): cbe = ce.cat_boost.CatBoostEncoder() cbe.fit(inp, oup) inp = cbe.transform(inp) inp = inp.to_numpy() inp = np.round(inp.astype(float), decimals=4) # CatBoostEncoder encodes NaNs for string inputs. # For numeric inputs it leaves them untouched (weight, height). ...
The code reads a dataset, encodes categorical labels ('Murmur', 'Outcome') using LabelEncoder, generates feature sets considering label contexts, splits data into training/test sets for two classifiers (Murmur and Outcome), and returns these splits for model training/evaluation.
def get_data(): df = pd.read_csv('training_data.csv') features = df.iloc[:, :-3] murmurs = df.loc[:, 'Murmur'] outcomes = df.loc[:, 'Outcome'] # Encode murmurs murmurs = murmurs.to_numpy() le = preprocessing.LabelEncoder() le.fit(murmurs) murmurs = le.transform(murmurs) # Enco...
def get_function_list(pe_object, pe_file): functions = get_cfg_table_function(pe_object, pe_file) for addr in get_exception_table_functions(pe_object): if addr not in functions: functions.append(addr) for entry in get_exports(pe_object): addr = pe_object.OPTIONAL_HEADER.ImageBas...
This code analyzes a Windows DLL file to extract and map all function calls. It uses the pefile library to parse the PE file structure, retrieves function addresses and names, and collects function call relationships. The result is a dictionary mapping function names (or default hex-based names) to lists of calls, aidi...
def get_all_function_calls(dll_path): calls = {} file_path = dll_path pe = pefile.PE(file_path) pe_file = open(file_path, "rb") pe.parse_data_directories() function_addr_list = get_function_list(pe, pe_file) indexable_function_table = get_function_names(pe) if not function_addr_l...
def jac(self,y,h=1e-7,method='forward'): """ Evaluate the objective jacobian. Use this function if n_partitions=1 or if distinct worker groups are evaluating jacobians at distinct points. y: input variables describing surface y: array of size (self.dim_x,) h: step size h: float ...
This function computes the Jacobian of the objective function using finite differences (forward or central) by distributing computations across worker groups. It handles multi-partition scenarios, perturbing input variables `y` with step size `h`, evaluating the function at perturbed points, and combining results. For ...
def jacp(self,y,h=1e-7,method='forward'): """ Evaluate the objective jacobian by distributing the finite difference over the worker groups. Use this function if n_partitions > 1 AND if all worker groups are evaluating the jacobian together at the same point, such as in a single optimizati...
def jac_residuals(self,y,h=1e-7,method='forward'): """ Evaluate the residulas jacobian. Use this function if n_partitions=1 or if distinct worker groups are evaluating jacobians at distinct points. y: input variables describing surface y: array of size (self.dim_x,) h: step size h:...
The function `jacp_residuals` computes the Jacobian of residuals using finite differences, distributing calculations across worker groups for parallel processing. It supports 'forward' or 'central' difference methods, perturbing input variables to evaluate residuals at neighboring points. When multiple partitions exist...
def jacp_residuals(self,y,h=1e-7,method='forward'): """ Evaluate the residuals jacobian by distributing the finite difference over the worker groups. Use this function if n_partitions > 1 AND if all worker groups are evaluating the jacobian together at the same point, such as in a single ...
def creatematrix(): column, lijst, termweights = termweightmatrix() df = pd.DataFrame(data = termweights, index = lijst, columns = column) return df def calcinnerproduct(matrix): innerproducts = [] queryvector = createqueryvector(matrix) for column in matrix: innerproduct = np.dot(queryv...
The code calculates cosine similarity between a query and items in a matrix. It computes inner products and norms, divides them to get similarity scores, sorts results in descending order, and returns a preview of the top matches.
def similarity(zoekopdracht): df = creatematrix() global query query = zoekopdracht innerproducts = calcinnerproduct(df) underproductlijst = calcunderproduct(df) similarity = [i / j for i, j in zip(innerproducts, underproductlijst)] similarity = zip(list(df.columns),similarity) similarit...
def aggregate_mixed_taxonomy(dataframe, taxa_dict, main_dir='./', summarize_other=True, check_totals_sum_to_1=True): """ Summarise abundances based on cherry-picked taxonomic abundances, perhaps mixed at different levels. Loop over the different taxonomic levels specified i...
This function generates bar plots visualizing taxonomic abundances from a dataframe, aggregating data using a taxa dictionary. It renames 'other' categories, creates faceted bar charts with specified order/colors, adds a reference line, and saves the figure. Key tasks: data aggregation, plot customization, visualizatio...
def plot_bars_for_taxa_dict(dataframe, taxa_dict, order_list, colors, filename, main_dir, portrait=True, summarize_other=True, check_totals_sum_to_1=True): plot_data = aggregate_mixed_taxonomy( dataframe=dataframe, taxa_dict=taxa_dict, ...
def run_pca(main_dir='./', top_percent=20, genus_only=True): # get data # has a variance column tacked on. df = sort_by_variance(main_dir=main_dir, genus_only=genus_only) # drop rows that don't have sum of abundances in the top %. pca_input = most_variant_genera_for_pca(data=df, top_percent=top_per...
The code generates PCA plots visualizing transformed microbial data, with options to facet by experimental conditions, standardize axes, and apply custom color schemes. It processes input data, computes principal components, maps samples to metadata, and creates scatter plots using Seaborn. Results are saved as PDFs wi...
def plot_pca_results(top_percent=20, genus_only=False, facet_row=True, uniform_axes=True, main_dir='./', plot_dir='./plots/', savefig=True): # get data that's ready for PCA: pca_input, data_transformed, variances = \ run_pca(main_dir=main_di...
def ordkrig_estimator(self,p21, z): pa10 = (self.z_dep_func(p21[11], p21[12], z[:])*1e4)/(self.t0_max[:]-self.t0_min[:]) pb10 = self.z_dep_func(p21[13], p21[14], z[:])/(self.slope_max[:]-self.slope_min[:]) p37 = np.concatenate((p21[3:11], pa10[6:], pb10[6:])) astrokrig_result = np.zeros(...
The main task of the code is to compute a 3D ordinary kriging estimator by interpolating input matrices, adjusting them with a kriging model, and combining the results with a weighted summation using a lambda function. It processes 3D grid data, applies normalization, clips values to ensure non-negativity, and returns ...
def ordkrig_estimator_3D(self,p21, z): ABG_matrix_new = np.zeros(( self.zeta_full_length, self.kappa_full_length, self.grid_size+self.num_sim_thermal), 'float64') NEW_ABG_matrix = np.zeros(( self.grid_size+self.num_sim_thermal, self.zeta_full_length, self.kappa_full_length), 'float64') full_matr...
def write_error_to_binfile(self,data,errorname): with open(self.bin_file_path, "a") as bin_file: bin_file.write("#"+errorname+"\t") for elem in data.get_mcmc_parameters(["varying"]): bin_file.write(" %.6e\t" % data.mcmc_parameters[elem]["current"]) for elem in data.get_mcmc_param...
The function `loglkl` computes the log-likelihood of a cosmological model by comparing its theoretical predictions (via CLASS) to observational data. It initializes parameters, calculates the linear matter power spectrum, adjusts for non-LCDM models, computes a transfer function $ T(k) $, applies smoothing, interpolate...
def loglkl(self, cosmo, data): k = self.k # Initialise the bin file if not os.path.exists(self.bin_file_path): with open(self.bin_file_path, "w") as bin_file: bin_file.write("#") for name in data.get_mcmc_parameters(["varying"]): name = re.sub("[...
def read_file(input_file: str) -> str: with open(input_file) as f: buffer = f.readlines() return buffer def part_1(lines: list) -> int: TOP_SIZE = 100000 file_system = parse_file_system(lines) result = sum([x.get_size() if x.type == NT.DIR and x.get_size() < TOP_SIZE else ...
The main task of the code is to process a file's content by executing two parts of logic. It reads the file into lines, runs `part_1` and `part_2` with these lines, prints their results, and returns 0. The function orchestrates data processing and output for two distinct tasks, likely part of a problem-solving or analy...
def main() -> int: lines = read_file(file_path) # Part One print(f"Part One: {part_1(lines)}") # Part Two print(f"Part Two: {part_2(lines)}") return 0
def read_file(input_file: str) -> str: with open(input_file) as f: lines = f.readlines() return lines def part_1(lines: list) -> int: points = [] for line in lines: ABC, XYZ = line.split() points.append(get_points(ABC, XYZ)) return points def part_2(lines: list) -> int: p...
The main task of the code is to read a file's contents, process them in two distinct parts (Part One and Part Two), sum the results of each part's computation, and print these sums. The `main()` function returns 0 after executing these steps.
def main() -> int: lines = read_file(file_path) # Part One print(f"Part One: {sum(part_1(lines))}") # Part Two print(f"Part Two: {sum(part_2(lines))}") return 0
def reset(self): self.set_all_leds(BLACK) self.show() def set_led(self, string, fret, color): self.color_arr[string-1][NUM_FRETS - fret] = (color[1] << 16) + (color[0]<<8) + color[2] def get_led_color(self, note): if note in self.structure.notes: return self.structure.colors[...
This function updates the LED colors on a musical instrument's board by calculating the note for each string and fret, then setting the corresponding LED color based on the note's position in the chromatic scale. It resets the board, iterates through all strings and frets to determine the note value, assigns colors usi...
def update_board_colors(self): self.reset() for string in range(NUM_STRINGS): stringRoot = self.tuning.notes[string] for fret in range(NUM_LEDS): fretNote = (stringRoot + fret - self.rootNote)%12 self.set_led(string+1, fret, self.get_led_color(fret...
def heu(self,state) -> int: score = 0 score += self.west_check(state) score += self.nw_check(state) score += self.north_check(state) score += self.ne_check(state) return score def get_moves(self,playable): moves = [] # explores middle row first as it's mor...
This function implements the minimax algorithm with alpha-beta pruning to evaluate game states, recursively exploring possible moves up to depth k. It tracks the best move (index) and heuristic value for max/min nodes, pruning branches when values exceed alpha/beta thresholds. The parent_map records each node's value, ...
def prune_minmax(self,state : str,k : int,max : bool,playable,alpha = None,beta = None): # if max depth reached if k == 0: heu = self.heu(state) parent_key = str(len(self.parent_map.keys())) self.parent_map[parent_key] = (str(heu),[],max) return None , h...
def heu(self,state) -> int: score = 0 score += self.west_check(state) score += self.nw_check(state) score += self.north_check(state) score += self.ne_check(state) return score def get_moves(self,playable): moves = [] # explores middle row first as it's mor...
This function implements the Minimax algorithm with depth limitation to determine the optimal move for a game state. It recursively evaluates possible moves, tracks heuristic values, and stores move indices and evaluation results in a parent map. The function alternates between maximizing and minimizing strategies base...
def minmax(self,state : str,k : int,max : bool,playable): # if max depth reached if k == 0: heu = self.heu(state) parent_key = str(len(self.parent_map.keys())) self.parent_map[parent_key] = (str(heu),[],max) return None , heu , parent_key ...
def get_determinant(self): if self.height == 1: return self.numbers[0][0] if self.height == 2: result = self.numbers[0][0] * self.numbers[1][1] - self.numbers[1][0] * self.numbers[0][1] #print(f"Determinant of {self} is {result}") return result res...
This code computes the inverse of a square matrix using the adjugate method. It checks if the matrix is invertible (non-zero determinant and square dimensions), calculates cofactors for matrices larger than 2x2, transposes and adjusts signs, then divides by the determinant. For 2x2 matrices, it swaps diagonal elements ...
def invert(self): #print(self, "before inversion") determinant = self.get_determinant() if determinant == 0 or self.height != self.width: return None if self.height != 1: result = Matrix([[0 for i in range(self.width)] for j in range(self.height)]) if ...
def set_data(self, x, t): self.x0 = x x = tf.convert_to_tensor(x, dtype=tf.float64) t = tf.convert_to_tensor(t, dtype=tf.float64) x, t = tf.meshgrid(x, t) x, t = tf.reshape(x, [-1, 1]), tf.reshape(t, [-1, 1]) self.x, self.t = x, t def grad(self)...
The code trains a neural network over specified epochs using gradient descent to approximate eigenvalues and eigenvectors of a system. It initializes storage arrays, applies the Adam optimizer to update model parameters, computes eigenvalues/vectors at each epoch using `compute_eig`, and returns time-evolving eigenvalu...
def predict(self, epochs,x,t,lr): """ Fit the neural network arguments: epochs(int): the number of epochs x(numpy array): the x values t(numpy array): the t values lr(float): the learning rate returns: eigenvals(n...
def get_total_time_for_all_games(self): """Record total time to self.info""" for application in self.applications: app_name = application[NAME] total_time = self.get_total_time_for_a_single_game(app_name) self.info[app_name][TOTAL] = total_time def get_last_start_and...
The code's main task is to display application statistics by retrieving the total time spent on all games, fetching the last start and finish times for each game, and printing a formatted table with this information.
def show_application_stats(self): self.get_total_time_for_all_games() self.get_last_start_and_finish_time_for_each_game() self.print_table_with_current_info()
def F_core(self) -> np.ndarray: Phi_ = self.Phi() return np.power(Phi_, 2) def F_corona(self) -> np.ndarray: N_agg = self.N_agg F_RPA_ = self.F_RPA() F_RPA_0 = F_RPA_[0] S_corona_corona_ = self.S_corona_corona() return ...
The function computes a weighted sum of core and corona contributions to a micelle's free energy, combining `F_core_`, `F_corona_`, and `S_core_corona_` terms scaled by `r_beta`, then normalizes the result by `(1 + r_beta)**2` to return a normalized free energy value as a NumPy array.
def F_micelle(self) -> np.ndarray: r_beta = self.r_beta F_core_ = self.F_core() F_corona_ = self.F_corona() S_core_corona_ = self.S_core_corona() return (F_core_ + (r_beta**2)*F_corona_ + (2*r_beta)*S_core_corona_)/((1 + r_beta)**2)
def get_context_layers(conf, mode): if mode == "list": lookup_fn = "context_feature_collection" else: lookup_fn = "context_feature" layers = [] for field in conf.get("geometry_fields") or []: layer_conf = { "name": get_geometry_label(conf, field, mode), "...
The function updates a configuration dictionary's map settings by initializing default map configurations, converting single map dicts to lists, and dynamically adding layers based on mode and auto-layer flags, ensuring proper layer composition for 'list', 'detail', and 'edit' modes while removing redundant auto-layer ...
def update_map_config(conf, pages): if not conf.get("map"): return if conf.get("map") is True: if conf.get("list"): conf["map"] = [ { "mode": "list", "auto_layers": True, }, {"mode": "detail", "a...
def compute_rubber_ball(ball): H = (2 * R - ball.d) + (pow(ball.r, 2) / (10 * pow(ball.d, 2))) * (R - ball.d) print(f"Height ratio for rubber ball (Should be close to 2.7): {H/R}") return H def compute_drop_height_bisection(ball, a, b): i = 0 while True: i += 1 c = (a + b) / 2 ...
The main task of the code is to compute analytical and numerical drop heights for rubber, stainless steel, and plastic balls using bisection methods, adjust values for 20% energy losses, and simulate/plot results. It calculates drop heights in inches, compares analytical vs numerical solutions, and applies confidence-b...
def main(): """ # Find min H for rubber ball H_rubber = compute_rubber_ball(rubber) print(f"Min H for rubber ball (analytical): {H_rubber/0.0254} inches") # Use rubber ball drop height as initial guess h_guess = H_rubber """ # Compute analytical drop height for rubber ball H_rubber...
def get_base_columns(self): # Get feature list from parsed data header, set all columns to 0 base_columns = pd.read_pickle( f"{tsh_config.data_dir}/parsed/act_states.pkl" ).columns base_columns = sorted( list(set(base_columns) - set(["entity_id", "state", "duplica...
The code initializes a state tracking system by setting up a DataFrame for current states, loading machine learning models, configuring a database, and registering event handlers to monitor state changes in TheSillyHome application. It also logs initialization completion.
def initialize(self): # Define columns for current_state_base DataFrame feature_list = self.get_base_columns() current_state_base = pd.DataFrame(columns=feature_list) # Set initial values in current_state_base DataFrame current_state_base.loc[0] = 0 self.handle = self.lis...
def get_last_child(self, parent_node): children = self.get_children(parent_node) try: return children.order_by('path').reverse()[0] except IndexError: return None def _inc_path(self, obj): """ returns: The path of the next sibling of a given node path. ...
This code adds a child node to a parent node in a tree structure. It sets the child's depth, generates its path based on the parent's path and existing children, saves the child, and increments the parent's child count both in the database and in memory.
def process(self, parent_node, child_node): last_child = self.get_last_child(parent_node) child_node.depth = parent_node.depth + 1 if last_child: # adding the new child as the last one child_node.path = self._inc_path(last_child) else: # the node had...
def tap_password_validation(self, password): msg = '' if len(password)==0: msg = 'INVALID! Password can\'t be empty' else: try: # If the password is smaller than the min length then report if len(password)<self.min_tap_len: ...
This code processes password input in a Tkinter GUI, validating entries against set rules, tracking consecutive correct attempts, and managing user confirmation. It handles initial password setup, validation checks, and displays feedback messages, destroying the window upon successful confirmation or after 6 failed att...
def processing_password(self, event): password = self.password_field.get() self.password_field.delete(0, END) if(self.set_password is None): if (self.tap_password_validation(password) and (self.confirm_password_message())): msg = 'Success!\nNOW enter the correct passw...
def placeCops(self, denX, denY): copNum = int((self.feildSize[0] * self.feildSize[1]) * self.copsRate) while self.copsInBush < copNum: x = randrange(0, self.feildSize[0]-1) y = randrange(0, self.feildSize[1]-1) tree = self.treeMap[x][y] if tree.treeStatus ...
This function handles revealing a grid cell in a game, updating its icon based on adjacent 'cops' and game state. It places cops, updates icons (sweet/cop/none), uncovers blank areas, restores icons, and checks for win conditions, triggering full forest reveal if won.
def get_zakladka(self, x, y, showMessage = False): self.isNewGame = False tree = self.treeMap[x][y] if tree.iconNumber == iconEnum['alert']: return if self.StepCounter == 0: self.StepCounter += 1 self.placeCops(x,y) if tree.copsNear == 0: ...
def countDefaultP(self): t = 0 i = 0 while (i < self.feildSize[0]): j = 0 while (j < self.feildSize[1]): tree = self.treeMap[i][j] if tree.iconNumber == iconEnum['tree']: t += 1 j += 1 i += 1 ...
The code calculates probabilities for each tree in a grid, identifies trees with minimum and maximum probabilities, marks low-probability trees as bad guesses, and highlights high-probability trees. It iterates through the grid multiple times to refine probabilities, then returns coordinates of high-probability, low-pr...
def hint(self, imAI = False): #probability calculate mg = magicNumber defaultP = self.countDefaultP() averageAmountOfNumber = self.countAverageAmountNumbersNearTrees() steps = 3 for z in range(steps): i = 0 while (i < self.feildSize[0]): ...
def restore_icon(self, tree): x = tree.x y = tree.y self.master.set_icon_for_cell(x, y, icons[tree.iconNumber]) def itIsNumber(self,tree): if tree.iconNumber >= iconEnum['one'] and tree.iconNumber <= iconEnum['eight']: return True return False def uncover_blank_area(...
This function checks the 3x3 grid around coordinates (x,y) to update icons based on cop and alert presence. It restores icons, evaluates cop visibility, updates tree states (e.g., 'sweet' to 'alert'), and triggers flags if conditions match. It also checks win conditions after processing.
def check_near(self, x, y): self.isNewGame = False tree = self.treeMap[x][y] alertsNear = 0 if self.StepCounter == 0: i = x - 1 while (i <= x + 1): j = y - 1 while (j <= y + 1): if i >= 0 and i < self.feildSize[0...
def get_zakladka(self, x, y, showMessage = False): self.isNewGame = False tree = self.treeMap[x][y] if tree.iconNumber == iconEnum['alert']: return if self.StepCounter == 0: self.StepCounter += 1 self.placeCops(x,y) if tree.copsNear == 0: ...
The main task of the code is to execute an AI agent's step in a game, determining optimal moves by evaluating tree probabilities. It identifies high-probability trees for marking/uncovering, prioritizes low-probability placements, handles alerts, and returns status based on success/failure conditions, aiming to progres...
def doStep(self, showMessage=False): #self.master.update_idletasks() #self.master.update() self.stepStat = AIStatEnum['inProgress'] if self.StepCounter == 0: self.get_zakladka(randrange(0, self.feildSize[0]), randrange(0, self.feildSize[1])) ...
def read_isolet(filename): x, y = [], [] with open(filename, 'r') as f: lines = f.readlines() for line in lines: data = line.strip('.\n').split(',') new_y = int(data[-1]) new_x = data[:-1] y.append(new_y) x.append(new_x) x, y = np.array(x), np.array(y) return x, y def normalize_data(data, scaler...
The main task of the code is to load and preprocess ISOLET dataset (training and test splits), normalize features, and generate scatter plots and PCA plots for visualizing the first 100 samples of both datasets. It demonstrates data exploration techniques including standardization and dimensionality reduction via PCA f...
def main(): # read training data X_train, y_train = read_isolet('isolet1+2+3+4.data') print(X_train.shape, y_train.shape) # normalize training data X_train, scaler = normalize_data(X_train) # read test data X_test, y_test = read_isolet('isolet5.data') print(X_test.shape, y_test.shape) X_test = scaler.transfo...
def get_pmatrix(X, perplexity): """ Calculates the final probability matrix using the pairwise affinities/conditional probabilities. :param M: the matrix of data to be converted :param perplexity: the specified perplexity :return: the joint probability matrix p_ij """ # get the pairwise dist...
The code performs t-SNE dimensionality reduction, mapping high-dimensional data (X) to 2D space. It uses perplexity, learning rate, and momentum parameters to optimize low-dimensional embeddings (Y) via gradient descent. Early exaggeration (scaling joint probabilities) aids initial optimization, while momentum adapts d...
def TSNE(X, perplexity=40, num_iter=1000, learning_rate=100, momentum_initial=0.5, momentum_final=0.8): """ Performs t-SNE on a given matrix X. :param X: matrix of high dimensional data :param perplexity: cost function parameter :param num_iter: number of iterations :param learning_rate: learnin...
def get_pmatrix(X, perplexity): """ Calculates the final probability matrix using the pairwise affinities/conditional probabilities. :param M: the matrix of data to be converted :param perplexity: the specified perplexity :return: the joint probability matrix p_ij """ # get the pairwise dist...
The code performs t-SNE dimensionality reduction on high-dimensional data matrix X, returning a 2D embedding. It initializes probabilities, applies early exaggeration, iteratively computes gradients, updates positions with momentum, and adjusts momentum over iterations to optimize the low-dimensional representation.
def TSNE(X, perplexity=40, num_iter=1000, learning_rate=100, momentum_initial=0.5, momentum_final=0.8): """ Performs t-SNE on a given matrix X. :param X: matrix of high dimensional data :param perplexity: cost function parameter :param num_iter: number of iterations :param learning_rate: learnin...
def _handle_riot_screen(): logging.info('[riot] Checking riot screen') while (location := _get_button_location(riot_images, confidence=0.85)) is not None: time.sleep(1) logger.info("[riot] clicking it away") center = location.center above_center = Point(center.x, center.y - 300)...
The main task of the code is to locate and click a specified button on the screen within a timeout period, with options to delay the click, wait for the button's disappearance, and handle the Riot screen. It continuously searches for the button, logs debug information, and raises an error if the button isn't found with...
def click_on_button(button, wait_before_click: float = 0, wait_for_disappearance: bool = True, waiting_time=None, check_riot_screen: bool = True): found_button = None wait_until = datetime.now() + timedelta(seconds=5*60 if waiting_time is None else waiting_time) while datetime.now() < wait_until: if...
def get_viable_seqnames(self): return self._viable_seqs def get_frame_ids(self, seqname): """ Returns ids of all images that have idx higher than or equal to the first annotated frame""" all_frame_ids = sorted([self._frame_name_to_idx(fname) for fname in self.get_image_frame_names(seqname)]) ...
The code processes video sequences by loading frames and their segmentations, applies random horizontal flips and transformations, filters valid frames, handles segmentation label adjustments, and returns a dictionary containing stacked images, initial segmentation masks, and processed labels for training a video segme...
def __getitem__(self, idx): """ returns: dict (Tensors): contains 'images', 'given_segmentations', 'labels' """ seqname = self.get_viable_seqnames()[idx] # We require to begin with a nonempty frame, and will consider all objects in that frame to be tracked. #...
def update_result(scan_num, partition_num, repo_location, status, results, settings): try: connection = sqlite3.connect(settings['database']) cursor = connection.cursor() cursor.execute("UPDATE SCAN_RESULTS set status = ?, results = ? WHERE scan_num = ? and scan_thread_num = ? and r...
This function processes a specific scan partition by retrieving repository locations from a database, scanning each location using the scan_url function, and updating scan results with statuses ("Scanning" -> "Finished") and outcomes. It handles database connections, error logging, and thread status updates for distrib...
def scan_partition(scan_num, partition_num, userid, password, rescan, entropy, settings): print ("processing scan_num: " + str(scan_num) + ", partition_num: " + str(partition_num)) try: connection = sqlite3.connect(settings['database']) cursor = connection.cursor() cursor.ex...
def read_params(request): querydict = request.GET if not "domain" in querydict: raise MissingOrBrokenFields("Missing domain for update") if not "key" in querydict: raise MissingOrBrokenFields("Missing key for update") name, zone = querydict["domain"].split(".", 1) if not zone.endswith("."): zone += "." k...
The main task of the code is to handle HTTP requests for updating DNS records (A and AAAA types) based on parameters extracted from the request. It validates input fields, updates the specified DNS records, and returns a success response with the updated values or "unchanged" if no changes were made. If validation or b...
def index(request): try: name, zone, key, a, aaaa = read_params(request) recordName = validate_name_zone_key(name, zone, key) trySetRecord(recordName, "A", a) trySetRecord(recordName, "AAAA", aaaa) return HttpResponse("Updated %s a=%s, aaaa=%s\n" % ( recordName, a or "unchanged", aaaa or "unc...
def http_command(httpbase, cmd): if config.has_option("healthttp", httpbase): return "%s %s" % (config.get("healthttp", httpbase), cmd) else: return cmd def image_fail(self): call(self.dockertag + [self.tag, "%s:%s" % (self.tag_to_rep(), self.ftag)]) if self.exist...
This function tests a Docker image by running a specified command inside a container, waits for the service to start, checks the command's exit code, and handles success/failure. It creates a container, executes the command, logs errors if the command fails, stops/removes the container, and pushes the image to the regi...
def test_image(self, cmd, waittime=config.getint("variable", "test_waittime"), noservice=False, toreg=True, httpbase=None): """Testet das generierte Image\n\ Parameter:\n\ waittime: Wartezeit bis der Test ausgefuert werden soll in Sekunden um denn Dienst Zeit zu geben zu starten (Default: 20...
def _kFoldSplitIndices(self, dataset, k): ''' k-fold cross validation: split the indices of the dataset into k groups ''' num_data = dataset.shape[0] fold_size = int(num_data / k) indices = np.arange(num_data) np.random.shuffle(indices) indices_split = np....
This function performs k-fold cross-validation for each lambda in lambda_list. It splits data into k folds, trains on k-1 folds, tests on the remaining fold, computes errors (1 - accuracy) for both training and test sets, averages these errors across all folds, and returns a list of average errors for each lambda.
def runKFold(self, lambda_list, X, Y, k = 3): ''' Run k-fold cross validation on X and Y with respect to each lambda ''' k_fold_errors = [] for lmbda in lambda_list: self.lmbda = lmbda # Split indices into k groups randomly indices_split = self...
def time_elapsed(start_time): return time.time() - start_time def smart_heuristic(state, agent_id): pawnLocationList = [] rivalPawnLocationList = [] if agent_id == 0: for key, value in state.player1_pawns.items(): if not np.array_equal(value[0], not_on_board) and not is_hidden(state,...
This function implements the minimax algorithm with alpha-beta pruning for a game state. It recursively evaluates possible moves, alternating between maximizing (agent's turn) and minimizing (opponent's turn) the heuristic value. Depth limits, time constraints, and pruning thresholds (alpha/beta) optimize decision-maki...
def rb_minimax_recursion(current_state, turn_id, current_depth, alpha, beta): if time_elapsed(start_time) > time_limit - cushion: return -np.inf if current_depth == 0: return smart_heuristic(current_state, agent_id) if gge.is_final_state(current_state): retu...
def time_elapsed(start_time): return time.time() - start_time def smart_heuristic(state, agent_id): pawnLocationList = [] rivalPawnLocationList = [] if agent_id == 0: for key, value in state.player1_pawns.items(): if not np.array_equal(value[0], not_on_board) and not is_hidden(state,...
The function implements an Expectimax algorithm for game state evaluation, recursively calculating optimal values by alternating between max (agent's turn) and expected (opponent's turn) nodes. It checks time limits, returns heuristic values for terminal states or depth zero, explores neighbors, and computes maximum va...
def rb_expectimax_recursion(current_state, turn_id, current_depth): if time_elapsed(start_time) > time_limit - cushion: return -np.inf if current_depth == 0: return smart_heuristic(current_state, agent_id) if gge.is_final_state(current_state): return smart_h...
def read_lines(file_name): file = open(file_name, 'r') # opens the file with the note to read only lines = file.readlines() # reads the lines and stores the lines into a list outside_spaces = remove_spaces(lines) # function call to remove all spaces and reformat the list return outside_spaces def is_...
The main task of the code is to read a Julia file, process each line to identify if it is a keyword or token, and print the results in a formatted table. It uses helper functions to check the type of each line and retrieve corresponding token values, displaying either the keyword/token or an error message for unrecogni...
def main(): # sets the file past for the file filepath = "C:\Dev\Programming_Language_project\\4308-Project-Fall-2021\Julia-Files\\" filename = 'Test1.jl' # optional input for user to do a file name selection # filename = input("Enter the name of the file: ") # sets file data list to the output...
def mse(self,X,y): y_pred=self.predict(X) return((y-y_pred)**2).sum()/len(y) def rmse(self,X,y): return np.sqrt(self.mse(X,y)) def r2(self,X,y): y_pred=self.predict(X) return 1-((((y - y_pred)**2).sum())/((y-y.mean())**2).sum())
The code performs linear regression by calculating coefficients using the normal equation. It centers input features and target, computes weights via matrix inversion, derives bias from means, and evaluates performance with MSE, RMSE, and R².
def fit(self,X,y): """ Uses Linear Regression to fit X and y Arguments: X: DataFrame y: Array """ X=pd.DataFrame(X) self.X=X self.y=y self.W=np.zeros(X.shape[1]) self.w=X.shape[1] X_norm = X - X.mean() y_nor...
def output_exit(status: str, message): output(status, message) mt5.shutdown() quit() def output(status: str, message): result = { "status": status, "message": message } print(json.dumps(result)) sys.stdout.flush() def order_now(type, symbol, max_price, tp, sl, comment): r...
The function `send_orders` places multiple market or limit trades for a given symbol based on price conditions. It checks symbol validity, calculates stop-loss/take-profit levels, and places orders at current prices or specified max_price. It iteratively adds limit orders, adjusting prices incrementally, and stops when...
def send_orders(type, symbol, max_price, tp, sl, comment): isBuy = True if type == 'buy' else False success = 0 symbol_info = mt5.symbol_info(symbol) if symbol_info is None: output_exit( "fail", symbol+" not found, can not call order_check()" ) # if the symbol is unavailable in MarketWatch,...
def output(status: str, message): result = { "status": status, "message": message } print(json.dumps(result)) sys.stdout.flush() def show_info(): account = mt5.account_info()._asdict() output_exit("success", f"Info for account {account['name']}\n\nBalance: {account['balance']}\nC...
This function routes trading commands to specific operations: outputs info, sends orders, shows active positions, closes, or edits positions based on the 'call' parameter. Unknown commands trigger MT5 shutdown and exit.
def resolve_call(call, *args): if call=="info": output('info', show_info()) elif call=="order": return send_orders(args[0], args[1], args[2], args[3], args[4], args[5]) elif call=="show_active_positions": return show_active_positions() elif call=="close_position": return ...
def refresh(self): """Refresh the opened widgets.""" if self.QView and self.QView.isVisible(): # Refresh the BooN View if opened. self.QView.initialize_view() if self.QStableStates and self.QStableStates.isVisible(): # Refresh the stable states View if opened. self.QSta...
The main task of the code is to open a file dialog for selecting a ".boon" file, load the selected file into the application, and refresh the UI. It uses Qt's file dialog to filter and retrieve the file path, assigns it to `self.filename`, loads the file via `self.boon.load()`, then triggers `refresh()`, `setup_design(...
def open(self): """Open file dialog.""" filename = QFileDialog.getOpenFileName(self, "Open file", "", "Boon Files (*.boon);; All Files (*);;") if filename: self.filename = filename[0] self.boon.load(filename[0]) self.refresh() self.setup_design() ...
def refresh(self): """Refresh the opened widgets.""" if self.QView and self.QView.isVisible(): # Refresh the BooN View if opened. self.QView.initialize_view() if self.QStableStates and self.QStableStates.isVisible(): # Refresh the stable states View if opened. self.QSta...
The code's main task is to implement a file import dialog that allows users to select text, SBML, or XML files. It determines the file extension, loads the content into a 'boon' object using appropriate methods, and refreshes the GUI. If an unsupported extension is selected, it displays an error message. This function ...
def importation(self): """Import file dialog.""" filename = QFileDialog.getOpenFileName(self, "Import from files", "", "Text or SBML Files (*.txt *.xml *.sbml);; All Files (*);;") if filename: self.filename = None # no file name since the BooN is not saved in the internal format. ...
def build_frequency_dict(text: bytes) -> Dict[int, int]: """ Return a dictionary which maps each of the bytes in <text> to its frequency. >>> d = build_frequency_dict(bytes([65, 66, 67, 66])) >>> d == {65: 1, 66: 2, 67: 1} True >>> d = build_frequency_dict(bytes([])) >>> d {} """ ...
(The code compresses the contents of an input file using Huffman coding and writes the compressed data to an output file. It reads the input file's binary data, builds a frequency dictionary, constructs a Huffman tree, generates binary codes, calculates average bits per symbol, and combines the tree structure, text len...
def compress_file(in_file: str, out_file: str) -> None: """ Compress contents of the file <in_file> and store results in <out_file>. Both <in_file> and <out_file> are string objects representing the names of the input and output files. Precondition: The contents of the file <in_file> are not empty. ...
def get_requested_microversion(): requested_version = microversion_parse.get_version( flask.request.headers, api_version.RESERVATION_SERVICE_TYPE ) if requested_version is None: requested_version = api_version.MIN_API_VERSION elif requested_version == api_version.LATEST: ...
This function validates a requested API microversion against allowed minimum and maximum versions. It creates an APIVersionRequest object if the input is valid, otherwise sets it to None and triggers error handlers for invalid or out-of-range versions. The validated version is stored in the Flask request context for su...
def set_api_version_request(): requested_version = get_requested_microversion() try: api_version_request = api_version.APIVersionRequest(requested_version) except ex.InvalidAPIVersionString: flask.request.api_version_request = None bad_request_microversion(requested_version) if...
def _init_resp_type(file_upload): """Extracts response content type.""" # get content type from Accept header resp_type = flask.request.accept_mimetypes # url /foo.json if flask.request.path.endswith('.json'): resp_type = RT_JSON flask.request.resp_type = resp_type # set file upl...
This function processes HTTP requests by initializing response types, handling method-specific data (POST/PUT/PATCH), extracting query parameters, and executing the target function. It wraps the function call in a context, catches exceptions, and converts them into appropriate HTTP error responses with customized messa...
def handler(**kwargs): LOG.debug("Rest.route.decorator.handler, kwargs=%s", kwargs) _init_resp_type(file_upload) # update status code if status: flask.request.status_code = status if flask.request.method in ['POST', 'P...
def scope(name): global name_scope bk = name_scope name_scope = name_scope + name + '/' yield name_scope = bk def conv(*args, **kargs): kargs['param_attr'] = name_scope + 'weights' if 'bias_attr' in kargs and kargs['bias_attr']: kargs['bias_attr'] = paddle.ParamAttr( name...
This function implements a depthwise separable convolution by sequentially applying a depthwise convolution (with group-wise filtering) followed by a pointwise convolution (1x1 kernel). The depthwise layer uses dilation and batch normalization, while the pointwise layer adjusts the number of output channels. Both steps...
def separate_conv(input, channel, stride, filter, dilation=1, act=None): param_attr = paddle.ParamAttr( name=name_scope + 'weights', regularizer=paddle.regularizer.L2Decay(coeff=0.0), initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0, std=0.06)) with scope('depthwise'): ...
def conv_bn_layer(input, filter_size, num_filters, stride=1, padding=1, num_groups=1, if_act=True, name=None, bias_attr=False): conv = nn.conv2d( input=input, ...
The code constructs a High-Resolution Network (HRNet) for image processing. It processes input through multiple stages with varying channel configurations, using convolutional layers, transition layers, and parallel branches. Features from different stages are upsampled to align resolutions, concatenated, and passed th...
def high_resolution_net(input, num_classes): channels_2 = cfg.MODEL.HRNET.STAGE2.NUM_CHANNELS channels_3 = cfg.MODEL.HRNET.STAGE3.NUM_CHANNELS channels_4 = cfg.MODEL.HRNET.STAGE4.NUM_CHANNELS num_modules_2 = cfg.MODEL.HRNET.STAGE2.NUM_MODULES num_modules_3 = cfg.MODEL.HRNET.STAGE3.NUM_MODULES ...
def add_to_watchlist(message, params): author_id = message.author.id filename = watchlists_data_path + os.sep + author_id + ".json" if not os.path.exists(filename): data = {} data['watchlist'] = [] with open(filename, 'w') as outfile: json.dump(data, outfile) with ope...
The main task of the code is to parse a message's content to determine an action (add, delete, search, or event search) on a watchlist. It processes the message by checking prefixes like 'wa', 'wd', 'ws', or 'we', extracts parameters, and delegates to corresponding functions such as `add_to_watchlist`, `delete_from_wat...
def process_watchlist(message): params = [] if message.content.startswith('!'): message.content = message.content[1:] if message.content.startswith('wa'): params.append('a') params.append(message.content.split()[1:]) elif message.content.startswith('wd'): params.append('d...
def draw_rect(my_turtle, x_pos, y_pos, width, height): # todo test """ Draw rectangle at given position of given size. :param my_turtle: Turtle object :param x_pos: left-most x position of rectangle (in pixels) :param y_pos: bottom-most y position of rectangle (in pixels) :param width: width o...
The function `draw_house` uses Turtle graphics to render a house with a garage, 1 door, 4 windows, 2 trees (optional), and 2 clouds on a customizable canvas. It accepts parameters for canvas size, tree rendering, and window persistence. The house and garage are drawn as rectangles, with doors and windows placed proport...
def draw_house(world_width, world_height, skip_trees=False, keep_window_open=True): """Draw house with garage, 1 door, 4 windows, 2 trees, and 2 clouds on blank canvas. :param world_width: width of world (in pixels) :param world_height: height of world (in pixels) :param skip_trees: optional boolean pa...
def handle_missing_values(df, prop_required_column = .7, prop_required_row = .5): # create thresholds thresh = threshold(df, 'index', prop_required_column) # drop cols that don't meet prop requirement df.dropna(axis=1, thresh=thresh, inplace=True) thresh = threshold(df, 'columns', prop_req...
The main task of the code is to clean and preprocess the Zillow dataset by handling missing values, removing irrelevant columns, renaming variables, applying domain-specific assumptions, mapping counties, converting data types, eliminating duplicates, and removing outliers based on standard deviations. The function ret...
def clean_zillow(df): # drop nulls and extra column #df = df.dropna() df = handle_missing_values(df) df = drop_zillows_cols_and_na(df) df = rename_cols(df) df = domain_assumptions(df) df = map_counties(df) df, quants = convert_zillow_dtypes(df) df = drop_duplicates(df) #remo...
def add_dist_cols(df, county='all'): la_dist = ['dist_from_la', 'dist_from_long_beach', 'dist_santa_monica', 'dist_from_malibu', 'dist_from_bel_air'] oc_dist = ['dist_balboa_island', 'dist_laguna_beach', 'dist_seal_beach'] ventura_dist = ['dist_simi', 'dist...
This function splits a dataset into training, validation, and test sets, adds distance-related columns based on a specified county, encodes and scales features, and prepares structured data for modeling by renaming and combining scaled features with original datasets. It returns all processed data splits along with the...
def all_train_validate_test_data(df, target_var, county): train, validate, test = split.train_validate_test_split(df, target_var) train = add_dist_cols(train, county) validate = add_dist_cols(validate, county) test = add_dist_cols(test, county) x_train_scaled, y_train, \ x_validate_scaled, y_va...
def has_current(self) -> bool: return self.index < len(self.text) def current(self) -> str: if not self.has_current(): raise ParseException('Unexpected end of input', self) return self.text[self.index] def next(self): self.index += 1 # let's skip the whitespaces - we ...
The code parses a numeric literal (integer or float) from a character stream by collecting digits, underscores, and decimal points. It constructs a string from these characters, then attempts to convert it to a float wrapped in a `Value` object. If conversion fails (invalid format), it raises a `ParseException` with th...
def parse_value(self) -> Value: value = '' while self.has_current() and self.current() in '0123456789_.': value += self.current() self.next() try: return Value(float(value)) except ValueError: # not an int/float raise ParseException(f'Inval...
def has_current(self) -> bool: return self.index < len(self.text) def current(self) -> str: if not self.has_current(): raise ParseException('Unexpected end of input', self) return self.text[self.index] def next(self): self.index += 1 # let's skip the whitespaces - we ...
The code parses a variable name by iterating through alphanumeric characters and underscores, concatenating them into a string, then encapsulating the result in a `Variable` object. It advances through the input stream until non-alphanumeric/underscore characters are encountered, ensuring proper tokenization of variabl...
def parse_variable(self) -> Variable: variable = '' while self.has_current() and (self.current().isalnum() or self.current() == '_'): variable += self.current() self.next() return Variable(variable)
def process_game_events(self) -> None: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key in [K_UP, K_DOWN, K_RIGHT, K_LEFT]: if not self.direction_lo...
This code updates the game state by processing events, checking collisions, moving the snake, and rendering the screen. It manages the game loop, controls the snake's direction, handles apple collisions for growth, tracks death counts, and resets speed upon death, ensuring smooth gameplay at the specified FPS.
def run(self) -> None: if self.speed_list[self.tick_number] != (0, 0): self.direction_lock = False self.clock.tick(self.game_fps) self.tick_number += 1 if self.tick_number >= len(self.speed_list): self.tick_number = 0 self.process_game_events() ...
def _mutation(self): p1, p2 = self._event_timetables[np.random.randint(0, self._event_timetables.shape[0], 2)] mutation_cond = numpy.random.uniform() <= self._parameters.mutation_rate return [self._apply_move_n1(p) if mutation_cond else self._apply_move_n2(p) for p in [p1, p2]] def _crossover(se...
This function performs a differential evolution step by mutating parents, crossover to generate children, evaluating their quality, selecting the better child, and updating the population if it outperforms the current best solution.
def _differential_evolution_algorithm(self): p1_m, p2_m = self._mutation() child_1, child_2 = self._crossover(p1_m, p2_m) child_qualities = [self._object_function(child) for child in [child_1, child_2]] better_child = (child_qualities[0], 0) if child_qualities[0] < child_qualities[1] els...
def _load_parameters(self): global PARAMETERS_FILE file = os.path.abspath(os.path.dirname(__file__) + f"/{PARAMETERS_FILE}") if not os.path.exists(file): raise FileNotFoundError with open(file) as json_file: parameters = json.load(json_file) jsonschem...
The code executes a differential evolution algorithm (DEA) for optimization, initializing parameters, applying a constructive heuristic, and evaluating timetables. It iteratively improves solutions over generations, logging fitness values and terminating early if optimal (fitness=0). Finally, it prints the optimized ev...
def run(self): self._load_parameters() self._constructive_heuristic() self._evaluate_timetables() # results = [] # uncomment to run experiments for idx, _ in enumerate(range(self._parameters.generations_number)): logger.warning(f"Run DEA iteration no. {idx}: {self._f...
def reset(self): for obj in self.objs(): obj.delete() for player in _players: player.delete() _players.clear() _batches.clear() self.mode = 'go' self.set_instruction('Use ←↓↑→ or WASD to move. Press R to reset.') pyglet.clock.unschedule(sel...
This code updates all objects in the world by iterating through them and calling their update method with a time delta (dt). It checks if the world is complete, and if so, transitions to a 'stop' state, unschedules further updates, displays a completion message, plays a sound, and resets movement tracking.
def update_all(self, dt): if self.mode == 'reset': self.reset() for obj in self.objs(): obj.update(dt) if self.is_complete(): self.mode = 'stop' pyglet.clock.unschedule(world.update_all) self.complete.visible = True self.set...
def _handle_events(self): """ Handle key events """ for event in pg.event.get(): if event.type == pg.QUIT: self.playing = False self.running = False elif event.type == pg.KEYDOWN: pressed = pg.key.get_pressed() ...
The code runs a game loop handling events, updating state, and rendering at a fixed FPS. After the loop, it adjusts mutation probability (pb) based on the max score achieved, then evolves the population using cgp.evolve with the adjusted pb, MU, and LAMBDA parameters to drive generational improvement.
def run(self): self.playing = True while self.playing: self._handle_events() self._update() self._draw() self._clock.tick(self._fps) if not self.running: return # one generation finished and perform evolution again # if ...
def select_leaf(self, node): """Traverse the tree until in an unexpanded node and return this node""" # search_path for storing the nodes visited in. search_path = [node] # Traverse tree until in leaf node while node.expanded: action, node = self.select_child(node) ...
This code performs a single Monte Carlo Tree Search (MCTS) iteration by selecting a leaf node from the root, expanding it if the state is non-terminal, evaluating its value, and backpropagating the result along the search path to update the tree's statistics. The process enhances the tree with new information to guide ...
def search(self, root): """Execute one MCTS search from root node""" # Select a leaf node - traverse the tree from the root until in a leaf. leaf, search_path = self.select_leaf(root) # Expand leaf node - if the leaf's state is not terminal, expand the leaf. if not self.env_clo...
def add_exploration_noise(self, node): """Add exploration noise to probabilities in a node's children using dirichlet noise""" actions = node.children.keys() noise = np.random.gamma(self.dirichlet_alpha, 1, len(actions)) noise_sum = sum(noise) normalised_noise = [n / noise_sum fo...
The code performs one step of Monte Carlo Tree Search (MCTS) by running simulations to explore actions, adjusting exploration-exploitation balance via temperature parameter `tau`, computing a policy from visit counts, selecting an action, and updating the current node. It introduces noise for exploration, aggregates vi...
def run(self): """Run one step using MCTS returning an action and policy""" self.add_exploration_noise(self.current_node) # Introduce some noise to encourage exploration # Run MCTS simulations for _ in range(self.num_simulations): self.env_clone = self.env.clone() ...
def cancel_all_open_orders(): res_a = xb.getopenorders("A") for order in res_a: msg = "A.CANCELLING:\n", order["id"] # print(msg) trade_logger.info(msg) # print(x) xb.cancelorder("A", order['id']) time.sleep(1) res_b = xb.getopenorders("B") for order in re...
The main task of the code is to execute automated trades between two blockchain instances (A/B) by checking market balances, volume targets, and order data. It randomly selects trading pairs, cancels open orders, and executes trades on either 'side1' or 'side2' based on balance validation. The loop includes delay manag...
def main(): global trade_counter, flush_timer, ccblockcounts_logger_timer fail_count = 0 try: print("dxloadxbridgeconf A:", xb.dxloadxbridgeconf("A")) print("getnetworkinfo A:\n", xb.getnetworkinfo("A")) print("dxloadxbridgeconf B:", xb.dxloadxbridgeconf("B")) print("getnetwo...
def is_wp_oauth_error(self, response) -> bool: """ validate the structure of the response object conforms to a wp-oauth error json dict. """ qc_keys = ["error" "error_description"] return self.is_valid_dict(response, qc_keys) def is_get_user_details_extended_dict(self, re...
This function determines the type of a given response by checking its structure and content. It returns specific string labels like 'error response json dict' or 'get_user_details() return dict' based on predefined conditions, or 'unrecognized response dict' if none match. The goal is to classify the response for handl...
def get_response_type(self, response) -> str: if type(response) != dict: return "unknown response of type {t}".format(t=type(response)) if self.is_wp_oauth_error(response): return "error response json dict" if self.is_get_user_details_extended_dict(response): ...
def is_valid_get_user_details_response(self, response) -> bool: """ True if the response object can be processed by get_user_details() """ return self.is_valid_user_details(response) or self.is_wp_oauth_response( response ) def get_response_type(self, response) -> str...
The function `get_user_details` processes a response object to extract and structure user information into a dictionary. It validates the response, handles extended or invalid formats by logging errors/warnings, and populates `self.user_details` with fields like ID, name, email, roles, and OAuth tokens. It returns the ...
def get_user_details(self, response) -> dict: if not self.is_valid_get_user_details_response(response): logger.error( "get_user_details() received an invalid response object of {t}:{response} Cannot continue. Returning: {retval}".format( t=self.get_response_type(r...
def _urlopen(self, url): """ ensure that url response object is utf-8 encoded. """ return urlopen(url).read().decode("utf-8") def get_user_details(self, response) -> dict: if not self.is_valid_get_user_details_response(response): logger.error( "get_use...
This function retrieves user data via an API using an access token, validates the response, and updates a user's details in the database if necessary. It handles errors, logs activities, and synchronizes fields like is_superuser, is_staff, first_name, and last_name when the UPDATE_USER_ON_LOGIN flag is enabled.
def user_data(self, access_token, *args, **kwargs) -> dict: response = None user_details = None url = f"{self.USER_QUERY}?" + urlencode({"access_token": access_token}) if VERBOSE_LOGGING: logger.info("user_data() url: {url}".format(url=url)) try: respons...
def increment_pagination(self): if self.pagination_index == None: self.pagination_index = 0 else: self.pagination_index += 10 def fetch_food_truck_data(self): base_url = 'https://data.sfgov.org/resource/jjew-r69b.json' query_string = self.build_query_collection() return requests.get(base_url + query_str...
The main task of the code is to retrieve a list of open food trucks by incrementing pagination, fetching food truck data, and parsing the response. It handles paginated data retrieval and processing to return structured information about available food trucks.
def get_open_food_truck_list(self): self.increment_pagination() response = self.fetch_food_truck_data() return self.parse_response(response)
def read_assets(csv_path: str) -> Iterator[Asset]: with open(csv_path, 'r', newline='') as f: reader = csv.reader(f) next(reader) for (name, area, h, phase, rf, phi, sw, temp, pres, api, sg) in reader: yield Asset(name, float(area), float(h), Phase.OIL if phase == 'o...
The main task of the code is to convert data from a source CSV file to a destination CSV file by processing each asset. It reads assets from the input CSV, calculates the original in-place (OIP) volume and estimated ultimate recovery (EUR) for each, and writes the results—including asset name, phase type (oil/gas), OIP...
def main(argv: List[str]) -> int: try: _, src_csv, dst_csv = argv except ValueError: print(f'usage: {argv[0]} src-csv-path dst-csv-path', file = sys.stderr) return 1 with open(dst_csv, 'w', newline='') as f: w = csv.writer(f) w.writerow(OUTPUT_HDR) for asset ...
def start_server(self): self.kill_server() print('Starting server and keeping it up ...') # replace with `21 sell` when that command is ready server = Popen(['python3', self.server_script], stderr=PIPE) while True: line = server.stderr.readline().decode('utf-8') ...
The code tests a system's functionality by publishing, verifying presence via CLI/web, deleting, ensuring removal, resetting, republishing, updating, re-verifying presence, purchasing, and deleting again. It validates correct behavior of publish, delete, reset, update, and buy operations through assertion checks on sea...
def run_test(self): self.start_server() self.publish() assert self.search_found_cli() assert self.search_found_web() self.delete() assert self.search_not_found_cli() assert self.search_not_found_web() self.reset() self.publish() assert s...
def is_empty(self) -> bool: return self.empty_spaces() == self.__max_level__ def empty_spaces(self) -> int: empty = 0 while empty < self.__max_level__: if self.__contents__[empty] == None: empty += 1 else: break return empty def t...
This function determines if a given pour can be received by checking if the container is empty, if the pour's amount fits into the available space, and if the pour's color matches the top color of the container.
def can_receive(self, pour: Pour) -> bool: if self.is_empty(): return True (colour, amount) = pour return amount <= self.empty_spaces() and colour == self.top_colour()
def _get_studies(self): """Get information of current studies. Input: None Return: - list of the dict, or - None if something goes wrong. """ studies = [] search_path = JUPYTER_WORKSPACE if not os.path.isdir(search_path): ...
The main task of the code is to allow a user to start studying a report by checking it out in their Jupyter lab environment. It verifies the report's existence, ensures it's not already in use, authenticates the user, creates a lab if needed, and establishes a symlink to the report. The function returns success with la...
def start_study(self, report_id, username, password): """Start a study for a specified user. Input: report_id - Report ID to be studied username - Username associated with the lab password - Password to be set/checked Return: - (True, json-block...
def reset(self): #delete everything for pix in self.pixels: pix.delete() self.pixels=[] i=0 for x in self.matrix: j=0 for y in self.matrix[i]: ...
The code modifies a pixel at (i,j) by setting it to black (0) if it isn't already. It then resets the grid and updates all pixels via a linear scan. If the pixel was already black, it flushes the row. The main task is to update the grid state by blackening a pixel and propagating changes through the matrix.
def delij(self,i,j): #check if the pixel is not black if self.matrix[i,j]!=0: self.matrix[i,j]=0 #update matrix element to zero self.reset() #reset the grid with non-black pixels #linear scan...
def is_two_circle_intersect(wc1x,wc1y,r1, wc2x,wcy2,r2): d12 = get_dist_two_points((wc1x,wc1y), (wc2x,wcy2)) return d12 <= (r1+r2) def rec_to_world(rec:PlacedPrimitive): wrec = {} lps = [np.array([[rec.primitive.xmax], [rec.primitive.ymax]]), np.array([[rec.primitive.xmin], [rec.primitiv...
The code checks if two placed geometric primitives (circles or rectangles) collide by evaluating their positions and dimensions. It handles four shape combinations: circle-circle, rectangle-circle, circle-rectangle, and rectangle-rectangle. For each case, it uses helper functions to calculate intersections, convert sha...
def check_collision_shape(a: PlacedPrimitive, b: PlacedPrimitive) -> bool: # This is just some code to get you started, but you don't have to follow it exactly # This is just some code to get you started, but you don't have to follow it exactly if isinstance(a.primitive, Circle) and isinstance(b.primitive,...
def get_circle_from_plpr(self, rb_plpr, clock_deg=1.0): pose_at_w = np.array([[rb_plpr.pose.x],[rb_plpr.pose.y]]) r_cuvr = 1 / self.params.max_curvature # min curvature radius c_local_ctcw = np.array([[0],[r_cuvr]]) c_local_cw = np.array([[0],[-r_cuvr]]) theta_deg = ...
The main task of the code is to generate a feasible motion plan from a start pose to a target pose using circle-based path planning. It constructs a graph of valid circular transitions, checks direct and indirect paths via intermediate circles, and compiles a sequence of rotation and straight-line movement steps to nav...
def generate_best_plan(self, PQ, clock_deg=1.0): """return bool, plan""" p0 = PQ.start pt = PQ.target rb_plpr_0 = PlacedPrimitive(pose=p0,primitive=self.params.body[0].primitive) rb_plpr_t = PlacedPrimitive(pose=pt,primitive=self.params.body[0].primitive) ...
def _fire_bullet(self): if len(self.bullets) < self.settings.bullets_cadence and self.stats.game_active and not self.stats.game_paused: new_bullet = Bullet(self) self.bullets.add(new_bullet) self.sounds.play_sound(self.sounds.bullet_sound) def _start_game(self): if no...
This function handles keydown events in a Pygame game, mapping specific keys to actions: right/left arrow keys control ship movement, 'q' quits the game, 'space' fires bullets, 'j' starts the game, and 'p' pauses it. It updates the ship's movement flags and triggers corresponding methods for game actions.
def _check_keydown_events(self, event) -> None: if event.key == pygame.K_RIGHT: self.ship.is_moving_right = True elif event.key == pygame.K_LEFT: self.ship.is_moving_left = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE:...
def _check_keydown_events(self, event) -> None: if event.key == pygame.K_RIGHT: self.ship.is_moving_right = True elif event.key == pygame.K_LEFT: self.ship.is_moving_left = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE:...
This method checks for keyboard, mouse, and quit events in a Pygame game. It exits the game on quit events, processes key presses/releases via helper methods, and detects mouse clicks on the play button by retrieving the mouse position and triggering a play button check.
def _check_events(self) -> None: """Looks for keyboard and mouse inputs to close the game""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) ...
def _check_fleet_edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """handles ship hit""" # check if the game should still active before remove a live if self.stat...
The code updates alien positions by checking fleet edges, moving aliens, detecting collisions with the player's ship (triggering a hit response), and verifying if any aliens have reached the bottom of the screen.
def _update_aliens(self): """updates all alien positions""" self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() self._check_aliens_bottom()
def _check_events(self) -> None: """Looks for keyboard and mouse inputs to close the game""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) ...
The main task of the code is to run a game loop that continuously checks for events, updates game elements (ship, bullets, aliens) when the game is active and unpaused, and renders the screen. The loop maintains gameplay flow by handling user input, physics, and visual updates in real-time.
def run_game(self) -> None: """Init the game""" while True: self._check_events() if self.stats.game_active and not self.stats.game_paused: self.ship.update() self._update_bullets() self._update_aliens() self._update_sc...
def forward_computation_dataset(w, v, dataset): """Calculates the predictions for the entire training set. """ print("--- FOWARD COMP ----") y_hat_all = [] for i in range(len(dataset)): x = list(dataset[i]) x[len(x)-1] = 1 # override y to be the bias 1 y_hat_all.append(forward_computation(w, v, x)[1]) re...
The main task of the code is to perform backpropagation over an entire training dataset to compute average gradients for model parameters `v` and `w`. It calculates predictions, computes loss and its derivative, accumulates gradients from each training example, and normalizes them by dividing by the dataset size. The f...
def backpropagation_dataset(v, w, dataset, y_axis): """Calculates the gradients over the entire training set. """ # get all the y-values from the dataset as a vector y = [] for i in range(len(dataset)): y.append(dataset[i][2]) y_hat_all = forward_computation_dataset(w, v, dataset) # compute prediction for eve...