dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def stem(inputs, num_filters): # Construct the Stem Convolution Group # inputs : input vector # First Convolutional layer, where pooled feature maps will be reduced by 75% conv = Conv_2D_Block(inputs, num_filters, 7, 2) if conv.shape[1] <= 2: pool = tf.keras.layers.MaxPooling2D(pool_size=(1,...
The main task of the code is to construct a ResNet34 model using TensorFlow. It defines an input layer, applies a stem convolution group, processes features through the learner (residual blocks), and feeds the output into an MLP for final predictions. The model is instantiated and returned as a Keras model with specifi...
def ResNet34(self): inputs = tf.keras.Input((self.length, self.width, self.num_channel)) # The input tensor stem_ = stem(inputs, self.num_filters) # The Stem Convolution Group x = learner34(stem_, self.num_filters) # The learner outputs = self.MLP(x) # Instantiate the Model ...
def stem_bottleneck(inputs, num_filters): # Construct the Stem Convolution Group # inputs : input vector # First Convolutional layer, where pooled feature maps will be reduced by 75% conv = Conv_2D_Block(inputs, num_filters, 7, 2) if conv.shape[1] <= 2: pool = tf.keras.layers.MaxPooling2D(po...
The code defines a ResNet50 model using TensorFlow/Keras. It constructs a neural network by first creating an input tensor, then applying a stem bottleneck convolution group, followed by a learner block with specified filters, and finally a Multi-Layer Perceptron (MLP) for output processing. The model is instantiated a...
def ResNet50(self): inputs = tf.keras.Input((self.length, self.width, self.num_channel)) # The input tensor stem_b = stem_bottleneck(inputs, self.num_filters) # The Stem Convolution Group x = learner50(stem_b, self.num_filters) # The learner outputs = self.MLP(x) # Instantiate...
def stem_bottleneck(inputs, num_filters): # Construct the Stem Convolution Group # inputs : input vector # First Convolutional layer, where pooled feature maps will be reduced by 75% conv = Conv_2D_Block(inputs, num_filters, 7, 2) if conv.shape[1] <= 2: pool = tf.keras.layers.MaxPooling2D(po...
The code defines a ResNet101 model using TensorFlow, constructing a deep neural network with an input layer, a stem bottleneck convolution group, a learner block (likely containing residual layers), and a Multi-Layer Perceptron (MLP) for classification. It returns the compiled model architecture for image processing ta...
def ResNet101(self): inputs = tf.keras.Input((self.length, self.width, self.num_channel)) # The input tensor stem_b = stem_bottleneck(inputs, self.num_filters) # The Stem Convolution Group x = learner101(stem_b, self.num_filters) # The learner outputs = self.MLP(x) # Instantia...
def stem_bottleneck(inputs, num_filters): # Construct the Stem Convolution Group # inputs : input vector # First Convolutional layer, where pooled feature maps will be reduced by 75% conv = Conv_2D_Block(inputs, num_filters, 7, 2) if conv.shape[1] <= 2: pool = tf.keras.layers.MaxPooling2D(po...
The code defines a ResNet-152 model using TensorFlow/Keras. It constructs a neural network by first creating an input layer, applying a stem bottleneck convolution group, processing features through the learner152 module, and classifying outputs via an MLP. The model is instantiated and returned for use in tasks like i...
def ResNet152(self): inputs = tf.keras.Input((self.length, self.width, self.num_channel)) # The input tensor stem_b = stem_bottleneck(inputs, self.num_filters) # The Stem Convolution Group x = learner152(stem_b, self.num_filters) # The learner outputs = self.MLP(x) # Instantia...
def add_news(id, stock, news, top_news): for article in news: sql = "SELECT title FROM articles WHERE title = %s" val = (article['title'], ) cur = mysql.connection.cursor() cur.execute(sql, val) exists = cur.fetchall() cur.close() if not top_news: ...
The main task of the code is to retrieve and aggregate financial data for a given stock ticker, including news, sentiment analysis, sustainability metrics, analyst recommendations, and price history, then render this information in a web view for display.
def view(ticker): cur = mysql.connection.cursor() cur.execute("SELECT * FROM stocks WHERE ticker = %s", (ticker, )) stock = cur.fetchone() id = stock[0] top_news = [] all_news = [] try: top_news = news.top_news(stock[2]) all_news = news.all_news(stock[2]) add_news(id...
def start_menu(): global game_option game_option = int(input('Press 1 for Single/Computer\nPress 2 for Multiplayer\nOption : ')) def display_board(): print(f"{board[0]} | {board[1]} | {board[2]}") print(f"{board[3]} | {board[4]} | {board[5]}") print(f"{board[6]} | {board[7]} | {board[8]}") def handl...
The main task of the code is to orchestrate a game loop that starts the game menu, displays the board, handles player turns, checks for game-ending conditions, and switches players until the game concludes. It manages turn-based gameplay flow by repeatedly processing moves, evaluating win/draw states, and alternating p...
def play_game(): # menu of the game start_menu() # Display initial game display_board() while game_is_going: handle_turn(current_player) check_if_game_over() flip_player(current_player)
def check_for_winner(self, icon): # check row if self.check_rows(): self.winner = self.current_player # check column elif self.check_column(): self.winner = self.current_player # check diagonals elif self.check_diagonal(): self.winner =...
This function handles player and computer moves in a tic-tac-toe game. It updates the board with the current player's icon, checks for a win, switches players, and updates UI elements like turn labels and scores. If playing against the computer (game_option=1), it executes the computer's move, updates the board, and tr...
def flip_player(self, pos, icon, icon1, icon2): self.is_game_running = True if self.current_player == 'X' and self.is_game_running: self.list_of_x.append(pos) self.board[pos] = 'X' self.check_for_winner(icon) if self.is_game_running: self.c...
def compile_all(li, recipient, sender): reactt_1, reactt_2 = reaction_time( li)[sender], reaction_time(li)[recipient] # print(reactt_1) words_1, words_2 = most_used(li, recipient, sender)[ 0], most_used(li, recipient, sender)[1] # print(words_1[0]) read_1, read_2 = leaving_on_read( ...
The code calculates sender and recipient scores based on sentiment, texting patterns, read status, reaction time, and reactions. It weights these factors (30% sentiment, 20% texting, 10% read/status, 10% time, 30% reactions) to compute composite scores, returning both overall scores and individual metric breakdowns for...
def calc_score(li, recipient, sender): dict1, dict2 = compile_all(li, recipient, sender) sen1_score = dict1["sentiment"] * \ 200 if(dict1["sentiment"] >= 0.5) else (1 - dict1["sentiment"]) * 200 sen2_score = dict2["sentiment"] * \ 200 if(dict2["sentiment"] >= 0.5) else (1 - dict2["sentiment"...
def game_intro(): print("\nLet's play JENGA") def round_info(round, stand_probability): print( """ ---------- ROUND {}: PROB OF TOWER STANDING: {}% ---------- """.format( round, stand_probability ) ) def computer_turn(stand_probability): print("Computer's turn...") level...
The code simulates a Jenga game where a player and computer take turns removing blocks. The game tracks rounds and turns, reducing a "stand probability" each move. If the tower falls (stand_probability ≤ 0), the outcome is determined by whose turn it was. The computer's turn decreases stability via a function, while th...
def jenga(): round = 1 turn = 1 stand_probability = 100 game_intro() while stand_probability > 0: if turn % 2 == 1: round_info(round, stand_probability) stand_probability -= computer_turn(stand_probability) else: stand_probability -= player_turn(...
def generate_header_svd_files_for_pgm_image(filename): ascii_pgm_file_contents = img.read_ascii_pgm_file(filename) width, height, max_pixel = ascii_pgm_file_contents[:3] header_file , svd_file = utils.get_header_and_svd_txt_filenames(filename) # generates header.txt file. create_header_te...
The code generates images using SVD compression for specified rank ranges, analyzes compression details, saves stats to CSV, and plots results. It processes image dimensions, validates rank inputs, creates header/SVD files, and visualizes compression performance across ranks.
def generate_images_by_rank_range(filename, *args): # fetching width, and height. width, height = img.read_ascii_pgm_file(filename)[:2] min_size = min(width, height) # generating header.txt and svd.txt files for the given image. generate_header_svd_files_for_pgm_image(filename) # creates ...
def frequency_spectrum(self, start): """ Method to return the frequency spectrum and corresponding amplitudes. Parameters ---------- start: the number of seconds after the start of the track from where analysis begins. """ #total number o...
The method `get_pitch` analyzes an audio clip's frequency spectrum starting at a specified time, identifies significant harmonic peaks, and returns the most probable musical notes based on these peaks. It uses FFT to compute spectrum and amplitudes, detects peaks, optionally plots results, and calculates note probabili...
def get_pitch(self, start): """ Method that returns a list of frequencies whose harmonics represent the frequency spectrum of a clip the best. spectrum is a list of all the frequencies calculated using FFT. amplitudes is a list of the amplitudes corresponding to the fre...
def legalMoves(self): moves = [] for i in range (0, Dx): for j in range (0, Dy): m = Move (self.turn, i, j) if m.valid(self): moves.append (m) return moves def terminal (self): if self.existFive()[0]: return True...
The function performs a discounted playout in a game by randomly selecting legal moves until a terminal state is reached, then returns the misere score divided by (t+1) to discount future rewards. It simulates game progression, incrementing the step count (t) with each move, and uses a discounting factor to prioritize ...
def discountedPlayout(self, t): # global totalGame # totalGame += 1 # print('totalGame: '+str(totalGame)) while(True): moves = self.legalMoves () if self.terminal (): return self.misereScore () / (t + 1) n = random.randint (0, len (move...
def terminal (self): if self.existFive()[0]: return True l = self.legalMoves () if len (l) == 0: return True return False def misereScore (self): s = self.score () if s == 1: return 1 if s == 0: return -1 if ...
The function `nestedDiscountedPlayout` recursively evaluates game states by simulating moves, selecting the optimal action based on discounted future rewards. It iteratively explores legal moves, simulates each via deep copying, and computes scores using `discountedPlayout`. Scores are negated for the Black player's tu...
def nestedDiscountedPlayout (self, t): while (True): if self.terminal (): return self.misereScore () / (t + 1) moves = self.legalMoves () bestMove = moves [0] best = -2 for i in range (len (moves)): b = copy.deepcopy (se...
def parse_recommender_arguments(strings): parser = argparse.ArgumentParser() parser.add_argument('--rating_file', type=str, default="data/competition/interactions.csv") parser.add_argument('--target_users', type=str, default="data/competition/target_users.csv") parser.add_argument('--rating_key', type=s...
The code processes multiple recommendation models (IALS, item-based/user-based CF, content-based) by parsing parameters, combining their outputs with weighted parameters, and evaluating hybrid performance. It compares hybrid results against individual models, prints performance metrics, and writes recommendations based...
def main(): to_append = "" if parsed.holdout_perc != 0: to_append = " --holdout_perc "+str(parsed.holdout_perc)+" --seed "+str(parsed.seed) if parsed.rating_file != "data/competition/interactions.csv": to_append = to_append + " --rating_file "+str(parsed.rating_file) if parsed.target_use...
def hold_out_split(hold_out_percentage, interactions_file, user_key="user_id", item_key="item_id", rating_key="rating", seed=1234): temp_dic, row_number, col_number, target_users, users, position_uid_dic, \ uid_position_dic, position_iid_dic, iid_position_dic = data_importation(interacti...
The code computes user and item biases from interaction data, adjusts ratings by subtracting these biases, and constructs a sparse user-rating matrix (and a Pearson-adjusted version) for recommendation systems. It also handles data splitting, normalization, and returns structures for downstream tasks like collaborative...
def urm_computer(interactions, target_users_file=None, user_key="user_id", item_key="item_id", rating_key="rating", _user_bias_=1, _item_bias_=1): # This functions returns the couple, users to recommend and user rating matrix if args.holdout_perc != 0: temp_dic, row_number, col_number,...
def urm_computer(interactions, target_users_file=None, user_key="user_id", item_key="item_id", rating_key="rating", _user_bias_=1, _item_bias_=1): # This functions returns the couple, users to recommend and user rating matrix if args.holdout_perc != 0: temp_dic, row_number, col_number,...
The main task of the code is to generate personalized item recommendations for target users using a collaborative filtering approach. It computes user-item similarity, filters out non-recommendable items (expired or already rated), and produces top-N recommendations. The code processes each target user iteratively, lev...
def main(): user_rating_matrix, target_users, users, position_uid_dic, uid_position_dic, position_iid_dic, \ iid_position_dic, row_number, col_number, user_rated_items, item_rating_users, pearson_urm, removed_positions = \ urm_computer(args.rating_file, args.target_users, user_key="user_id", item_ke...
def user_knn(interactions, target_users_file=None, k=50, user_key="user_id", item_key="item_id", rating_key="rating", _item_bias_=1, _user_bias_=1): # This function is called in order to test or recommend using an user based collaborative filtering approach time_print("Building the URM...") # ...
This code generates user recommendations using a collaborative filtering approach with k-nearest neighbors. It processes target users in parallel across multiple CPUs, computes item similarities, filters expired items, and merges results. If testing, it evaluates recommendation quality using MAP@k metrics. The output i...
def main(interactions, target_users_file=None, k=50, user_key="user_id", item_key="item_id", rating_key="rating", rec_length=5, _item_bias_=1, _user_bias_=1): # Setting the timers global last_time global time_offset last_time = int(round(time.time() * 1000)) time_offset = last_time # ...
def score(self, state): """Given a list of size n where n is the number of party members 1 through n/2 is the first row of the table from left to right n/2 through n is the second row of the table from left to right such that n/2 is across from n. This method retu...
This code implements hill climbing strategies to optimize a state's score by swapping elements. It uses 'first-choice' (random swaps), 'greedy' (evaluates all swaps), 'random restart' (greedy with random resets), or 'simulated annealing' (nonfunctional). The process iterates for a given number of flips, updating the st...
def solve(self, flips=10, flag=False, strat="f"): """Uses other Search methods to find better scoring states. Implements hill climbing strategy. Set the default state, randomize list until we get a score better than default. Swap two positions in a newly created state, then compare the s...
def houseHolderCalc(m:Matrix, n:int)->Matrix: ''' Calculates the householder transformation matrix for m, Matrix. Is created by the formula outlined in class. Args: m: A matrix stored as a list of lists. n: An integer n (Should be set to 0 always) Returns: Returns the house...
The function `houseHolderDriver` performs QR decomposition on a matrix using Householder transformations. It iteratively applies Householder reflections to reduce the input matrix to an upper-triangular form (R) while accumulating orthogonal transformation matrices (Q). The process slices the matrix, constructs transfo...
def houseHolderDriver(m:Matrix)->List: ''' Drives the houseHolderCalc function. Basically slices and constructs the matricies to form each transformation matrix and multiplies it with m for the next iteration. Continues until the slices make a 2x2 matrix (the smallest that is useful) Args: m...
def load_data(directory): result = [] for filename in ["positives.txt", "negatives.txt"]: with open(os.path.join(directory, filename)) as f: result.append([ extract_words(line) for line in f.read().splitlines() ]) return result def generate_fre...
The main task of the code is to classify user input text as indicating a desire for a refill by analyzing word frequencies in positive and negative example datasets. It calculates probabilities based on word occurrences, adjusts them to a percentage, and outputs the likelihood of the input being a refill request, with ...
def main(): # Read data from files corpus_path = "../resources/corpus" positives, negatives = load_data(corpus_path) # Create a set of all words words = set() for document in positives: words.update(document) for document in negatives: words.update(document) words.remove...
def tpf_bkg_sub(tpf): bkg_sum = 0 nt, nx ,ny = np.shape(tpf) median_50 = np.percentile(tpf, axis=(1,2), q=50 ) median_16 = np.percentile(tpf, axis=(1,2), q=16 ) flags = [] bkg_arr = [] for i in range(nt): light_all = np.ravel(tpf[i]) flag = light_all < median_50[i] + 3* (medi...
The function processes transit photometry data by subtracting background, detecting sources via thresholding and peak finding, extracting light curves (LCs) for identified stars, applying PCA to reduce noise, and returning processed LCs, source positions, and background data for further analysis.
def return_lc_from_tpf(tpf_before_bkg, threshold_source=100, pca_comp = 5, ap_wd=3): tpf, bkg_sum, flags, bkg_arr= tpf_bkg_sub(tpf_before_bkg) tpf = tpf[flags] image = np.sum(tpf, axis = 0)/len(tpf) nx, ny = np.shape(image) neighborhood = generate_binary_structure(2,2) local_max = maximum_f...
def load_tpf(file_name): tpf = [] hdul = fits.open(file_name) header = hdul[1].header image = hdul[1].data image = image for i in range(len(image)): tpf.append(image[i][4]) hdul.close() tpf = np.array(tpf) return tpf def tpf_bkg_sub(tpf): bkg_sum = 0 nt, nx ,ny = np.s...
This function processes astronomical time-series data to extract and refine light curves (LCs) of celestial sources. It loads a target pixel file (TPF), subtracts background noise, identifies stellar positions via peak detection, generates initial LCs, and applies PCA to denoise them. The output includes the PCA-proces...
def return_lc(file_name, threshold_source=100000, pca_comp = 5): tpf_before_bkg = load_tpf(file_name) tpf, bkg_sum= tpf_bkg_sub(tpf_before_bkg) image = np.sum(tpf, axis = 0) nx, ny = np.shape(image) neighborhood = generate_binary_structure(2,2) local_max = maximum_filter(image, footprint=nei...
def data_dl(ra, dec, size): cutout_coord = SkyCoord(ra, dec, unit="deg") hdulist = Tesscut.get_cutouts(coordinates=cutout_coord, size=size ) return hdulist def load_tpf_hdulists(hdulist): tpf_arr = [] time_arr = [] for hdul in hdulist: tpf = [] header = hdul[1].header ima...
This function processes stellar data to extract and analyze light curves (LCs) from TESS Target Pixel Files (TPFs). It downloads TPFs for given coordinates, computes PCA-reduced and original LCs, saves results (LCs, centroids, background) in .npz files, generates 2D images, LC plots, Lomb-Scargle periodograms, and cent...
def main(name_arr, ra_arr, dec_arr, size = 50, start_star = "", folder_output = "../tess_output", until_i=-1, pca_comp = 5, ap_wd=3, replace = False ): flag_star = 0 if len(start_star) ==0: flag_star = 1 for i in range(len(ra_arr)): folder_out_now = folder_output + "/output/%s" % name_ar...
def check(self, *types): if self.is_at_end(): return False return self.peek().type in types def advance(self): if not self.is_at_end(): self.previous = self.current self.current = self.scanner.next() return self.previous def error(self, token, message)...
The code consumes a message based on a type check. If the type is valid, it advances processing; otherwise, it logs an error with the current token and message. The method checks validity, progresses if valid, or reports errors with context.
def consume(self, type, message): if self.check(type): return self.advance() self.error(self.peek(), message)
def is_at_end(self): return self.peek().type == TokenType.EOF def peek(self): return self.current def advance(self): if not self.is_at_end(): self.previous = self.current self.current = self.scanner.next() return self.previous
The code resets the handler and advances through tokens until encountering a left square bracket or left brace, then stops. Its main task is to navigate or parse input tokens up to a specific structural element (array or object) in a language, skipping over non-target tokens.
def reset(self): self.handler.reset() while not self.is_at_end(): if self.peek().type in ( TokenType.LEFT_SQUARE_BRACKET, TokenType.LEFT_BRACE, ): return self.advance()
def _get_string(self): token = self.previous string_scanner = StringScanner(self.scanner.source, token.start + 1, token.line) try: value = string_scanner.scan_string() except StringScanError: self.error(token, "Invalid string") else: self.scann...
This code processes a string token by validating subsequent tokens (comma, closing bracket/brace) and handling errors if invalid. It retrieves the string value, checks for allowed follow-up tokens, and passes the string's literal value to the handler if valid.
def string(self): quotes = self.previous value = self._get_string() if not self.check( TokenType.COMMA, TokenType.RIGHT_SQUARE_BRACKET, TokenType.RIGHT_BRACE ): self.scanner.current = quotes.start + 1 self.error("Cannot continue after string") ...
def query_statistics(all_sensors_df, destination_lat, destination_long, length_of_stay, max_walk, input_hour, dayofweek_letters): # start = time.time() dayofweek_dict = dict() dayofweek_dict['Monday'] = 1 dayofweek_dict['Tuesday'] = 2 dayofweek_dict['Wednesday'] = 3 dayofweek_dict['Thursday'] = ...
The function calculates parking statistics by analyzing sensor data, merging with cost data, and simulating parking scenarios based on location, stay duration, and time parameters. It processes occupation/vacancy ratios, fills missing values, and returns a structured DataFrame with insights or 'No results' on failure.
def calculate_parking_statistics(dest_lat, dest_lng, length_of_stay, max_walk, hour, day_of_week): try: all_sensors_df = pd.read_csv('all_sensors_df.csv') query_results = query_statistics(all_sensors_df, dest_lat, dest_lng, length_of_stay, max_walk, hour, day_of_week) parking_statistics_df =...
def make_cloud(L,K,D): start = timeit.default_timer() cloud_arr = np.ones((L,L,L)) #makes return array delta = np.exp(np.log(K)/D) #sets 'clumpiness' upLevel = L/(2*delta) #defines how far away a 'child' can be from a parent' for n1 in range (0,K): n1point = (np.random.random()*L, np.random....
The code generates a fractal cloud model, scales it using optical depth calculations, and simulates radiative transfer with specified parameters (trajectories, observation points). It computes intensity distributions, saves results to a .mat file, and reports total computation time.
def main(): start = timeit.default_timer() np.random.seed(4) #allows for repetability parser = argparse.ArgumentParser() parser.add_argument('L',type=int,help='length of supercube side') parser.add_argument('N',type=int,help='trajectories per direction') parser.add_argument('M',type=int,help=...
def set_active(self): """ Sets the window to active if it isn't already """ if not self.is_active(): """ Press alt before and after to prevent a nasty bug """ pyautogui.press('alt') win32gui.SetForegroundWindow(self._handle) pyautogui.press('alt') ...
This code automates teleporting to a friend in a game by checking if the friends menu is open, closing it if necessary, opening the menu, locating a friend via image matching, and performing clicks to select the friend, port, and confirmation. If the friend isn't found, it returns False.
def teleport_to_friend(self, match_img): """ Completes a set of actions to teleport to a friend. The friend must have the proper symbol next to it symbol must match the image passed as 'match_img' """ self.set_active() # Check if friends already opened (and close...
def set_active(self): """ Sets the window to active if it isn't already """ if not self.is_active(): """ Press alt before and after to prevent a nasty bug """ pyautogui.press('alt') win32gui.SetForegroundWindow(self._handle) pyautogui.press('alt') ...
This function attempts to locate a spell image on the screen by capturing screenshots of the spell area, matching it against a reference image with a specified threshold. It retries up to max_tries times, waiting 1 second between attempts. If found, it calculates the spell's position, stores it in memory, and returns t...
def find_spell(self, spell_name, threshold=0.15, max_tries=2, recapture=True): """ Attempts the find the spell passed is 'spell_name' returns False if not found with the given threshold Use recapture=False to not re-take the screenshot of the spell_area Adds spell position to me...
def set_active(self): """ Sets the window to active if it isn't already """ if not self.is_active(): """ Press alt before and after to prevent a nasty bug """ pyautogui.press('alt') win32gui.SetForegroundWindow(self._handle) pyautogui.press('alt') ...
This code identifies positions of grayed-out (unusable) spells in a game interface by analyzing a screenshot. It scans for rectangular gray areas, calculates their coordinates, and returns them to help manage spell decks for farming Loremaster, preventing overcrowded decks when learning new spells.
def find_unusable_spells(self, limit=-1): """ Returns an array of the positions of unusable spells (grayed out) """ """ Useful for farming Loremaster, it prevents getting a crowded deck if you learn a new spell """ self.set_active() self.mouse_out_of_area(self._spell_area) self.s...
def set_active(self): """ Sets the window to active if it isn't already """ if not self.is_active(): """ Press alt before and after to prevent a nasty bug """ pyautogui.press('alt') win32gui.SetForegroundWindow(self._handle) pyautogui.press('alt') ...
The function automates facing the questing arrow in a game by pressing 'a' until a specific color pixel (407,519) matches (247,231,51), then pressing 'd' proportionally to the time taken to detect the color, allowing the game to process movement. It uses pixel color detection to determine direction and timing for key p...
def face_arrow(self): """ Faces the questing arrow, useful for finding your way out of a dungeon """ self.set_active() pyautogui.keyDown('a') count = 0 while not self.pixel_matches_color((407,519), (247, 231, 51), 2): count += 1 pyautogui.keyUp('a') se...
def is_mana_low(self): self.set_active() #Matches a pixel in the lower third of the mana globe POSITION = (98, 597) COLOR = (155, 114, 208) THRESHOLD = 10 return not self.pixel_matches_color(POSITION, COLOR, threshold=THRESHOLD) def is_health_low(self): self.set_a...
The function checks if the character's mana or health is low. If either is low, it prints a message and triggers a click action at coordinates (170, 603) with a 0.2-second delay, likely to use a potion. The main task is to automatically use a potion when mana or health falls below threshold levels.
def use_potion_if_needed(self): mana_low = self.is_mana_low() health_low = self.is_health_low() if mana_low: print('Mana is low, using potion') if health_low: print('Health is low, using potion') if mana_low or health_low: self.click(170, 603,...
def is_turn_to_play(self): """ matches a yellow pixel in the 'pass' button """ return self.pixel_matches_color((242, 398), (255, 255, 0), 20) def wait(self, s): """ Alias for time.sleep() that return self for function chaining """ time.sleep(s) return self def is_idle(self): ...
The main task of the code is to wait for the end of a battle round by repeatedly checking if it's the player's turn to play or if the battle has become idle. It first waits for the turn to start, then waits until the turn ends or the battle concludes, ensuring proper synchronization with game state changes.
def wait_for_end_of_round(self): """ Similar to wait_for_next_turn, but also detects if its the end of the battle """ """ Wait for spell round to begin """ while self.is_turn_to_play(): self.wait(1) """ Start detecting if it's our turn to play again """ """ Or if it'...
def find_unusable_spells(self, limit=-1): """ Returns an array of the positions of unusable spells (grayed out) """ """ Useful for farming Loremaster, it prevents getting a crowded deck if you learn a new spell """ self.set_active() self.mouse_out_of_area(self._spell_area) self.s...
The main task of the code is to repeatedly identify and discard unusable spells by right-clicking their positions, using memory checks and fallback searches. It loops until no more unusable spells are found, flushing memory after each discard to maintain state consistency.
def discard_unusable_spells(self, limit=-1): count = 0 while True: count += 1 print(count) try: # Try accessing from memory card_pos = self._spell_memory["unusable"][0] except (KeyError, IndexError): result =...
def find_spell(self, spell_name, threshold=0.15, max_tries=2, recapture=True): """ Attempts the find the spell passed is 'spell_name' returns False if not found with the given threshold Use recapture=False to not re-take the screenshot of the spell_area Adds spell position to me...
The code's main task is to cast a specified spell by checking its existence, clearing memory cache, and selecting the spell if valid. If the spell requires a target, it must be chained with .at_target(). The function returns the spell selection result or False if the spell isn't found.
def cast_spell(self, spell): """ Clicks on the spell and clears memory cache if the spell requires a target, chain it with .at_target([enemy_pos]) """ if self.find_spell(spell): print('Casting', spell) self.flush_spell_memory() return self.sel...
def screenshot(self, name, region=False): """ - Captures a screenshot of the window and saves it to 'name' - Can also be used the capture specific parts of the window by passing in the region arg. (x, y, width, height) (Relative to the window position) """ self.set_active() ...
The code attempts to apply an enchant to a spell by locating both in the game, selecting them, and handling failures. It captures a screenshot to track monster HP during the process. If both spells are found, it selects and applies the enchant, then returns self. Otherwise, it prints an error and returns False unless s...
def enchant(self, spell_name, enchant_name, threshold=0.1, silent_fail=False): #we screenshot during enchant period as it would mean we would be in card selection which is when the monster hp pops up. #we screenshot it to be able to change the values in count_enemies method. self.screenshot('fi...
def compare_ground_truth(*,firings,firings_true,json_out,opts={}): Ft=mdaio.readmda(mlp.realizeFile(firings_true)) F=mdaio.readmda(mlp.realizeFile(firings)) times1=Ft[1,:] labels1=Ft[2,:] times2=F[1,:] labels2=F[2,:] out=compare_ground_truth_helper(times1,labels1,times2,labels2) with ope...
The main task of the code is to validate sorting results by comparing detected firings with ground truth data, compute true neuron templates, and return evaluation metrics including classification accuracies and true template amplitudes. It creates output directories, runs analysis pipelines, and aggregates results int...
def validate_sorting_results(*,dataset_dir,sorting_output_dir,output_dir): if not os.path.exists(output_dir): os.mkdir(output_dir) compare_ground_truth( firings=sorting_output_dir+'/firings.mda', firings_true=dataset_dir+'/firings_true.mda', json_out=output_dir+'/compare...
def pad_to_length(a, length): return np.pad(a, (0, length - len(a)), "constant") def FFT(a): n = len(a) if n == 1: return a else: a_even = FFT(a[::2]) a_odd = FFT(a[1::2]) factor = np.exp(-2j * np.pi * np.arange(n) / n) return np.concatenate( [a_even +...
The code performs polynomial division of two sequences `A` and `B` using FFT-based methods. It pads both sequences to the next power of two, computes their FFTs, divides them element-wise (with a small epsilon to avoid division by zero), applies inverse FFT, rounds the result, and trims trailing/leading zeros. The outp...
def divide(A, B): # Find the next power of 2 that is greater than or equal to the length of A + length of B - 1 length = 2 ** np.ceil(np.log2(len(A) + len(B) - 1)).astype(int) A_padded = pad_to_length(A, length) B_padded = pad_to_length(B, length) fft_A = FFT(A_padded) fft_B = FFT(B_padded) ...
def Poly(roots): p = Polynomial([-roots[0], 1]) for root in roots[1:]: p *= Polynomial([-root, 1]) coeffs = p.coef[::-1] formatted_coeffs = [ round(coeff, 5) if abs(coeff - round(coeff)) < 0.0001 else coeff for coeff in coeffs ] return formatted_coeffs def divide(A, B): ...
The main task of the code is to provide a user interface for selecting and executing polynomial operations (root-to-coefficient conversion, division) and signal noise removal. It reads input from text files, processes data using defined functions (Poly, divide, remove_noise), outputs results, and measures CPU time for ...
def run_ui(): print("Choose an option:") print("1 - Problem 1: Polynomial with given roots") print("2 - Problem 2: Polynomial division") print("3 - Problem 3: Noise removal from a signal") print("4 - Terminate the program") choice = input("Enter your choice: ") start_time = time.process_tim...
def get_rect_coords(self): if self._rect is None: return rect = self._rect.rect() x, y, = rect.topLeft().x(), rect.topLeft().y() width, height = rect.width(), rect.height() return x, y, width, height def emit_rect(self): if self._rect is None: retu...
This function handles mouse movement to dynamically adjust a rectangle's position or size. It calculates displacement (dx, dy) between previous and current positions. If in 'moving' mode, it shifts the rect by dx/dy. If resizing, it adjusts width/height based on dragged border (left/right/top/bottom). Updates the rect ...
def mouseMoveEvent(self, event): if self._rect is None: return lastx, lasty = event.lastScenePos().x(), event.lastScenePos().y() thisx, thisy = event.scenePos().x(), event.scenePos().y() dx = thisx - lastx dy = thisy - lasty x, y, w, h = self.get_rect_coords(...
def updateAllAssets(self): for portfolio in self.portfolios: for order in portfolio.orders: currOrder = self.binance_client.get_order( symbol=order["symbol"], orderId=order['orderId']) if order["status"] != currOrder["status"]: ...
The main task of the code is to create a trade order on Binance based on provided details, handling both market and limit orders. It checks sell permissions, executes the order, updates portfolio balances, and records order details. If successful, it returns True; otherwise, it returns False upon exceptions.
def createOrder(self, portfolio_id, orderDetails): self.updateAllAssets() try: if orderDetails["type"] == "M": if orderDetails["action"] == "Buy": order = self.binance_client.order_market_buy( symbol=orderDetails["symbol"], quantity...
def generate_cache_key(self, func, *args, **kwargs): key = func.__name__ + "_" + "_".join([str(v) for v in args]) key += "_".join(["%s_%s" % (k, v) for k, v in kwargs]) return key def get_redis_cache(self, cache_key): print([cache_key, "get_redis_cache"]) conn = get_redis_conn() ...
This code implements a caching mechanism that retrieves data from either Redis or local cache using a generated key. If the value isn't found, it executes the target function, caches the result in the appropriate storage, and returns it, ensuring efficient data retrieval and reducing redundant computations.
def wrap(*args, **kwargs): cache_key = self.generate_cache_key(func, *args, **kwargs) if self._use_redis: value = self.get_redis_cache(cache_key) else: value = self.get_local_cache(cache_key) if value: return value ...
def probability(H,x,y): ybest = np.max(y) mu, std = MakeMuStd(H, x, y) if std != 0: z = (ybest - mu) / std p = norm.cdf(z) else: p = (mu < ybest) return p def GetGrad(H,h,y,Sinv): ybest= np.max(y) k=MakeKappa(H,h) Help = MakeKappaPrime(H,h) kgamma= Help[:,0...
The code implements the Adam optimization algorithm to iteratively find an optimal point `xk` by minimizing a function involving parameters `H`, `y`, and `Sinv`. Starting from a random initial guess, it updates the parameters using gradient descent with momentum (controlled by `b1`, `b2`) and adaptive learning rates (v...
def Adam(H,y,printing,Sinv,alpha,b1,b2): m = np.zeros([1, 2]) v = np.zeros([1, 2]) k=1 xk=[np.random.uniform(-10, 0), np.random.uniform(0, 9)] #Randomly choose starting point Initial=probability(H,xk,y) tol1=1 while k < 500 and tol1>10**-6: grad = GetGrad(H,xk,y,Sinv) ...
def Kernel_Matrix( X,type ): XNorm = np.sum(X ** 2, axis=-1) print(XNorm) g=gamma_parameter(X) if type=="Gaussian": K = np.exp(-(g) * (XNorm[:, None] + XNorm[None, :] - 2 * np.dot(X, X.T))) elif type=="Cauchy": A = np.ones([X.shape[0], X.shape[0]]) + g*(XNorm[:, None] + XNorm[None,...
The code implements the kernel elbow method to determine the optimal number of clusters in a dataset. It calculates the minimum error (ESD) for varying cluster counts (1 to max-1) over multiple iterations, using a kernel matrix transformation. The results are visualized as a plot showing ESD vs. cluster numbers, aiding...
def kernel_elbow(array,kerneltype,NumberOfIterations,max): nClusters = range(1,max); ESD=[] IDs=range(array.shape[0]) ker=Kernel_Matrix(array,kerneltype) for i in nClusters: S=0 print('analyzing number of clusters:',i) for iter in range(NumberOfIterations): Initi...
def cluster_start(number_of_clusters,IDs): #Initialize the clusters randomly cluster_list = [] for i in range(number_of_clusters): cluster_list.append([]) for i in IDs: assigned_list = np.random.choice(number_of_clusters) cluster_list[assigned_list].append(i) #Lists of elements in ...
This function evaluates the stability of clustering results under random node removal. It initializes clusters, runs clustering twice (before/after removing a fraction of nodes), compares cluster changes, and returns stability score (S) and error ratio (ER). S measures cluster consistency post-removal, while ER compare...
def stability(NumberOfClusters,ker,level,seed): np.random.seed(seed) IDs=range(ker.shape[0]) InitialClusters = cluster_start(NumberOfClusters,IDs) ClusterList,ESD = call( NumberOfClusters, ker, IDs, InitialClusters) PreSet=ListToSet(ClusterList) HowManyToRemove=int(np.floor(level*ker.shape[0])) ...
def MakeSigma(H): l=1 #how to choose ASK #Grid search fr this hp HNorm = np.sum(H ** 2, axis=-1) Sigma = np.exp(- (HNorm[:, None] + HNorm[None, :] - 2 * np.dot(H, H.T))/(2* l**2)) return Sigma def Adam(H,y,printing,Sinv,alpha,b1,b2): m = np.zeros([1, 2]) v = np.zeros([1, 2]) k=1 x...
The function `BestAdam` aims to find the optimal parameters (`bxk`) that minimize an acquisition function by iteratively applying the Adam optimizer. It initializes parameters, computes the inverse of a covariance matrix (`Sinv`), and runs Adam to generate initial solutions. Through a loop, it refines solutions, compar...
def BestAdam(H,y,flag): alpha= 0.01 b1=0.9 b2=0.999 Sinv = np.linalg.inv(MakeSigma(H)) bxk=Adam(H,y,flag,Sinv,alpha,b1,b2)[0] best=probability(H,bxk,y) k=0 while k<50 and best>0.25: xk=Adam(H,y,0,Sinv,alpha,b1,b2)[0] p=probability(H,xk,y) k+=1 if p<bes...
def GetGrad(H, h, y, l,a_type): # INPUT: ~H: matrix containing the previously evaluated points # ~h: the point at which we want to calculate the gradient # ~y: the evaluation of G at the previous points stored in H # ~l: length scale parameter # ~a_type: acquisition Function...
The function `ADAM_Optimizer` minimizes an acquisition function (e.g., Expected Improvement or Probability) using the Adam optimization algorithm. It iteratively updates the current point `xt` by computing gradients via `GetGrad`, applying Adam's momentum and RMSProp components to adjust the learning rate. Boundary con...
def ADAM_Optimizer(xt,H, y, l,a_type,printing): # INPUT: ~H: matrix containing the previously evaluated points # ~h: the point at which we want to calculate the gradient # ~y: the evaluation of G at the previous points stored in H # ~l: length scale parameter # ~a_type: acqu...
def Eval_probability(H, h, y, l): # INPUT: ~H: matrix containing the previously evaluated points # ~h: the point at which we want to calculate the gradient # ~y: the evaluation of G at the previous points stored in H # ~l: length scale parameter # # # OUTPUT: Evaluation of...
The function `COORD_search` performs a grid search over a 2D domain to identify the optimal point based on a specified acquisition function (Probability or Expected Improvement). It evaluates the acquisition function across a meshgrid, computes the corresponding values, and returns the coordinates of the minimum (for P...
def COORD_search(H,y,l,a_type,printing): # INPUT: ~H: matrix containing the previously evaluated points # ~y: the evaluation of G at the previous points stored in H # ~l: length scale parameter # ~a_type: acquisition Function type. P=Probability, EI=Expected Improvement # ~...
def hint(n): M=np.zeros([n,2]) M[:, 0] = np.random.uniform(-10, 0,n) #log(gamma) first column M[:,1] = np.random.uniform(0,9,n) #log(C) second column return M def EvalAcc(hnew,X,Y,kf): K = 5 # print('hnew',hnew) acc_sum = 0 gg = 10 ** hnew[0] CC = 10 ** hnew[1] for train_ind...
The main task of the code is to optimize hyperparameters using a Bayesian optimization approach with Adam, evaluating model accuracy via cross-validation. It initializes multiple starting points, iteratively refines them using the Adam algorithm, checks for NaNs, and selects the best hyperparameters based on maximum ac...
def main(): n=5 #chose how many starting points H=hint(n) K = 5 test_size = 270 / 5 kf = KFold(n_splits=K,shuffle=True, random_state=27) #Mat' bday z=np.empty(0) for i in range(H.shape[0]): h=H[i,:] mean_acc = EvalAcc(h,X,Y,kf) z= np.append(z,mean_acc ) Sinv=np...
def COORD_search(H,y,l,a_type,printing): # INPUT: ~H: matrix containing the previously evaluated points # ~y: the evaluation of G at the previous points stored in H # ~l: length scale parameter # ~a_type: acquisition Function type. P=Probability, EI=Expected Improvement # ~...
The `Hybrid_Optimizer` function identifies the minimum of an acquisition function by switching between exploration and exploitation modes. In exploration mode (step=False), it randomly samples points within a predefined range. In exploitation mode (step=True), it uses `COORD_search` and optionally `ADAM_Optimizer` to r...
def Hybrid_Optimizer(H, y, l,a_type,step): # INPUT: ~H: matrix containing the previously evaluated points # ~y: the evaluation of G at the previous points stored in H # ~l: length scale parameter # ~a_type: acquisition Function type. P=Probability, EI=Expected Improvement # ...
def hint(n): # INPUT: ~n: Number of initial points of the function # # # OUTPUT: ~M: matrix containing the points at which to initially evaluate G M = np.zeros([n, 2]) M[:, 0] = np.random.uniform(-10, 0, n) # In the first column we have the log(gamma) coordinate M[:, 1] = np.random.uniform...
The main task of the code is to perform Bayesian optimization for hyperparameter tuning using a hybrid approach. It initializes candidate parameters, evaluates their performance via cross-validation, iteratively refines solutions with exploration-exploitation balance, and identifies optimal log(gamma) and log(C) values...
def Bayesian_Optimizer(seme): # INPUT:~Seme: setting the random seed # # # OUTPUT: Does most of the work n = 5 # chose how many starting points explore=8 #How much exploration a_type="P" #A.F. type l=0.5 #Length Scale Parameter np.random.seed(seme) #set random seed H = hint(n)...
def read_train_list(fn): ''' return dataframe(sampleID label_fn) ''' df = pd.read_table(fn, index_col=0) # ID label_fn num_pos num_neg geneExp_fn return df def read_sequence_feature(seqFeature_fn): data = pd.read_csv(seqFeature_fn, sep='\t', index_col=0) data = data.iloc[:, 13:] ret...
The main task of the code is to train a machine learning model for classification using sequence features, gene expression data, and splicing information. It initializes a classifier, processes training data in batches, performs cross-validation, evaluates model performance (accuracy, loss, AUROC/AUPR), implements earl...
def train_model(fn, odir, geneExp_absmax, seqFeature, RBP_dir, splicing_max='', splicing_dir='', splicing_amount=True, CIRIdeepA=False): if not os.path.isdir(odir): os.mkdir(odir) print('output directory: %s' % odir) print('input train list: %s' % fn) train_list = read_train_list(fn) ...
def train_model(fn, odir, geneExp_absmax, seqFeature, RBP_dir, splicing_max='', splicing_dir='', splicing_amount=True, CIRIdeepA=False): if not os.path.isdir(odir): os.mkdir(odir) print('output directory: %s' % odir) print('input train list: %s' % fn) train_list = read_train_list(fn) ...
The code defines a command-line tool (`CIRI-deep`) for predicting differentially spliced circRNAs. It supports two modes: `train` (to train the model with custom data) and `predict` (to use a pre-trained model for prediction). The tool processes input files, model paths, and parameters like gene expression thresholds, ...
def main(): prog = 'CIRI-deep' description = 'CIRI-deep predicts differentially spliced circRNAs between biological samples. This program can be used for training and predicting.' epilog = 'Zihan Zhou <odpai@example.com>' argparser = ap.ArgumentParser(prog=prog, description=description, epilog=epil...
def fillTable(self): if anki_21_version <= 44: headers, row_contents_list_of_lists = self.gather_contents_old() else: headers, row_contents_list_of_lists = self.gather_contents_new() self.oldnids = [i[0] for i in row_contents_list_of_lists] row_count = l...
The main task of the code is to initialize and configure the user interface components of a card organizer application. It populates the table with data, sets up date-related functionality, configures headers, restores window geometry, connects event handlers, and focuses on the currently selected card for user interac...
def setupUi(self): # print("=====Performance benchmark=====") # start = timer() self.fillTable() # end = timer() # print("total", end - start) self.setupDate() self.updateDate() self.setupHeaders() restoreGeom(self, "organizer") self.se...
def _validate_keys(required: Set, present: Set) -> Set: return required - present def _filter_required_keys(required: Dict) -> Set: return {k for k, v in required.items() if v} def _filter_present_keys(present: Dict) -> Set: return {p for p in present.keys() if not p.startswith('.')} def validate_selectors(...
This function validates a pipeline template's structure and contents. It checks required keys, ensures 'phases' is a list, converts 'template' and 'includes' to full paths, validates 'selectors' and 'jobs' recursively, and raises exceptions for missing/invalid fields. The goal is to enforce schema compliance and path n...
def validate_pipeline(pipeline_template: Dict, path_keys: Tuple) -> Dict: # 'the key at this level': True (required to be present) or False (optional) level_keys = { 'phases': True, 'template': True, 'includes': False, 'selectors': False, 'host_order_label': True, 'jobs': True } if miss...
def betweenness_centrality_parallel(self, G, processes=None): if self.verbose: print("Computing Centrality with", processes, "processes.") """Parallel betweenness centrality function""" p = Pool(processes=processes) node_divisor = len(p._pool) * 4 node_chunks = list...
The code generates a "Jammin Graph" by analyzing a network's structure (clustering coefficients, betweenness centrality), selecting key topic/connector words, extracting ranked meta-patterns, and constructing a new graph from pattern matches, then saving nodes/edges to a file.
def generate_jammin_graph(self): if self.verbose: print("\nJammin Graph Generation") # Step 1: Graph Analysis G = nx.read_adjlist("temp/graph.edgelist") # Obtain the reverse nodes # nodes, reverse_nodes, edges = net_file_to_graph_data(("%s.net"%graph_path_prefix)) ...
def infonce(self, users, pos, conf): (users_emb, pos_emb, neg_emb, userEmb0, posEmb0, negEmb0) = self.getEmbedding(users.long(), pos.long(), None) users_emb = torch.nn.functional.normalize(users_emb, dim=1) pos_emb = torch.nn.functional.normalize(pos_emb, dim=1) logits = torch.m...
The code computes a multi-task loss for a recommendation model by combining the main INFONCE loss, SSL loss, contrastive loss (cl_loss), and a counter loss (conter_loss). It processes user-item interactions, extracts embeddings, normalizes them, and calculates contrastive scores. The final loss is a weighted sum of the...
def calculate_loss(self, interaction): # multi-task loss users, pos, conf = interaction[0], interaction[1], interaction[4] cold, warm = interaction[5], interaction[6] user_pop = interaction[2] item_pop = interaction[3] main_loss = self.infonce(users, pos, conf) s...
def handle_menu_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: exit() elif self.current_menu.name == "Name": name = self.player[2] if event.type == pygame.KEYDOWN: if event.key == pygame.K_B...
The code updates the game state by handling events and rendering visuals based on the current playstate. It manages menu interactions, map navigation, battle mechanics, and stat upgrades. Transitions between states (MENU, MAP, BATTLE, STATMENU) occur based on conditions like player movement, battle outcomes, or stat in...
def update(self): if self.playstate == utilities.PlayState.MENU: self.handle_menu_events() self.current_menu.render_menu(self.screen) elif self.playstate == utilities.PlayState.MAP: self.player_moved = False self.screen.fill(config.black) self...
def initialize_population(self): ''' function to randomly create the initial population using config values. Population is a list of the size [n, ], each element is one binary string of size m * b , and its values are concatenated binary representations of parame...
This function runs a genetic algorithm (GA) for a specified number of generations. It initializes a population, iteratively applies selection, crossover, mutation, and carries the best solution forward. Fitness is calculated each generation, with RMSE visualized in real-time using a plot. The process repeats until max ...
def run_ga(self): self.initialize_population() max_gen = self.config.get("max_generations") generation = 0 condition = True with tqdm(total = max_gen) as pbar: while condition: if generation >= 1: self.sele...
def initialize_population(self): ''' function to randomly create the initial population using config values. Population is of the size [n, m], each paramter is one column in this array, and its values are within specified bounds. First 3 genes are rotations, next...
This code implements a genetic algorithm (GA) to optimize a solution by evolving a population over generations. It initializes a population, iteratively selects, crosses over, mutates, and retains the best individuals while tracking fitness. The process stops when maximum generations are reached or convergence is detec...
def run_ga(self): self.initialize_population() max_gen = self.config.get("max_generations") condition = True with tqdm(total = max_gen) as pbar: while condition: if self.generation >= 1: # ax = plt.figure().add_su...
def _log_logistic(X): """ This function is used from scikit-learn source code. Source link below """ """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``. This implementation is numerically stable because it splits positive and negative values:: -log(1 + exp(-x_i)) if x_i...
This function computes the loss and gradient for a logistic regression model with fairness constraints. It calculates truncated loss gradients for two groups (A=1 and A=0), adjusts regularization via fairify(), combines truncated and non-truncated losses, and applies L2 regularization. The output includes normalized lo...
def compute_loss_grad(self, theta, X, Y): p = np.exp(_log_logistic(_dot_intercept(theta,X))) idx1 = self.grp1 # A == 1 idx0 = self.grp2 # A == 0 n = X.shape[0] self._lambda = fairify(p[idx1], p[idx0]) / n loss, grad, trunc_idx = sum_truncated_loss_grad(theta, X, Y, idx1, ...
def _log_logistic(X): """ This function is used from scikit-learn source code. Source link below """ """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``. This implementation is numerically stable because it splits positive and negative values:: -log(1 + exp(-x_i)) if x_i...
This function computes the loss and gradient for a logistic regression model with fairness constraints and regularization. It calculates probabilities using the logistic function, applies group-specific fairness adjustments via `fairify`, combines truncated and ordinary logistic losses, and adds L2 regularization. The ...
def compute_loss_grad(self, theta, X, Y): p = np.exp(_log_logistic(_dot_intercept(theta,X))) idx1 = self.grp1 # np.logical_and(A == 1, Y == 1) idx0 = self.grp2 # np.logical_and(A == 0, Y == 1) n = X.shape[0] self._lambda = fairify(p[idx1], p[idx0]) / n loss, grad, trunc_...
def _log_logistic(X): """ This function is used from scikit-learn source code. Source link below """ """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``. This implementation is numerically stable because it splits positive and negative values:: -log(1 + exp(-x_i)) if x_i...
This function computes the total loss and gradient for a logistic regression model with fairness constraints. It calculates group-specific fairness adjustments (lambda1, lambda0), computes truncated losses and gradients for protected groups, adds an outlier-aware loss term, and incorporates L2 regularization. The final...
def compute_loss_grad(self, theta,X, Y): p = np.exp(_log_logistic(_dot_intercept(theta,X))) n = X.shape[0] idx11 = self.grp1 # np.logical_and(A == 1, Y == 1) idx01 = self.grp2 # np.logical_and(A == 0, Y == 1) self._lambda1 = fairify(p[idx11], p[idx01]) / n loss1, grad1,...
def get_image_module(self): imageModule = [] imageModule.extend( self.convBlock(3, 32, 5, 2) +\ self.convBlock(32, 32, 3, 1) +\ self.convBlock(32, 64, 3, 2) +\ self.convBlock(64, 64, 3, 1) +\ self.convBlock(64, 128, 3, 2) +\ self.convBlock(128, 128, 3, 1) +\ self.convBlock(128, 256, 3, 1) +\ self.co...
This code initializes a neural network model with multiple modules for image, measurement, and joint sensory processing, along with four action branches (follow lane, left, right, straight). It sets hyperparameters, loads data directories, clears GPU memory, and applies Xavier weight initialization to all modules. The ...
def __init__(self, data_cache_size=100, lamb=0.5, hparams=argparse.Namespace( **{'learning_rate':1,'train_batch_size': 1, 'val_batch_size': 1}), train_data_dir=None, val_data_dir=None): super().__init__() torch.cuda.empty_cache() self.train_data_dir = train_data_dir self.val_data_dir = val_data_dir self.l...
def get_data_point(self, index): """Returns requested data point from cache. if h5 file not in cache, loads it.""" data_point_info = self.get_data_point_info(self.data_info, index) file_idx = data_point_info[1] file_name = data_point_info[2] if file_name not in self.data_cache: self.load_dataset(file_name)...
The code's main task is to retrieve and transform a data point into input features and ground truth actions for a machine learning model. It extracts an image, specific label features (speed, command), and stacks steering, gas, and brake values as the target action. The transformed data is returned as input_data and gt...
def __getitem__(self, index): data_point = self.get_data_point(index) image = self.imageTransform(data_point[0]).type(torch.FloatTensor) label = self.labelTransform(data_point[1]).type(torch.FloatTensor) input_data = [image, label[10], label[24]] # [img, speed, command] gt_action = torch.stack([label[0], labe...
def create_encryption_key() -> dict: """Creates a random substitution key to encrypt the message Returns ------- dict key value pairs where each is a lowercase alpha value """ keys = list(string.ascii_lowercase) values = keys.copy() random.shuffle(values) key = {k: v for k,...
The code's main task is to encrypt a message from a file using a substitution cipher, then decrypt it and compare the original and decrypted keys. It reads "message.txt", cleans the message, encrypts it with a predefined key, decrypts the result, prints the original and decrypted messages, and evaluates how many letter...
def main(): """Encrypts a message loaded from file, then decrypts the message """ filename = "message.txt" key = create_encryption_key() key = {"a":"z", "b":"e", "c":"b", "d":"r", "e":"a", "f":"s", "g":"c", "h":"d", "i":"f", "j":"g", "k":"h", "l":"i", "m":"j", "n":"k", "o"...
def print_solution(solution: [str], max_width = None): """Pretty print the current solution Parameters ---------- solution: [str] list of characters in the solution. Unguessed positions are "_" max_width: int the maximum number of characters to show on each line Returns ---...
This code provides an interactive tool to solve a two-time pad cipher by iteratively testing user-provided "cribs" (plaintext guesses) against encrypted messages. It displays potential matches, lets users select valid results, and updates a partial solution based on whether the crib or decrypted text aligns with the ta...
def interactive_solver(ciphers: [str], target: str): """An interactive solver users run to solve a two time pad Iteratively tries to solve the two time pad. First asks the user for a crib and runs it against the different ciphers. Then asks the user to choose a result which seems like it would be the o...
def _remove_duplicate_cols(self, dataset: DataSet) -> DataSet: title, df = dataset df = df.loc[:, ~df.columns.duplicated()] return DataSet(name=title, dataframe=df) def _rename_columns(self, dataset: DataSet) -> DataSet: title, df = dataset if self._config.column_name_map: ...
The main task of the code is to clean a dataset by removing duplicate columns, renaming columns, assigning custom values, eliminating duplicate rows (tracking the count), converting data types, and reordering columns, returning the cleaned dataset and the number of duplicates removed.
def _clean_dataset(self, ds: DataSet) -> Tuple[DataSet, int]: ds = self._remove_duplicate_cols(ds) ds = self._rename_columns(ds) ds = self._assign_custom_values(ds) ds, dups = self._remove_duplicates(ds) ds = self._convert_dtypes(ds) ds = self._reorder_columns(ds) ...
def repeatedForward(maze, start, end): rows,cols = np.shape(maze) if maze[start[0]][start[1]] == 1: return "Path could not be found" #print("create empty maze") emptyMaze = [[0 for i in range(rows)] for j in range(cols)] # print("size of empty maze " , len(emptyMaze)) # print(emp...
The main task of the code is to compare the performance of three pathfinding algorithms (`repeatedForward`, `repeatedBackward`, and `adaptive`) on multiple mazes. It reads 50 maze configurations from text files, runs each algorithm on each maze, records their execution times, and stores the results in lists for analysi...
def main(): maze3 = [[0,0,0,0,0], [0,0,1,0,0], [0,0,1,1,0], [0,0,1,1,0], [0,0,0,1,0]] start = (0,0) end = (4,4) pathStr = 'E:/Coding/python work/project1/arrs/randGrid/' + str(1) + '.txt' with open(pathStr, 'r') as f: ...
def get_requested_ip_blocks(): ''' Gets ip subnet requested by user ''' ip = click.prompt("first 3 blocks of ipv4 like. 1.1.1") while ip != 'stop' and not validate_ipv4_blocks(ip): ip = click.prompt("Invalid IP. Please enter the first 3 block of the ip like 1.1.1") return ip def get_d...
The main task of the code is to scan a network subnet using a specified interface to detect active devices, retrieve their IP and MAC addresses, and display the results. It first validates the interface, fetches IP blocks, checks for termination signals, scans for devices, handles cases with no devices found, prints de...
def scan_network(interface): ''' Main function used to scan ips anc mac addresses on subnet ''' interface = get_interface(interface) ip = get_requested_ip_blocks() if ip == 'stop': return device_details = get_devices(ip, interface) # No followup or print possible if no devic...
def getUserMissileCoord(app): if app.specialActivated: special = mslC.Special(app.userJet.UserX, app.userJet.UserY, app.userJet.speed) app.userMissiles.append(special) else: linear = mslC.ULinear(app.userJet.UserX, app.userJet.UserY, app.userJet.speed) app.userMissiles.append(lin...
The main task of the code is to manage the game's timer logic, including updating game state, handling enemy jet generation, missile firing, checking for game over conditions, and adjusting difficulty. It tracks elapsed time, spawns enemy jets periodically, moves enemies, fires missiles, checks for user input (e.g., 's...
def gameMode_timerFired(app): if app.userJet.health <= 0: app.gameOver = True return if app.pause: return app.timePassed += app.timerDelay app.difficultyTracker += app.timerDelay if app.difficultyTracker == 15000: app.difficultyTracker = 0 app.enemyJetCapacity...
def parse_if(nodes): # Check that format is correct if nodes[1].get_type() == 'KEYWORD' or nodes[2].get_token() != 'then': print("Invalid Input: If Statement does not follow correct syntax.") sys.exit() else_location = -1 for i in range(3, len(nodes)): if nodes[i].get_token() == ...
This function parses a list of nodes by identifying and processing if statements and while loops. It recursively replaces each if/while block with parsed versions, ensuring proper syntax. If unbalanced, it exits with an error. Finally, it delegates to parse_semicolons for further processing.
def parse_language(nodes): index = 0 flag = 'd' # d = default, i = if statement, w = while loop start_index = -1 while index < len(nodes): if nodes[index].get_token() == 'if': flag = 'i' start_index = index if nodes[index].get_token() == 'while': star...
def is_punc(my_string): PUNCTUATION = r"^(\+|\-|\*|/|\(|\)|\:=|\;)$" return re.match(PUNCTUATION, my_string) is not None def is_par(my_string): PARENTHESES = "^(\(|\))$" return re.match(PARENTHESES, my_string) is not None def is_num(my_string): NUMBER = "^[0-9]+$" return re.match(NUMBER, my_stri...
The function `parsify_expression` validates and parses an expression from a list of tokens (`line_nodes`). It checks for invalid symbols (keywords, `:`, `;`), ensures balanced parentheses, verifies that expressions do not start/end with invalid punctuation, and prevents consecutive invalid token types. If errors are de...
def parsify_expression(line_nodes, line): open_count = 0 for token in line_nodes: if token.get_type() == 'KEYWORD' or token.get_token() == ':=' or token.get_token() == ';': print("Invalid Input - Expression has unexpected symbols on line " + str(line + 1) + ".") sys.exit() ...
def initialize_NN(self, layers): weights = [] biases = [] num_layers = len(layers) for l in range(0,num_layers-1): W = self.xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) ...
This code initializes a neural network model for solving a physics-informed problem, setting up placeholders for input data, defining neural networks for variables w, u, v, computing predictions at initial/boundary points, and formulating a loss function combining data fidelity and governing equations. It configures op...
def __init__(self, xd, td, wd, N, layers, lb, ub): self.xd = xd self.td = td self.wd = wd self.N = N self.lb = lb self.ub = ub # Initialize NNs self.layers = layers self.weights, self.biases = self.initialize_NN(layers) s...
def rand_points(self, n_0, n_b): x0 = np.random.uniform(lb[0], ub[0], [n_0, 1]); t0 = np.zeros([n_0, 1]) w0 = self.exact_w(x0, 0); w_t0 = self.exact_w_t(x0, 0) x_lb = self.lb[0] * np.ones([n_b, 1]); t_lb = np.random.uniform(lb[1], ub[1], [n_b, 1]) x_ub = self.ub[0] * np.ones([n_b, 1]); ...
The code trains a model using Adam optimization for `nIter` iterations, generating random points each time and logging loss and time every 10 steps. After training, it performs a final L-BFGS optimization on grid points to refine the model.
def train(self, nIter): start_time = time.time() for it in range(nIter): inp = self.rand_points(self.N[0], self.N[1]) loss_value = self.adam_train_step(inp) if it % 10 == 0: elapsed = time.time() - start_time print('It: %d, Loss: %.3e...
def initialize_NN(self, layers): weights = [] biases = [] num_layers = len(layers) for l in range(0,num_layers-1): W = self.xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) ...
This code initializes a neural network model for solving partial differential equations (PDEs) using physics-informed neural networks (PINNs). It sets up placeholders for input data, boundary conditions, and collocation points, defines the neural network architecture, and prepares loss functions to enforce governing eq...
def __init__(self, xd, td, wd, tb, X_f, layers, lb, ub): """ x0, u0, v0: points for initial condition and corresponding values tb: time points for boundary condition X_f: collocation points that have to satisfy the governing equation layers: structure of MLP lb: lower bou...
def get_talks(): return _get_file("sessions") def get_speakers(): return _get_file("speakers") def write_talks(talk_entries): talks = "\n<br><br>\n".join(talk_entries) talk_content = f"{TALKS_HEADER}\n\n{talks}" TALK_FILE.write_text(talk_content) def build_talk_entries(talks, speakers): talk_ent...
The main task of the code is to compile talk and speaker data into structured entries and schedule rows, then write them to output files. It retrieves talks and speakers, builds formatted entries and schedule rows using helper functions, and saves the results, likely generating content for a conference agenda or docume...
def write_pages(): talks = get_talks() speakers = get_speakers() write_talks(build_talk_entries(talks, speakers)) write_schedule(build_schedule_rows(talks, speakers))
def fix_string(x): out = x.str.lower() out = out.str.replace("\[[^\]]*\]", "", regex=True) out = out.str.replace("†", "", regex=True) out = out.str.replace("\(more\)", "", regex=True) out = out.str.strip() return out def get_county(value_name="cases"): """Get cases or deaths county data from...
The main task of the code is to aggregate and merge COVID-19 data (cases, deaths, tests, hospitalizations, vaccinations, population) from counties, states, and countries into a unified DataFrame. It standardizes geographic identifiers, combines datasets via joins, adds metadata (e.g., "type" column), and calculates sta...
def get_data(n=7): """Get covid data for countries, states, and counties""" state_postal = pd.read_csv(IN_STATE_POSTAL) state_postal["state_code"] = fix_string(state_postal["state_code"]) county_cases = get_county(value_name="cases") county_deaths = get_county(value_name="deaths") by = ["code",...
def find_path(path: str) -> str: if path.endswith('/'): path = path[:-1] if path == '' or path == '/users': # all users data = dumps(get_users()) elif '/users/' in path: # specific user try: user_id = path.split('/')[2] data = dumps(get_user_by_id(user_id)...
This function processes HTTP requests by determining the request method, handling GET, POST, PUT, and DELETE operations, and returning an appropriate HTTP status code along with response data encoded in UTF-8. It uses the WSGI environment to extract request details, processes data via corresponding functions, and manag...
def choosing_method(environ: dict) -> (str, bytes): status_code = '200' method = environ['REQUEST_METHOD'] request_data = FieldStorage( fp=environ['wsgi.input'], environ=environ, ) data = find_path('/users') if method == 'GET': path: str = environ.get('PATH_INFO') ...
def get_org_ids(self, domains: [str]) -> {str: str}: """ Get a dictionary of {domain: organization id} from apollo given a list of domains. :param domains: List of domains in format 'domain.tld' :type domains: list :returns: dictionary of {domain: organization id,}, containing ...
The function `get_people_filtered` retrieves a list of people currently working at an organization (identified by domains) holding specific job titles. It filters results by matching domains to organization IDs, then narrows down people by titles, ensuring they are associated with the correct organization. The output i...
def get_people_filtered(self, domains: [str], titles: [str] = None): """ Get a list of people currently working at an org as one of titles. Pass in multiple domains if org is known by more than one :param domains: domains of org in format list of 'domain.tld' :type domains: lis...
def success_formatter(resp, status_code=200): print("Success response : {}".format(str(resp))) responseObj = {} responseObj['StatusCode'] = 200 responseObj['headers'] = {'Content-Type': 'application/json'} responseObj['body'] = json.dumps(resp) return responseObj def delete_all_records(table_nam...
This Lambda function handles HTTP requests to perform various DynamoDB operations based on the method and input parameters. It processes POST requests for inserting records, batch writes, deleting all records, or forcing payments, and GET requests for balance queries. The function routes requests to appropriate backend...
def lambda_handler(event, context): method = event['requestContext']['http']['method'] body = json.loads(event.get('body', '{}')) query = event.get('queryStringParameters', dict()) resp = success_formatter('No functions be triggered in the backend , please provide the valid inputs') if method == ...
def map_search(query, driver): print(f">>> Searching Google Maps for {query}...") query_encoded = "+".join(query.split()) driver.get(f"https://www.google.com/maps/search/{query_encoded}") search_button = WebDriverWait(driver, 15).until( EC.element_to_be_clickable((By.XPATH, '//button[@id="searc...
The main task of the code is to scrape data from Google Maps by automating a Chrome browser session. It searches for a query, extracts API URLs from the page, parses the APIs to retrieve structured data, and ensures proper cleanup of the browser instance. The function automates interaction with Google Maps to gather in...
def scrape_googlemaps(query): driver = webdriver.Chrome(service=service, options=options) map_search(query, driver) api_urls = get_api_urls(driver) parse_apis(api_urls, query) try: driver.quit() except: pass
def config_logging(): ch = logging.StreamHandler() ch.setFormatter(TimeFormatter("%(asctime)s %(threadName)s | %(message)s")) logging.root = logging.getLogger('build') logging.root.setLevel(logging.INFO) logging.root.addHandler(ch) currentThread().setName('inf') def install_deps(): # It is p...
The main task of the code is to configure and execute the build process for an Android emulator CMake project, handling platform-specific CPU constraints, parsing command-line arguments for build configurations (e.g., output directory, build ID, test concurrency), and launching build scripts with options for QtWebEngin...
def main(argv): config_logging() # We don't want to be too aggressive with concurrency. test_cpu_count = int(multiprocessing.cpu_count() / 4) # The build bots tend to be overloaded, so we want to restrict # cpu usage to prevent strange timeout issues we have seen in the past. # We can incremen...
def change_page(self, mode, flag:int): # +1:up page -1:down page now = Unlocker(mode) if now.page + flag < 1 or now.page + flag > now.max_page: return mode else: if now.book_num != -1: mode = now.cur_type+"-"+str(now.book_num)+"-"+str(now.page+flag) ...
This function handles user interactions for editing a book's content in a pygame application. It processes mouse clicks on navigation buttons (menu, reader, writer, page controls) and keyboard inputs (backspace, enter, tab) to edit text, manage pages, and update the display. Changes are saved to the file, and the scene...
def edit_book(self,event,mode): if event.type != MOUSEBUTTONDOWN and event.type != KEYDOWN: return mode now = Unlocker(mode) name = now.name text = story(name) self.pre_mode = mode pos = pygame.mouse.get_pos() if self.menu_rect.collidepoint(pos) and ev...
def clear_board(self): max_x = self.size[0] max_y = self.size[1] d = self.dist d2 = self.dist_down background = pygame.Surface(self.screen.get_size()).convert() select_label = pygame.image.load("./icon/index1.png").convert() select_label = pygame.transform.scale(s...
This function processes mouse events for UI navigation and interaction in a game/application. It handles mode transitions, updates the lobby scene with story lists, checks for button clicks (reader, menu, page navigation, add book), and returns status codes or actions based on user input and current mode.
def to_write(self,event,mode): now = Unlocker(mode) if mode == self.pre_mode: cou = self.pre_cou else: if now.in_lobby == True: self.clear_board() self.scene(1,"Index",change_p=True,add_book=True) cou = self.print_list(page ...
def clear_board(self): max_x = self.size[0] max_y = self.size[1] d = self.dist d2 = self.dist_down background = pygame.Surface(self.screen.get_size()).convert() select_label = pygame.image.load("./icon/index1.png").convert() select_label = pygame.transform.scale(s...
This function handles mouse click events for reading content in a UI, managing page navigation, story listing, and button interactions. It updates the display based on the mode, processes clicks on list items to return specific read actions, and triggers navigation or menu actions depending on which UI element is click...
def to_read(self,event,mode): now = Unlocker(mode) if mode == self.pre_mode: cou = self.pre_cou name = self.pre_name else: if now.in_lobby == True: self.clear_board() self.scene(0,"Index",change_p=True) cou = sel...
def clear_board(self): self.screen.fill((255,255,255)) pygame.draw.rect(self.screen, (90,0,0), [0,0,200,200], 2) pygame.display.update() def p_text(self, text): k = 0 idx = 0 f = open("story.txt","w+") for i in text: tp_text = "" ...
This code handles mouse click events to determine if the cursor is within a defined rectangular area. It updates the 'in_box' state based on mouse position and button presses, triggering actions like clearing a board and displaying text when conditions are met, primarily for interactive GUI elements like input boxes or...
def start(self, event): pos = pygame.mouse.get_pos() global initii #print(initii) if(initii): if (self.x[0] <= pos[0] and pos[0] <= self.x[1] and self.y[0] <= pos[1] and pos[1] <= self.y[1]): if(event.type == MOUSEBUTTONDOWN): ...
def keyExpansion(key): RCon = ["01", "02", "04", "08", "10", "20", "40", "80", "1B", "36"] words = [] for i in range(0, len(key), 4): wi = "" for x in key[i : i + 4]: wi += x words.append(wi) for i in range(4, 44): if i % 4 != 0: wi = "%X" % (int(...
This code implements the AES encryption algorithm by performing 10 rounds of transformations on the input state. It applies SubBytes, ShiftRows, MixColumns, and AddRoundKey in the first 9 rounds, omitting MixColumns in the final round. The keyExpansion function generates round keys, which are used in AddRoundKey operat...
def cipher(state, Key): global KEY Key = KEY roundkeys = keyExpansion(Key) round = 0 newState = AddRoundKey(state, roundkeys[round * 4 : round * 4 + 4]) # first 9 rounds have 4 transformations for round in range(1, 10): newState = state_subBytes(newState) newState = shiftR...
def keyExpansion(key): RCon = ["01", "02", "04", "08", "10", "20", "40", "80", "1B", "36"] words = [] for i in range(0, len(key), 4): wi = "" for x in key[i : i + 4]: wi += x words.append(wi) for i in range(4, 44): if i % 4 != 0: wi = "%X" % (int(...
This function performs AES decryption by applying inverse transformations in reverse order of encryption rounds. It uses the provided key to generate round keys via keyExpansion, then applies inverse operations (shiftRowsInv, state_subBytesInv, invmixColumns) and AddRoundKey for each of 10 rounds, starting from the las...
def decipher(state, Key): global KEY Key = KEY roundkeys = keyExpansion(Key) round = 10 newState = AddRoundKey(state, roundkeys[round * 4 : round * 4 + 4]) for round in range(9, -1, -1): newState = shiftRowsInv(newState) newState = state_subBytesInv(newState) newState = A...
def block_to_state(block): state = [[0 for _ in range(4)] for _ in range(4)] for i in range(4): for j in range(4): state[i][j] = block[i + (4 * j)] return state def cipher(state, Key): global KEY Key = KEY roundkeys = keyExpansion(Key) round = 0 newState = AddRoundK...
This code encrypts input text using a block cipher with AES-like processing. It pads the input to a multiple of 16 bytes by adding a 0xFF byte followed by spaces. Each 16-byte block is converted to a hexadecimal state matrix, encrypted using a cipher function with a predefined key, then reassembled into the output stri...
def encrypt(pt): if chr(255) in pt: raise ValueError("Unsupported character") totalPadding = 16 - len(pt) % 16 if totalPadding !=0: pt += chr(255) for i in range(totalPadding-1): pt += " " test = "" for i in range(0, len(pt), 16): curr_pt = pt[i : i + 16] ...
def block_to_state(block): state = [[0 for _ in range(4)] for _ in range(4)] for i in range(4): for j in range(4): state[i][j] = block[i + (4 * j)] return state def decipher(state, Key): global KEY Key = KEY roundkeys = keyExpansion(Key) round = 10 newState = AddRound...
This code decrypts input data by processing it in 32-character blocks, splitting each block into 2-character pairs, converting them to a state, decrypting using a key via the `decipher` function, converting back to characters, and trimming the result at the ASCII 255 character. The main task is to decrypt hexadecimal-e...
def decrypt(test): testc = "" for i in range(0, len(test), 32): curr_pt = test[i : i + 32] curr_pt = [curr_pt[i : i + 2] for i in range(0, len(curr_pt), 2)] state = block_to_state(curr_pt) cstate = decipher(state, KEY) cstate = state_to_block(cstate) chk = [chr...
def verify_file(pathname): """ Verify that the supplied pathname is an executable regular file. """ if os.path.isdir(pathname) or os.path.islink(pathname): return False for ext in '', '.ksh', '.sh': script_path = pathname + ext if os.path.isfile(script_path) and os.access(sc...
The code verifies the pre/post scripts and user credentials for a test. It checks each file and user against validation functions; if any fail, it logs an error and skips the test by returning False. If all pass, it returns True, allowing the test to proceed.
def verify(self): """ Check the pre/post scripts, user and Test. Omit the Test from this run if there are any problems. """ files = [self.pre, self.pathname, self.post] users = [self.pre_user, self.user, self.post_user] for f in [f for f in files if len(f)]: ...
def write_log(msg, target): """ Write the provided message to standard out, standard error or the logfile. If specifying LOG_FILE, then `msg` must be a bytes like object. This way we can still handle output from tests that may be in unexpected encodings. """ if target == LOG_OUT: os....
The `verify` method checks the validity of a TestGroup's pre/post scripts, users, and tests. It converts relative script paths to absolute, verifies file/user existence, and logs warnings if discrepancies or invalid entries are found. Invalid tests are removed, and the method returns `False` if no valid tests remain, e...
def verify(self): """ Check the pre/post scripts, user and tests in this TestGroup. Omit the TestGroup entirely, or simply delete the relevant tests in the group, if that's all that's required. """ # If the pre or post scripts are relative pathnames, convert to # ...
def init(): global sint global count global hdr global xhdr global opfile global sep global out global l2exist desired_cols = None xflag = False hflag = False vflag = False i = 1 try: opts, args = getopt.getopt( sys.argv[1:], "xo:...
The main task of the code is to run an infinite loop that periodically updates and displays system statistics (via snap_stats(), calculate(), print_values()), handles SIGINT and SIGWINCH signals, and terminates after a specified count of iterations. It initializes resources, manages output closure, and refreshes a head...
def main(): global sint global count global hdr_intr i = 0 count_flag = 0 init() if count > 0: count_flag = 1 signal(SIGINT, SIG_DFL) signal(SIGWINCH, resize_handler) while True: if i == 0: print_header() snap_stats() calculate() ...
def usage(): sys.stderr.write("%s\n" % cmd) sys.stderr.write("\t -b : Print table of information for each dbuf\n") sys.stderr.write("\t -d : Print table of information for each dnode\n") sys.stderr.write("\t -h : Print this help message\n") sys.stderr.write("\t -r : Print raw values\n") sys.stde...
The main task of the code is to parse command-line arguments to configure data processing modes (buffers, dnodes, types), validate input/output files, and redirect input/output streams before executing corresponding data processing functions based on selected flags. It handles column compatibility checks, mutual exclus...
def main(): global hdr global sep global raw desired_cols = None bflag = False dflag = False hflag = False ifile = None ofile = None tflag = False vflag = False xflag = False try: opts, args = getopt.getopt( sys.argv[1:], "bdf:hi:o:rs...
def df(query): return pd.DataFrame(list(query.dicts())) def get_all_ranks(self, cur_week): for week in range(1, cur_week + 1): self.get_rank(week) def get_all_scores(self, cur_week): for week in range(1, cur_week + 1): self.get_scores(week)
The code initializes a class to process user rankings and scores for a specific week. It loads user data from a DataFrame, renames columns, sets the user index, and initializes dictionaries for ranks, scores, and simulated ranks. The `get_all_ranks` and `get_all_scores` methods are called to populate these structures w...
def __init__(self, cur_week): self.cur_week = cur_week self.users = df(Users.select()).rename( columns={'roster_id': 'user'}).set_index('user') self.rank = {} self.scores = {} self.sim_rank = {} self.get_all_ranks(cur_week) self.get_all_scores(cur_w...
def get_likelihood_log_prob_fn(self, y_weights): def likelihood_log_prob(Ws, bs): likelihood = self.model(Ws, bs) log_prob = tf.reduce_sum(y_weights*likelihood.log_prob(self.y)) # log_prob = tf.reduce_sum(likelihood.log_prob(self.y)) return log_prob return...
This function computes a weighted target log probability function for a model, incorporating class weights to address imbalanced data. It calculates weights based on positive/negative sample counts, constructs a weighted y array, combines likelihood and prior log probability functions, and returns a lambda that evaluat...
def get_target_log_prob_fn(self): # Class weights pos = np.sum(self.y) neg = len(self.y) - pos total = pos + neg weight0 = (1 / neg)*(total)/2.0 weight1 = (1 / pos)*(total)/2.0 y_weights = [weight0 if val==0 else weight1 for val in self.y] y_weights = tf...
def train(model, train_loader, batch_size, opt): """Train model on the training dataset for one epoch""" batchLoss = 0 epochLoss = 0 for batch, (image, command, traffLD, traffLS, laneDist, routeAngle) in enumerate(train_loader): #print(f"Batch {batch+1}\n-------------------------------") ...
The main task of the code is to train an affordance prediction model on an expert dataset using a pre-defined neural network architecture. It loads training and validation data, applies image transformations, trains the model with Adam optimizer over 7 epochs, validates performance, records training/validation losses, ...
def main(): # Change these paths to the correct paths in your downloaded expert dataset train_root = 'expert_data/train' val_root = 'expert_data/val' model = AffordancePredictor().cuda() model.train() transform = transforms.Compose([ transforms.Resize(256), ...
def compact_page(self): """ Reclaim unused space so that records are contiguous and limit fragmentation. Eager -> compact page when a record is deleted (we do this) Lazy -> compact page when page is full """ write_ptr = 0 for i, (offset, length) in sorted(enumer...
This function updates a record in a page by either overwriting it if the size matches, compacting the page to avoid fragmentation if the new record is smaller, or deleting the old record and inserting the new one if it's larger. It adjusts the page's data and slot directory entries accordingly, ensuring efficient stora...
def update_record(self, slot_id, new_record): offset, length = self.page_footer.slot_dir[slot_id] # If new record size is equal, just overwrite if len(new_record) == length: self.data[offset:offset + length] = new_record return True # If new record is smaller, we ...