dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def extract_summary(s): global case_id if case_id == "2019CM002802": xxx = 1 # can set breakpoint here print("in summary",s.prettify()) output = {} cases_soup = None for link in s.find_all('dl'): # get all the dt dd pairs and stuff in dictionary #print("in summary",link.p...
The code extracts structured data from HTML sections using BeautifulSoup. It identifies sections by ID (e.g., "summary", "charges"), calls specific helper functions to parse content, and stores results in a dictionary. Key data points like case numbers, charges, defendants, and court records are extracted. Unhandled se...
def extract_data(soup): # partition the HTMTL into sections and extract data from each section global case_id case_id = "" data = {} case_id_bs = soup.find("div", id="case-header-info").find("span", class_="caseNo") case_id = case_id_bs.get_text(strip = True) data["case_number"] = case_id ...
def parse_arguments_fix(): global args parser = argparse.ArgumentParser(description='Parse the ccap records') parser.add_argument('-i', '--infile', dest='infile', default="Metcalf/State of Wisconsin vs. Wilbert Gordy.mht", # required=True, ...
The code processes HTML/MHTML files to extract defendant data (race, gender, address), charges, and court records, then exports them into structured CSV files. It handles directories or single files, formats extracted data with predefined headers, and generates time-stamped output files. The main tasks include parsing ...
def main(): global case_id starttime = datetime.datetime.today() output_race_gender = [] r_s_header = ["Name_Number", "Defendant name", "Date of birth", "DOC_ID", "Race", "Sex", "Case Number", "Filing date"] r_s_a_header = r_s_header+ ["Address", "Cross references"] #output_race_gender.append(r_...
def normal(): return random.normalvariate(0,1) def cauchy(): """ Generate a Cauchy random variable with center 0 and the same interquartile range as a standard normal curve. Use this rather than a normal curve to get fatter tails and more spice. https://math.stackexchange.com/questions/484395/how-to-generate-...
The function `bell_curve` returns a bell curve distribution based on the input parameter `dist`. If `dist` is 'normal', it returns a normal distribution; if 'cauchy', it returns a Cauchy distribution. It raises an error for invalid `dist` values. The choice of distribution affects the output's statistical properties (e...
def bell_curve(dist): # See notes about how choice of dist affects A. if dist=='normal': return normal() if dist=='cauchy': return cauchy() die("illegal value of dist in bell_curve")
def n_predictit_bins(): return 16 def predictit_bin_to_margin_range(b): r = raw_predictit_bin_to_margin_range(b) if r[0]==0: return(1,r[1]) return r def f2(x): if x is None: return "-----" else: return ("%5.2f") % x
The main task of the code is to write a histogram of electoral college margin probabilities to a file. It calculates the probability for each bin by dividing the histogram count by the total number of trials, then formats and writes the margin range and corresponding probability for each bin. The output includes a head...
def write_electoral_college_histogram(filename,electoral_college_histogram,n_trials): with open(filename,'w') as f: print("probabilities of electoral college margins:",file=f) for b in range(n_predictit_bins()): r = predictit_bin_to_margin_range(b) print(" ",r[0],"to",r[1],", ",f2(electoral_colle...
def bell_curve(dist): # See notes about how choice of dist affects A. if dist=='normal': return normal() if dist=='cauchy': return cauchy() die("illegal value of dist in bell_curve") def bell_to_200_percent_range(x): """ Input x is a random variable meant to represent a margin of victory in an elect...
This function simulates a single trial of an election outcome by calculating state-level vote margins using a bell curve distribution, aggregating electoral votes for Democratic (D) wins, determining if D achieves a majority or tie, and returning results including per-state win status, total D electoral votes, and a pr...
def do_one_trial(dat): (safe_d,safe_r,aa,k,s,dist,tot,c,ind,electoral_votes,lean,tie) = (dat['safe_d'],dat['safe_r'], dat['aa'],dat['k'],dat['s'],dat['dist'],dat['tot'],dat['c'], dat['ind'],dat['electoral_votes'],dat['lean'],dat['tie']) d = safe_d pop = aa*bell_curve(dist) x = {} t...
def get_defaults_from_file(file): pars = {} with open(file, newline='') as par_file: for line in par_file: if re.search(r"[^\s]",line): pars = get_one_par(pars,line,f"reading defaults from file {file}") return pars def parameter_names(): return list(parameter_types().keys()) def set_is_empty(s...
The function `parameters` loads adjustable parameters from a file, validates their presence, sets default correlation values (`rho1`, `rho2`, `rho3`) for state interactions, and allows command-line overrides. It ensures required parameters are present, updates the dictionary with correlation settings, and applies comma...
def parameters(filename): ''' Set adjustable parameters. The main parameters that it makes sense to fiddle with are A, k, s, and dist. See README for how to decide on these values. The defaults can be overridden from the command line, e.g., election.py a=10. ''' pars = get_defaults_from_file(filename) m...
def parameters(filename): ''' Set adjustable parameters. The main parameters that it makes sense to fiddle with are A, k, s, and dist. See README for how to decide on these values. The defaults can be overridden from the command line, e.g., election.py a=10. ''' pars = get_defaults_from_file(filename) m...
The code simulates election outcomes using calibrated parameters and state data, calculating probabilities of Democratic wins, state-level results, and joint events across multiple trials. It outputs win probabilities, conditional probabilities, and electoral college histograms to analyze election scenarios based on gi...
def main(): pars = parameters('defaults.txt') (a,k,s,dist,rho,n_trials,joint,tie) = (pars['a'],pars['k'],pars['s'],pars['dist'],pars['rho'],pars['n_trials'],pars['joint'],pars['tie']) (rho1,rho2,rho3) = rho sd = state_data('data.csv','polls.csv') (electoral_votes,lean,predictit_prob,poll,undecided,safe_d,sa...
def set_appropriate_class(self, process_id): class_types_for_process = { "reduce_dimension": ReduceDimensionNode, "add_dimension": AddDimensionNode, "load_collection": LoadCollectionNode, "save_result": SaveResultNode, "merge_cubes": MergeCubesNode, ...
This code initializes a node object with attributes like node_id, process_id, arguments, and relationships (dependencies/dependents). It validates the process definition exists, prepares arguments, generates a unique function name, and sets child nodes. The class dynamically assigns itself based on the process type and...
def __init__( self, node_id, process_id, arguments, child_nodes, dependencies, dependents, level, process_definitions_directory="javascript_processes", ): self.set_appropriate_class(process_id) self.variable_wrapper_string = uui...
def name_enter(self): if pyxel.btnp(pyxel.KEY_A): self.player_name += "A" if pyxel.btnp(pyxel.KEY_B): self.player_name += "B" if pyxel.btnp(pyxel.KEY_C): self.player_name += "C" if pyxel.btnp(pyxel.KEY_D): self.player_name += "D" if...
The code's main task is to manage game state transitions by checking conditions and executing corresponding methods: entering a name, displaying a menu, showing the leaderboard, handling game over, or running game logic based on state flags like name_entered, menu_pass, show_leader_board, and game_over.
def update(self): if not self.name_entered: self.name_enter() elif not self.menu_pass: self.menu() elif self.show_leader_board: self.leader_board() elif self.game_over: self.game_over_logic() else: self.game_logic()
def create_solved(self): """Create a valid solved 9x9 Sudoku puzzle. Returns: str: The solved puzzle is an 81-character string. Blank cells are represented by a '.' by default. The first 9 characters is the first row of the puzzle, the next 9 characters is the second...
The main task of the code is to generate a valid 9x9 Sudoku puzzle with a specified number of givens by iteratively attempting to remove numbers from a solved puzzle. It tries multiple solved puzzles (up to `repeat` times) and makes up to `attempts` modifications per puzzle to achieve the desired number of givens. If s...
def create_puzzle(self, num_givens, repeat=1, attempts=20, v=False): """Create a valid 9x9 Sudoku puzzle. Args: num_givens: The desired number of givens in a puzzle. repeat: (Optional) The number of different solved puzzles to use to try to create...
def error(code, line, object = ''): global errorCount errorCount += 1 if object != '': print("ERROR: " + errors[code] + " -> '" + object + "'") else: print("ERROR: " + errors[code]) print(f"--> {line+1}: " + ' '.join(srcCode[line])) return def parse_typeA(line, lineNumber): i...
The code assembles machine code from assembly-like instructions by processing variables, labels, and opcodes. It validates instruction formats, assigns binary addresses to variables and labels, ensures proper structure (e.g., ending with 'hlt'), and converts valid instructions into binary using parsing functions. Error...
def assemble(): if list(instructions.keys())[-1] > 255: error(11, list(instructions.keys())[-1]) # Variable Handling variableLineNumbers = list() for i, line in instructions.items(): if line[0] == 'var': if len(line) == 2: programVariables[line[1]] = 'null' ...
def get_next_unique_max(self): m = self.BOUNDARY while m >= -self.BOUNDARY: for col in self.data: if m in self.data[col]: m = self.next_after(m, -1) break else: return m return m def next_after(self, ...
This function determines the next move strategy by selecting maximum and minimum values in specific columns based on the game turn. For turns ≤9, it sets a boundary value to exclude certain moves. At turn 10, it calculates the next unique maximum value, applies enemy conditions, and sets subsequent moves. It updates pl...
def max_strategy(self): """ Need to take both max and min in the column :return: """ ret_d = dict() if self.turn_num <= 9: ret_d[self.v_col] = self.BOUNDARY # to rule out SumNeg elif self.turn_num == 10: next_unique_max = self.get_next_u...
def get_next_unique_min(self): m = -self.BOUNDARY while m <= self.BOUNDARY: for col in self.data: if m in self.data[col]: m = self.next_after(m, 1) break else: return m return m def next_after(self, n...
The function determines a minimum strategy by setting specific values in a dictionary based on the turn number. For turns ≤9, it excludes 'SumNeg' by assigning a low value. At turn 10, it calculates and assigns minimum values for enemy conditions and future moves. It updates game data with these values and returns the ...
def min_strategy(self): """ Need to take both max and min in the column :return: """ ret_d = dict() if self.turn_num <= 9: ret_d[self.v_col] = -self.BOUNDARY # to rule out SumNeg elif self.turn_num == 10: next_unique_min = self.get_next_...
def get_next_unique_max(self): m = self.BOUNDARY while m >= -self.BOUNDARY: for col in self.data: if m in self.data[col]: m = self.next_after(m, -1) break else: return m return m def get_next_unique_m...
The function `zero_m_strategy` calculates an adjusted value for a specific column (`v_col`) based on its current sum, applying epsilon offsets to avoid zero or negative values. On the 10th turn, it predicts the enemy's move using statistical mode or extremum conditions, then clamps the result within a boundary range. T...
def zero_m_strategy(self): # choose two other disguise col if not set ret_d = dict() current_sum = np.sum(self.data[self.v_col]) if current_sum <= abs(0.000001 * len(self.data[self.v_col])): ret_d[self.v_col] = 0.0000001 elif current_sum < 0: ret_d[self.v_...
def next_after(self, num, direction): """Utility function Get the next floating number with the precision of self.EPSILON :param num: the base number to increment/decrement :param direction: +1/-1 as the direction to move :return: the next floating number towards direction dir ...
This function determines a strategy to achieve a "Max" victory by setting the value in the victory column to approach an upper boundary, adjusting it in the final round to ensure dominance. It also assigns secondary values to other columns to counter opponents, using the counter_enemy_mix method, and records all played...
def max_strategy(self): """This function is called when our victory condition is Max. It first enters the value to meet our own victory condition. Then it passes the ret_d to the counter_enemy_mix function to put in values to defeat others. :return: a dictionary with same keys as data, ...
def next_after(self, num, direction): """Utility function Get the next floating number with the precision of self.EPSILON :param num: the base number to increment/decrement :param direction: +1/-1 as the direction to move :return: the next floating number towards direction dir ...
This function sets the victory column's value to meet the Min victory condition by adjusting values based on the turn number, then assigns additional minimum values to other columns in round 10 to secure the win. It also calls a counter function to fill remaining columns strategically against opponents, recording all m...
def min_strategy(self): """This function is called when our victory condition is Min. It first enters the value to meet our own victory condition. Then it passes the ret_d to the counter_enemy_mix function to put in values to defeat others. :return: a dictionary with same keys as data, ...
def get_next_unique_max(self): """Utility function From the boundary to check each number. If it is not yet added in the matrix, return the value :return: the maximum value possible that hasn't been put into the game matrix. """ m = self.BOUNDARY while m > -self....
This function determines optimal values for the game matrix under the "ZeroM" victory condition. It adjusts the victory column's value based on the current sum, ensuring it meets the win condition by setting specific values with epsilon and boundary checks. In the 10th turn, it predicts the opponent's move (using mode ...
def zero_m_strategy(self): """This function is called when our victory condition is ZeroM. It first enters the value to meet our own victory condition. Then it passes the ret_d to the counter_enemy_mix function to put in values to defeat others. :return: a dictionary with same keys as d...
def maximum(self): '''our strategy for max and min is similar, we confuse our opponent by putting all kinds of numbers that satisfy other victory conditions in the non-victory columns so that it's hard for him to guess what's our column name and what our victory conditon is''' if 0 <= s...
The main task of the code is to process input data by calculating statistical features (e.g., max, min, linear/quadratic trends, sum of negatives/positives), select a specific feature based on the `victory_con` condition, modify a value in a list at the `victory_col` index, and return a dictionary with all keys from th...
def take_turn(self, data, victory): self.data = data self.victory_con = victory[0] self.victory_col = victory[1] self.data_keys = sorted(list(data.keys())) self.data_values = list(data.values()) # self.count = int(len(self.list_all_numbers_before())/5) self.data_...
def check_is_first(self): for col in self.data.keys(): if self.data[col][1::2] != self.played_data[col]: return False return True def check_enemy_col(self): """ :return: """ if self.turn_num <= 3: return if self.turn_num ==...
The code's main task is to determine a player's optimal move in a game by selecting a strategy based on the given victory condition. It updates the player's data, turn number, and checks move order/opponent clues. Depending on the victory type (e.g., Max, Min, Linear), it executes a corresponding strategy to generate a...
def take_turn(self, data, victory): """Must return a dictionary with the same keys as data, and with single float values in the range [-1023, 1023]. data is a dictionary with column names as keys and a list of floats as the column values of the game so far. victory the condition ...
def check_is_first(self): """This function checks if this player is served as player1 or player2. It is used to check which values are from the opponent. :return: True if the player's value is entered before the opponent in the matrix, False otherwise. """ for col in self.data: ...
The function `take_turn` generates 5 values for the game matrix based on the current state (`data`) and victory condition (`victory`). It updates internal game state, determines the player's turn order, analyzes opponent clues, and selects a strategy (e.g., `max_strategy`, `min_strategy`) aligned with the victory condi...
def take_turn(self, data, victory): """This function is called by the server each turn to give 5 numbers to append to the game matrix. :param data: given by the server. current state of the game matrix. :param victory: (victory_condition, victory_column) tuple given by the server :retur...
def fetch_source_ips_from_email(): source_ips = set() # Using a set to store unique IPs # Connect to the IMAP server imap = imaplib.IMAP4_SSL(IMAP_SERVER) imap.login(IMAP_USERNAME, IMAP_PASSWORD) # Try both "Junk" and "Spam" folder names folder_names = ["Junk", "Spam"] selected_folder = N...
The main task of the code is to extract non-whitelisted source IP addresses from email messages, save them to a text file, add them to a blacklist, remove duplicate entries, and reapply one instance of each removed IP to maintain blacklist integrity.
def main(): # Fetch source IPs from email messages source_ips = fetch_source_ips_from_email() # Save non-whitelisted unique source IPs to a text file with open('source_ips.txt', 'w') as file: for ip in source_ips: file.write(ip + '\n') print("Oldest non-whitelisted unique sourc...
def __view_update(self,mode="human"): if not self.__game_over: # update the robot's position self.__draw_entrance() self.__draw_robot() # self.get_order() # update the screen self.screen.blit(self.background,(0,0)) self.screen....
This method updates the game's view and controller. If an error occurs during the update, it terminates the game and raises the exception. On success, it returns the image output from the view update.
def update(self,mode="human"): try: img_output = self.__view_update(mode) self.__controller_update() except Exception as e: self.__game_over = True self.quit_game() raise e else: return img_output
def __DH(self, dh_pair, dh_pub): """Perform DH key exchange.""" rootKey = dh_pair[0].exchange(ec.ECDH(), dh_pub) sharedKey = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=DH_NONCE, ).derive(rootKey) return sharedKey d...
This code receives and decrypts an end-to-end encrypted message. It establishes a shared key via Diffie-Hellman if the connection is new, then uses a ratchet decryption mechanism to process the ciphertext. The function returns the decrypted plaintext or None if decryption fails.
def __receiveMessage(self, name, header, ciphertext): """End-2-End encrypted messaging receiver.""" if name not in self.__conns: SK = self.__DH((self.__sk,self.__pk), header) self.__startReceiving(name, SK) try: pt = self.__RatchetDecrypt(ciphertext, header, ...
def __DH(self, dh_pair, dh_pub): """Perform DH key exchange.""" rootKey = dh_pair[0].exchange(ec.ECDH(), dh_pub) sharedKey = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=DH_NONCE, ).derive(rootKey) return sharedKey d...
The main task of the code is to securely send end-to-end encrypted messages using Diffie-Hellman key exchange and ratchet encryption. It retrieves the recipient's public key, generates a shared key if the connection is new, encrypts the message, and returns the encrypted result along with the public key for secure tran...
def __sendMessage(self, name, message): """End-2-End encrypted messaging sender.""" publicKey = self.certs[name]["pk"] if name not in self.__conns: SK = self.__DH((self.__sk, self.__pk), publicKey) self.__startSending(name, SK) ct = self.__RatchetENCRYPT(me...
def message_to_screen(msg, color, y_displace=0, size="small"): textSurf, textRect = text_objects(msg, color, size) textRect.center = (int(display_width / 2), int(display_height / 2) + y_displace) gameDisplay.blit(textSurf, textRect) def pause(): paused = True message_to_screen("Paused", black, -100,...
The code defines a game loop for a tank battle game, handling player movement, shooting mechanics, health tracking, and game state management. It processes keyboard inputs for tank control, fire power adjustment, and pausing. The loop updates the game display with tanks, barriers, health bars, and projectile effects. I...
def gameLoop(): gameExit = False gameOver = False FPS = 15 player_health = 66 enemy_health = 33 barrier_width = 50 mainTankX = display_width * 0.9 mainTankY = display_height * 0.9 tankMove = 0 currentTurPos = 0 changeTur = 0 enemyTankX = display_width * 0.1 enemyT...
def build_patch_model( self, fine_tune=True, training=True, use_baseline_weights=True ): ensemble_model = self.build_ensemble(fine_tune=fine_tune) top_model = self.build_top_model() if training: if fine_tune: if use_baseline_weights: t...
The code fine-tunes a neural network for image classification, either using patch-based or whole-image models. It configures an Adam optimizer, compiles the model with binary crossentropy loss, and trains it with specified epochs, batch size, and learning rate. Callbacks include early stopping, learning rate adjustment...
def fine_tune( self, epochs, batch_size, learning_rate, patch_weights="", use_baseline_weights=True, ): if self.classifier_type == "patch": model = self.build_patch_model( fine_tune=True, training=True, use_baseline_weights=use_base...
def unary(self): if self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS) or self.checkToken(TokenType.CONCAT): self.emitter.emit(self.curToken.text) self.nextToken() self.primary() def checkToken(self, kind): return kind == self.curToken.kind def nextToken(...
This code parses and emits multiplication/division operators in an expression. It processes unary expressions first, then repeatedly checks for * or / tokens, emitting them and advancing the tokenizer before parsing the next unary operand, allowing sequential handling of these operations in an expression tree.
def term(self): self.unary() # for * / expressions while self.checkToken(TokenType.ASTERISK) or self.checkToken(TokenType.SLASH): self.emitter.emit(self.curToken.text) self.nextToken() self.unary()
def term(self): self.unary() # for * / expressions while self.checkToken(TokenType.ASTERISK) or self.checkToken(TokenType.SLASH): self.emitter.emit(self.curToken.text) self.nextToken() self.unary() def checkToken(self, kind): return kind == self.curTok...
The main task of the code is to parse and emit expressions involving addition, subtraction, and bracket-opening operators. It processes terms recursively, emitting each operator (+, -, or BRACKOPEN) and parsing subsequent terms to handle chained operations, allowing for the construction of complex expressions in a comp...
def expression(self): self.term() # For + - expressions while self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS) or self.checkToken(TokenType.BRACKOPEN): self.emitter.emit(self.curToken.text) self.nextToken() self.term()
def expression(self): self.term() # For + - expressions while self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS) or self.checkToken(TokenType.BRACKOPEN): self.emitter.emit(self.curToken.text) self.nextToken() self.term() def isComparisonOperat...
The main task of the code is to parse and emit comparison operators in an expression. It starts by parsing an initial expression, then repeatedly checks if the next token is a comparison operator (e.g., >, <, ==). If so, it emits the operator, advances the token, and parses the next expression, effectively handling cha...
def comparison(self): self.expression() while self.isComparisonOperator(): self.emitter.emit(self.curToken.text) self.nextToken() self.expression()
def checkToken(self, kind): return kind == self.curToken.kind def nextToken(self): self.curToken = self.peekToken self.peekToken = self.lexer.getToken() def abort(self, message): txt = "{color}Parse Error\n{message}{end}" sys.exit(txt.format(color="\033[91m", end="\033[0m", messa...
This code parses and emits C# code for procedures/functions, handles control structures (if, while, for), manages symbols, processes expressions, and generates output for statements like return, input, and console output, ensuring syntax validity and symbol uniqueness.
def statement(self): if self.checkToken(TokenType.PROCEDURE): self.nextToken() self.emitter.isMethod = True name = self.curToken.text if name not in self.symbols: self.symbols.add(name) else: self.abort(f"Procedure name ...
def search_applicants(skills_needed, threshold): skills_needed = skills_entry.get().split(",") threshold = float(threshold_entry.get()) matched_skills = [] num_matched_skills = 0 for filename in os.listdir('C:/Users/Administrator/Desktop/ats/resumes'): filepath = os.path.join('resumes', file...
The function `find_candidates` retrieves required skills and a threshold, searches for matching applicants, and displays/results. If matches exist, it saves them to a timestamped CSV file, shows a confirmation, and opens a window to display the matching candidates.
def find_candidates(): skills_needed = skills_entry.get().split(",") threshold = float(threshold_entry.get()) matched_skills, num_matched_skills = search_applicants(skills_needed, threshold) if len(matched_skills) == 0: messagebox.showinfo("No matches found", "There are no candidates matching th...
def initialize(): global sp, player, df, song_queues, model, prev_song df = pd.read_csv("../data/UserTracks.csv", header=0) for index, row in df.iterrows(): tempo = math.floor(row['Tempo']/10) * 10 if tempo not in song_queues: song_queues[tempo] = [] song_queues[tempo]...
The code defines a `run()` function that initializes a program, creates a graphical window, updates its state, and starts the main event loop to keep the window interactive. The `initialize()` and `create_window()` functions likely set up initial configurations and the GUI interface, while `updater()` manages dynamic c...
def run(): initialize() create_window() updater() root.mainloop()
def iterate(): glViewport(0, 0, WIDTH, HEIGHT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, WIDTH, 0.0, HEIGHT, 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def drawLeftArrow(size): drawLine(25, 750, 75, 750, size) drawLine(25, 750, 50, 775, size) drawLine(25, 7...
This function renders the game screen by clearing the display, drawing UI elements (arrow, pause/play, cross), updating game objects (DIMOND, CATCHER), and swapping buffers for real-time rendering. It checks the GAME_PLAY and RUNNING states to control game logic flow and visual feedback.
def showScreen(): global RUNNING, dimond_speed, DIMOND, CATCHER glClearColor(*BACKGROUND_COLOR) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() iterate() glColor3f(*green_rgb) drawLeftArrow(2) if GAME_PLAY: glColor3f(*yellow_rgb) pause(2) # pause ...
def likelihoods2(self, alleles): """ Calculates the likelihood to observe two alleles/haplotypes under MATCHED and UNMATCHED scenarios. """ F = self.joint_frequencies_combo(alleles, normalize=True) a, b, ab = F[1], F[2], F[3] UNMATCHED = a*b MATCHED = (ab+a*b)/2 ...
The function `get_likelihoods` calculates likelihoods for given alleles by selecting an optimized method based on the number of alleles. It routes input to specific methods (`likelihoods2`–`likelihoods5`) for 2–5 alleles, defaulting to a general `likelihoods` function for other cases, ensuring efficient computation tai...
def get_likelihoods(self, alleles): """ Uses the optimal function to calculate the likelihoods. In general, self.likelihoods can get more than five alleles but the dedicated functions are optimized to a certain number of alleles. """ l = len(alleles) if l==2: result ...
def chr_length(chr_id): """ Return the chromosome length for a given chromosome, based on the reference genome hg38.""" #The data of chromosome length was taken from https://www.ncbi.nlm.nih.gov/grc/human/data?asm=GRCh38 length_dict = {'chr1': 248956422, 'chr2': 242193529, 'chr3': 198295559, 'chr4': 1902145...
The code generates an observation table representing chromosomal aneuploidy by combining haploid sequences from input files. It handles scenarios like monosomy/disomy, processes admixture configurations, validates input consistency, constructs observation tables with specified depth and read length, and saves results. ...
def MixHaploids(obs_filenames, read_length, depth, scenarios, **kwargs): """ Given N observation tables of haploid sequences, an observation table that depicts a chromosomal aneuploidy is created. """ time0 = time() seed(a=None, version=2) #I should set a=None after finishing to debug the code. ...
def chr_length(chr_id): """ Return the chromosome length for a given chromosome, based on the reference genome hg38.""" #The data of chromosome length was taken from https://www.ncbi.nlm.nih.gov/grc/human/data?asm=GRCh38 length_dict = {'chr1': 248956422, 'chr2': 242193529, 'chr3': 198295559, 'chr4': 190214...
The main task of the code is to generate a multi-panel figure visualizing log-likelihood ratios (LLRs) of BPH vs. SPH across chromosomal positions for each chromosome. It processes input data, bins LLRs, plots them with error bars, detects crossovers, and adjusts layout. The function returns an export dictionary contai...
def panel_plot(DATA,**kwargs): """ Creates a multi-panel figure. For each numbered chromosome, a figure depicts the log-likelihood ratio vs. chromosomal position for BPH over SPH. """ import matplotlib as mpl export = dict() scale = kwargs.get('scale', 0.5) bin_size = kw...
def load_likelihoods(filename): """ Loads from a file a dictionary that lists genomic windows that contain at least two reads and gives the bootstrap distribution of the log-likelihood ratios (LLRs). """ Open = {'bz2': bz2.open, 'gzip': gzip.open}.get(filename.rpartition('.')[-1], open) w...
This function processes multiple LLR files by loading likelihoods and metadata, extracting identifiers based on filename patterns, and compiling data into a dictionary. It generates a title combining chromosome info and a reference identifier, then uses panel_plot to create a visualization of all cases. The result is r...
def wrap_panel_plot_many_cases(filenames, **kwargs): """ Wraps the function panel_plot to show a panel with many cases. """ DATA = {} for llr_filename in filenames: likelihoods,info = load_likelihoods(llr_filename) if llr_filename[-6:]=='.LLR.p': identifer = llr_filename[:-6...
def load_likelihoods(filename): """ Loads from a file a dictionary that lists genomic windows that contain at least two reads and gives the bootstrap distribution of the log-likelihood ratios (LLRs). """ Open = {'bz2': bz2.open, 'gzip': gzip.open}.get(filename.rpartition('.')[-1], open) w...
This function wraps the 'single_plot' function by loading likelihood data and metadata from a file, generating a descriptive title based on file names and chromosome information, then calling 'single_plot' with the data and title. It automates data loading and visualization setup for comparative chromosome analysis.
def wrap_single_plot(llr_filename, **kwargs): """ Wraps the function single_plot. """ likelihoods,info = load_likelihoods(llr_filename) show_info(info) monosomy_id = info['disomy_obs_filename'].rsplit('/',1)[-1].split('.',1)[0] disomy_id = info['monosomy_obs_filename'].rsplit('/',1)[-1].split('.',1...
def get_action(state, epsilon): """your code here""" result = np.random.uniform() if result < epsilon: return random.randint(0, 2) else: st = env_state_to_Q_state(state) return np.argmax(q_table[st]) def env_state_to_Q_state(state): [position, velocity] = state """ retur...
The code implements Q-learning to train an agent by updating a Q-table over multiple episodes. It uses an epsilon-greedy strategy for exploration, decays epsilon linearly, and updates the policy based on state transitions and rewards. The final policy, representing optimal actions for each state, is returned as a numpy...
def q_learning(episodes): """your code here""" epsilon = 1 policy = [0] * num_states dec = (epsilon) / episodes for i in range(episodes): done = False state = env.reset() while not done: action = get_action(state, epsilon) new_state, reward,...
def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def replace_variables(prompt): variables = re.findall(r'\[\[(.*?)\]\]', prompt) if not variables: return prompt, dict(), '' config_hash = sha256_hash(','.join(variables)) history = read_history().sort_values('created_at', a...
The code processes a text prompt from a file using a specified model, tracks token usage and costs, handles interruptions, and saves results including execution time, token counts, and cost. It streams the prompt, replaces variables, and logs data for analysis.
def run(file_location, model, temperature, stop, print_tokens): clear_screen() file_location = os.path.abspath(file_location) enc = tiktoken.encoding_for_model(model) count_tokens = lambda s: len(enc.encode(s)) try: prompt = open(file_location, 'r').read() raw_prompt = prompt ...
def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def replace_variables(prompt): variables = re.findall(r'\[\[(.*?)\]\]', prompt) if not variables: return prompt, dict(), '' config_hash = sha256_hash(','.join(variables)) history = read_history().sort_values('created_at', a...
The code implements a chat interface that processes user input using a language model, tracks token usage, execution time, and cost, and saves interaction logs. It reads a prompt from a file, streams model responses, logs metadata (tokens, cost, time), and handles interruptions. The loop continues until the user stops ...
def chat(file_location, model, temperature, stop, print_tokens): clear_screen() file_location = os.path.abspath(file_location) enc = tiktoken.encoding_for_model(model) count_tokens = lambda s: len(enc.encode(s)) full_data = [] try: prompt = open(file_location, 'r').read() raw_pro...
def createLines(data): """ This function will create a dictionary of all the possible lines where the key is the string of start end point of the line and the value is the line. :param data: :return: dictionary of all the possible lines """ dict_lines = {} for i in range(len(data)): ...
The function `fit` implements the AdaBoost algorithm on given data points and labels over a specified number of iterations. It initializes line and point dictionaries, assigns initial weights, and iteratively splits data into training and testing sets. For each iteration, it executes AdaBoost, records training and test...
def fit(points, labels, num_iterations=50): """ This function will run the adaboost algorithm on the given data. :param points: list of points :param labels: list of labels :param num_iterations: number of iterations :return: list of rules, list of alphas """ global POINTS, LINES, POIN...
def generate_target_coords(coord, field): target_coords = [] base_coord = field['unknown_tiles'][0] if (link_is_vertical(field['unknown_tiles'])): for y in range(base_coord[1], base_coord[1] + 2): for x in range(base_coord[0] - 1, base_coord[0] + 2): if ( coord_is_correct((x, y)) and ...
The function `proceed_elimination` processes tile elimination in a game by evaluating neighboring tiles around a given coordinate. It generates target coordinates, checks conditions based on flagged/unknown tiles, and either frees or locks guessed tiles using helper functions. The goal is to update the game state by ap...
def proceed_elimination(driver, game, coord, field): print_coord_with_msg('proceed_elimination', coord) target_coords = generate_target_coords(coord, field) for target_coord in target_coords: target_field = get_field_data(game['table'], target_coord) if (target_field['nb_flagged'] == game['table'][coord_...
def get_field_data(table, coord): field = { 'unknown_tiles': [], 'nb_unknown': 0, 'nb_flagged': 0 } for y in range(coord[1] - 1, coord[1] + 2): for x in range(coord[0] - 1, coord[0] + 2): if (is_unknown(table, (x, y))): field['unknown_tiles'].append((x, y)) field['nb_unknown...
This function determines if a game tile at a given coordinate should be marked as safe based on surrounding flagged/unknown tiles. If conditions are met, it updates game state by either freeing or locking the tile, resets inactivity counter, and marks the tile as safe. The function returns the modified game object with...
def check_satisfaction(driver, game, coord): field = get_field_data(game['table'], coord) if (field['nb_flagged'] == game['table'][coord_to_id(coord)]['value']): game['tableHasChanged'] = True game['nbInactive'] = 0 game['table'][coord_to_id(coord)]['isSafe'] = True game['table'] = free_tile(driver...
def get_field_data(table, coord): field = { 'unknown_tiles': [], 'nb_unknown': 0, 'nb_flagged': 0 } for y in range(coord[1] - 1, coord[1] + 2): for x in range(coord[0] - 1, coord[0] + 2): if (is_unknown(table, (x, y))): field['unknown_tiles'].append((x, y)) field['nb_unknown...
This function checks if a group of linked tiles in a game meets specific criteria (2 unknown tiles, flagged tiles matching the cell's value minus one) and triggers an elimination process if so, updating the game state accordingly.
def check_linked_tiles(driver, game, coord): field = get_field_data(game['table'], coord) if ( # game['table'][coord_to_id(coord)]['value'] != 1 and field['nb_unknown'] == 2 and field['nb_flagged'] == game['table'][coord_to_id(coord)]['value'] - 1 and tiles_are_linked(game['table'], field['unknown_...
def check_satisfaction(driver, game, coord): field = get_field_data(game['table'], coord) if (field['nb_flagged'] == game['table'][coord_to_id(coord)]['value']): game['tableHasChanged'] = True game['nbInactive'] = 0 game['table'][coord_to_id(coord)]['isSafe'] = True game['table'] = free_tile(driver...
The function `play_next` processes a game board by iterating through tiles to apply strategies for updating the game state. It first checks satisfaction conditions, then linked tiles, and finally brute-force logic if previous strategies didn't modify the board. The goal is to determine safe moves or updates for the gam...
def play_next(driver, game): number_list = [1, 2, 3, 4, 5, 6, 7, 8] game['tableHasChanged'] = False # Check satisfaction strategy for y in range(0, 16): for x in range(0, 30): if (not game['table'][coord_to_id((x, y))]['isSafe'] and game['table'][coord_to_id((x, y))]['value'] in number_list): ...
def play_first_move(game): click_tile(game['table'], (15, 8)) game['tableHasChanged'] = True return (game) def is_mined(table): nb_bomb = 100 for tile_id in table.keys(): if (table[tile_id]['value'] == FLAGGED): nb_bomb -= 1 return (nb_bomb) def play_next(driver, game): number_list = [1, 2, 3, ...
The code simulates a game loop where a table is updated and moves are made iteratively. It tracks table changes and inactivity, resetting the game if two consecutive inactive states occur. The driver interacts with the table, updating it and executing moves until the table is no longer mined.
def play(driver, table): game = { 'tableHasChanged': False, 'nbInactive': 0, 'table': table } game = play_first_move(game) game['table'] = update_table(driver, game['table']) while (is_mined(table)): # if (not game['tableHasChanged']): game['table'] = update_table(driver, game['table']) ...
def lazy_triplet_loss(q_vec, pos_vecs, neg_vecs, margin): # Calc best_pos best_pos = best_pos_distance(q_vec, pos_vecs) # Prepare to calc triplet loss num_neg = neg_vecs.get_shape()[1] batch = q_vec.get_shape()[0] if len(pos_vecs.get_shape()) == 3: reduce = False query_copies =...
The main task of the code is to compute a quadruplet loss by combining a triplet loss with an additional loss component that considers other negative examples. It calculates the triplet loss using query, positive, and negative vectors, then computes a second loss term involving other negatives and margins m1/m2, summin...
def lazy_quadruplet_loss(q_vec, pos_vecs, neg_vecs, other_neg, m1, m2): # Calc lazy triplet loss trip_loss = lazy_triplet_loss(q_vec, pos_vecs, neg_vecs, m1) # Calc best pos best_pos = best_pos_distance(q_vec, pos_vecs) # Prepare to calc other negatives loss num_neg = neg_vecs.get_shape()[1] ...
def lf_polarities(self) -> List[List[int]]: """Infer the polarities of each LF based on evidence in a label matrix. Returns: List[List[int]]: Unique output labels for each LF Example: >>> L = np.array([ ... [-1, 0, 0], ... [-1, -1...
The main task of the code is to generate a pandas DataFrame containing per-label function (LF) statistics, including polarity, coverage, overlaps, conflicts, and empirical accuracy (if gold labels are provided). It optionally plots a bar graph of these metrics. The function maps gold labels, calculates confusion matric...
def lf_summary( self, Y: Optional[np.ndarray] = None, plot: Optional[bool] = False ) -> DataFrame: """Create a pandas DataFrame with the various per-LF statistics. Args: Y (Optional[np.ndarray], optional): [n] np.ndarray of gold labels. ...
def check_nodes(start: NodePos, end: NodePos, maze: np.ndarray) -> None: """ Checks if the given position is within the bounds of the maze and not an obstacle. Does nothing when the position is valid, raises an exception otherwise. Inputs: pos: NodePos - The position to check. pos_name:...
The function `py_run_astar` executes the A* pathfinding algorithm via a C library to find the shortest path in a maze from a start to an end point. It validates inputs (library, node positions, maze), converts data to C-compatible formats, invokes the C implementation, checks for errors (e.g., memory allocation, path e...
def py_run_astar(start: NodePos, end: NodePos, maze: np.ndarray) -> tuple[float, np.ndarray]: """ Executes the ``A* pathfinding algorithm`` to find the shortest path through a given maze from a start point to an end point. This function is a Python wrapper that calls the A* algorithm implemented in C. The d...
def articles_of_database(): # list of articles articles = [] #get of articles the collection articles col = name_of_database.get_collection("articles") for document in col.find({}): # add document in list of articles articles.append(document) #dataset=pd.DataFrame(articles) ...
The function retrieves articles from a database, converts them into a DataFrame, preprocesses text, extracts keywords, combines cleaned text and keywords into a new DataFrame, and returns the merged DataFrame containing original articles with processed text and keywords.
def dataframe_articles(): #get of articles the collection articles articles = articles_of_database() #Save list of articles in dataframe format dataset = pd.DataFrame(articles) #text preprocessing text = preprocessing() keyword_list = keywords_of_article() list_keywords = keyword_list ...
def get_csv_rows(self) -> List[List[str]]: """Return csv rows.""" return [[getattr(obj, field) for field in self.get_csv_fields()] for obj in self.get_csv_queryset().all()] def get_csv_columns(self) -> List[str]: """Return csv columns.""" lst = self.csv_columns or self.get_csv_fields() ...
This method generates a CSV file response by retrieving rows and columns data, processing the response with handle_response, and writing the CSV content using write_csv, ultimately returning the CSV file as an HTTP response.
def render_to_response(self, context: dict = None, **response_kwargs): """Return csv file response.""" rows = self.get_csv_rows() columns = self.get_csv_columns() response = self.handle_response(**response_kwargs) return self.write_csv(response, columns, rows)
def resource_path(rel_path: str) -> str: try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath('.') return os.path.join(base_path, rel_path) def begin_frame(): global _mouse_held, _mouse_up, _mouse_down _mouse_down = False _mouse_up = False def handle_...
This code initializes a Pygame window for the "Charged Up Score Analyzer" application, loads graphical assets, handles user input events (mouse clicks, key presses), and continuously updates the display with custom rendering functions. The main task is to create an interactive GUI for analyzing scores, featuring event-...
def main(): pg.init() icon = pg.image.load(resource_path('icon.png')) pg.display.set_caption('Charged Up Score Analyzer') pg.display.set_icon(icon) surf = pg.display.set_mode((600, 400)) font_name = 'Fira Code' font_big = pg.font.SysFont(font_name, 50) font_sml = pg.font.SysFon...
def writeFinalCode(line): global outBuffer outBuffer += line + "\n" def loadvr(v, r): entity, i = symbolTable.findEntity(v) if entity == None: # constant value writeFinalCode("li $t" + str(r) + ", " + str(v)) return scope_depth = symbolTable.getCurrentScopeNumber() - i if i == 0:...
This function generates MIPS assembly code from intermediate code by iterating through quads, handling operations like jumps, comparisons, assignments, arithmetic, I/O, and function calls. It manages stack frames, parameters, and returns, translating each intermediate instruction into corresponding assembly commands wh...
def generateFinalCode(): global startQuadIndex nextParameter = 0 currentFunction = "" for i in range(startQuadIndex, intermediate.nextQuad()): writeFinalCode("L" + str(i) + ":") current = intermediate.quads[i] if (current[0] == "jump"): writeFinalCode("j L" + str(curr...
def is_c_function(node, log=False): result = (node.type == "function_definition") if result and log: func_decl = node.child_by_field_name("declarator") name_decl = func_decl.child_by_field_name("declarator") logging.debug("is_c_function found: %s", name_decl.text) return result def i...
This function checks if a given code node represents a C function matching the Lua C API's signature: returning 'int', having exactly one parameter of type 'lua_State', and logging details. It combines multiple checks to validate the function's compliance with Lua's C API requirements.
def is_lua_c_api_function(node): return is_c_function(node, log=True) and \ is_c_function_return_type(node, "int") and \ is_c_function_parameter_count(node, 1) and \ is_c_function_parameter_type(node, 0, "lua_State")
def piece_can_move(self,piece,old,new): xd = abs(old[0] - new[0]) yd = abs(old[1] - new[1]) piece = (piece - 1) % 6 + 1 if piece == 1: return (xd <= 1 and yd <= 1) elif piece == 2: return self.bishop_check(old,new) or self.rook_check(old,new) elif ...
The code attempts to move a chess piece from position 'old' to 'new', saves the board state, checks if the move is valid, updates the board if valid, locates the king's position, and reverts the board to the saved state if the king is in check after the move.
def move_piece(self,old,new): save_board = [[y for y in x] for x in self.board] if self.piece_can_move(self.get_tile(old),old,new): self.set_tile(new,self.get_tile(old)) self.set_tile(old,0) for item in enumerate(self.board): if 1 in item[1]: ...
def open_instrument(self): if not self.instrument_is_open: try: self.instrument = self.rm.open_resource(self.instrument_idn) self.instrument_is_open = True except visa.VisaIOError as e: print(e.args) self.close_instrument() ...
This code initializes a device interface by connecting to a VISA instrument using the provided IDN, checks if the connection is successful, retrieves the instrument's IDN string (*IDN?), handles errors, and then closes the connection. It sets up resource management, verifies instrument accessibility, and stores identif...
def __init__(self, instrument_idn: str): self.instrument_idn = instrument_idn self.instrument = str() self.idn = 'Error' self.rm = visa.ResourceManager("@py") self.rm.list_resources() print(f'instrument_idn: {self.instrument_idn}') if self.open_instrument() !=...
def _cache_patches(cache_dir, patches, workers=0): """ Spawns the specified number of workers running _cache_patches_worker(). Call this with workers=0 to run on the current thread. """ if exists(cache_dir): rmdir(cache_dir) makedirs(cache_dir) tick_t = timer() print('===> Cac...
The main task of the code is to prepare a training dataset by either loading preprocessed patches from a JSON file or generating new patches from the DAVIS 17 dataset, shuffling them, and caching them if enabled. It handles dataset directory configuration, checks for existing cached data, and ensures patches are ready ...
def prepare_dataset(dataset_dir=None, force_rebuild=False): """ Performs all necessary operations to get the training dataset ready, such as selecting patches, caching the cropped versions if necessary, etc.. :param dataset_dir: Path to the dataset folder :param force_rebuild: Whether or not the pat...
def convert_letter_to_num(posn): """Converts a posn.x value from letter to number for indexing in the board array""" letters = 'ABCDEFGH' i = 0 for letter in letters: if posn.x == letter: return i i += 1 def capture_piece(self, piece, x_posn): ...
This function updates the game board after a piece moves, handling captures, updating the king's position if the moved piece is a king, and checking for check/checkmate conditions to inform the player of the game state.
def update_board(self, from_posn, piece): old_x_value = self.convert_letter_to_num(from_posn) new_x_value = self.convert_letter_to_num(piece.posn) is_capture, value = self.capture_piece(piece, new_x_value) if is_capture: print( colored("Your {0} captured the ...
def scale_down_deployments(self): """ Scale down deployments. """ try: for tier in config.TIERS: for deployment in self.deployments[tier]: step = "Scaling Down Deployment:\ndeployment={}".format( deployment["name"] ...
This method orchestrates a complete deployment process, handling scaling, migrations, backups, and error handling. It checks deployment status, scales resources, executes migrations, updates container images, and sends Slack notifications. If errors occur, it logs them, handles failures, and communicates results. The d...
def deploy(self): """ The master deployment method to process deployment from start to finish. """ if config.DISABLED: self.slacker.send_message(text="Automated deployment is currently disabled") return error_message = None error_handling_message...
def get_cards(): return get(path=f"lists/{config.TRELLO_LIST_ID}/cards") def add_comment(card_id): post( path=f"cards/{card_id}/actions/comments", params={"text": f"released as part of {config.TAG}"}, ) def archive(card_id): put(path=f"cards/{card_id}", params={"closed": "true"})
The function `cleanup_trello` checks if Trello notifications are enabled. If so, it retrieves all cards, adds a comment to each, archives them, and sends an email notification with the list of processed cards.
def cleanup_trello(): if not config.TRELLO_SEND_NOTIFICATION: return cards = get_cards() for card in cards: add_comment(card_id=card["id"]) archive(card_id=card["id"]) send_notification_email(cards)
def _check_fleet_edges(self): #Respond appropriately if any aliens have reached an edge for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): #Responding to the ship being hit by an alien if self.stats.ships_left > 0: #Decrement ships...
This method updates alien positions, checks fleet edges, detects collisions between the ship and aliens (triggering _ship_hit() if collided), and verifies if aliens have reached the bottom of the screen, handling game logic responses accordingly.
def _update_aliens(self): #Update the positions of all aliens in the fleet #Check if fleet is at an edge and update positions of the aliens self._check_fleet_edges() self.aliens.update() #Look for alien-ship collisions if pygame.sprite.spritecollideany(self.ship,self.aliens): self._ship_hit() #Check f...
def _check_events(self): #Responsiveness to keypresses and mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type==pygame.KEYDOWN: self._check_keydown_events(event) elif event.type==pygame.KEYUP: self._check_keyup_events(event) def _update_...
The `run_game` method manages the game's main loop by continuously checking for keyboard/mouse events, updating game elements (ship, bullets, aliens) when the game is active, and rendering the screen. It maintains the game state, processes user input, and synchronizes updates to game objects and visuals in real-time.
def run_game(self): #start the main loop of the game while True: #Watch for keyboard and mouse events self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen()
def get_workload(batch_size=1, num_classes=1000, image_shape=(3, 224, 224), dtype="float32", **kwargs): net = get_net(batch_size=batch_size, num_classes=num_classes, image_shape=image_shape, dty...
The main task of the code is to compile and optimize a deep learning model using TVM, extract convolutional tasks from a Relay program, compile the model with autotuning, export the optimized library, upload it to a remote device, execute inference on an input image, and evaluate the inference time. The process include...
def main(): input_shape = (1, 3, 375, 1242) # Extract workloads from relay program print("Extract tasks...") mod, params = get_workload(image_shape=input_shape[1:], batch_size=input_shape[0]) read_params(params) tasks = autotvm.task.extract_from_program(mod["main"], target=target, target_host=t...
def get_workload(batch_size=1, image_shape=(3, 224, 224), dtype="float32", **kwargs): net = get_net(batch_size=batch_size, image_shape=image_shape, dtype=dtype, **kwargs) return create_workload(net) def get_...
The code's main task is to extract and tune neural network tasks using AutoTVM, compile optimized kernels, deploy them on a remote device, and evaluate inference performance. It handles model-specific workloads, applies tuning configurations, builds relay modules, exports libraries, uploads them to a remote server, and...
def main(): input_shape = (1, 3, 224, 224) # Extract workloads from relay program print("Extract tasks...") network = MODEL_NAME if network is 'nvidia': print('get-nvidia') mod, params = get_workload(image_shape=input_shape[1:], batch_size=input_shape[0]) else: print('g...
def get_similarity_of_two_urls(self, url1, url2): if url1 in self.url_domain_terms: domain_terms = self.url_domain_terms[url1] if os.path.isfile(url_pkl_file_name): with open(url_pkl_file_name, 'rb') as f: entities_1 = pickle.load(f) if len...
This function constructs and updates a similarity matrix by appending new URLs, computing pairwise similarities, and ensuring symmetry. It filters URLs, expands the matrix with zeros, loads data from a .pkl file, calculates similarities using a helper method, and saves the updated matrix. Debugging checks and index tra...
def construct_similarity_matrix(self, url_list): if(sim_matrix): sim_matrix = self.sim_matrix if DEBUG: print(sim_matrix.shape) starting_index = len(self.indices_for_urls) url_list = [u for u in url_list if u not in self.url_domain_terms] ...
def from_string(self, text): if self.check_hex(text) and len(text)<=self.size: self.ival = int(text,16) self.hval = zfill(text, self.size) if not self.limits(self.ival): self.default() return self def from_int(self, value): self.default() if self.limits(value): self.iva...
This code initializes an object with parameters for value range and size, handling input as string or integer. It sets default vmin/vmax values, uses from_string/from_int methods based on input type, and ensures a default value if none is provided.
def __init__(self, value=0, size=4, vmin=None, vmax=None): self.ival = None self.size = size if vmin is None: self.vmin = 0 else: self.vmin = vmin if vmax is None: self.vmax = pow(2,self.size*4) else: self.vmax = vmax if isinstance(value, str): self.from_string(...
def plurality_value(examples): """Return the most popular target value for this set of examples. (If target is binary, this is the majority; otherwise plurality.)""" popular = argmax_random_tie(values[target], key=lambda v: count(target, v, examples)) ...
This code recursively builds a decision tree by selecting attributes to split examples, handling base cases like empty data or uniform class labels, and creating tree nodes (forks/leaves) based on attribute values and majority class votes.
def decision_tree_learning(examples, attrs, parent_examples=()): if len(examples) == 0: return plurality_value(parent_examples) elif all_same_class(examples): return DecisionLeaf(examples[0][target]) elif len(attrs) == 0: return plurality_value(examples) ...
def set_wall(self, _, pos): if pos == self.spawn or pos == self.finish or not self.choosing_walls: return if pos in self.walls: self.walls.remove(pos) col = self.pallete['default'] else: self.walls.append(pos) col = self.pallete['walls'] self.canvas.itemconfig(self.square[pos[1]][pos[0]], fill=c...
This code initializes a Q-learning environment with a grid-based maze, allowing user interaction to define walls via a Tkinter GUI. It sets up a Q-table for reinforcement learning, configures start/finish positions, and enters a loop to collect wall inputs. After setup, it trains the AI agent and executes the learned p...
def __init__(self, pallete=def_pallete, table=(20, 20), spawn=(0, 0), finish=None, max_tries=100): self.table = table self.spawn = spawn self.pallete = pallete if finish: self.finish = finish else: self.finish = (self.table[0] - 1, self.table[1] - 1) self.Q_matrix = [[[0 for _ in range(4)] for _ in ra...
def permutate(original, fixed_key): new = '' for i in fixed_key: new += original[i - 1] return new def f_k(bits, key): L = left_half(bits) R = right_half(bits) bits = permutate(R, FIXED_EP) bits = xor(bits, key) bits = lookup_in_sbox(left_half(bits), S0) + lookup_in_sbox(right_ha...
The code implements a Feistel cipher encryption process. It applies an initial permutation to the plaintext, performs two rounds of substitution-permutation using subkeys, combines halves with round outputs, and applies an inverse permutation to produce ciphertext.
def encrypt(plain_text): bits = permutate(plain_text, FIXED_IP) temp = f_k(bits, key1()) bits = right_half(bits) + temp bits = f_k(bits, key2()) encr=permutate(bits + temp, FIXED_IP_INVERSE) #print(encr) return encr
def permutate(original, fixed_key): new = '' for i in fixed_key: new += original[i - 1] return new def f_k(bits, key): L = left_half(bits) R = right_half(bits) bits = permutate(R, FIXED_EP) bits = xor(bits, key) bits = lookup_in_sbox(left_half(bits), S0) + lookup_in_sbox(right_ha...
This code decrypts a cipher text using a Feistel network structure. It applies permutation (FIXED_IP), performs two rounds of function operations (f_k) with keys key2() and key1(), combines halves, and applies inverse permutation (FIXED_IP_INVERSE) to retrieve the original plaintext.
def decrypt(cipher_text): bits = permutate(cipher_text, FIXED_IP) temp = f_k(bits, key2()) bits = right_half(bits) + temp bits = f_k(bits, key1()) decr=permutate(bits + temp, FIXED_IP_INVERSE) #print(decr) return decr
def move(self, xchange): if not self.gameover and not self.paused: new_x = self.piece_x + xchange if new_x < 0: new_x = 0 if new_x > columnnum - len(self.piece[0]): new_x = columnnum - len(self.piece[0]) if not check_collision(self....
This code runs a Tetris game loop, handling user input for movement/rotation, updating game state, rendering the game screen with the playing field, score, next pieces, and buttons, and managing game over/pause states until the player quits or loses.
def run(self): #create a dictionary for the possible moves: up, down, left, right, #p, escape, return, and space (and their coordinate code calls) keyslist = { 'SPACE': self.start_game, 'LEFT': lambda:self.move(-1), #moving left is negative 'RIGHT': ...
def move(self, xchange): if not self.gameover and not self.paused: new_x = self.piece_x + xchange if new_x < 0: new_x = 0 if new_x > columnnum - len(self.piece[0]): new_x = columnnum - len(self.piece[0]) if not check_collision(self....
This code runs a Tetris game loop, handling user input for piece movement and rotation, rendering the game screen with scores and UI elements, managing game states (pause/game over), and displaying multiplayer end-game results. It uses Pygame for graphics, event handling, and controls, including keyboard and mouse inte...
def run(self): #create a dictionary for the possible moves: up, down, left, right, #p, escape, return, and space (and their coordinate code calls) keyslist = { 'SPACE': self.start_game, 'LEFT': lambda:self.move(-1), #moving left is negative 'RIGHT': ...
def tokenize_and_stem(doc): token_docs = word_tokenize(doc) prepared_tokens = [token.lower() for token in token_docs] stemmed_terms = [stem(token) for token in token_docs] return prepared_tokens, stemmed_terms def calculate_document_lengths(term_freq_inve_doc_freq): return np.sqrt((term_freq_inve_do...
The main task of the code is to generate and save detailed results of a vector space model query processing, including term frequency-inverse document frequency (TF-IDF) calculations, product sum computations, cosine similarity scores, and related documents. It writes these results to a text file if the query matches d...
def build_output_content(query, related_docs_PQ_stage, tfidf, tfdf): query_tokens, query_terms = tokenize_and_stem(query) if related_docs_PQ_stage: # save the result for Phrase query document_lengths = calculate_document_lengths(tfidf) normalized_term_freq_idf = normalize_term_freq_idf(...
def collect_decl_macro(ctx, cursor): if str(cursor.location.file) != ctx.parse_file: return tokens = list(cursor.get_tokens()) macro_name = str(tokens[0].spelling) if ctx.has_decl_macro(macro_name): return ctx.collection_mode = ParseContext.Decl_Macro macro_values = list(map(...
The function `collect_decl` processes C/C++ declarations by traversing an AST (Abstract Syntax Tree) node (`cursor`). It iterates through child nodes, handling specific declaration types (e.g., macros, typedefs, enums, structs, functions) by calling corresponding helper functions. For other node types, it recursively p...
def collect_decl(ctx, cursor): ctx.push() for child in cursor.get_children(): if child.kind == CursorKind.MACRO_DEFINITION: collect_decl_macro(ctx, child) for child in cursor.get_children(): if child.kind == CursorKind.TYPEDEF_DECL: collect_decl_typedef(ctx, child) ...
def non_three_colourable(): G = Graph(4) G.add_edge(0, 1) G.add_edge(1, 2) G.add_edge(2, 0) G.add_edge(3, 0) G.add_edge(3, 1) G.add_edge(3, 2) three_colouring(G) # print([v.colour for v in G]) with open('./dots/icosahedron.dot', 'w') as f: write_dot(G, f) def triangle(...
The main task of the code is to execute and test three graph-related functions: `non_three_colourable()`, `triangle()`, and `petersen_graph()`, while printing descriptive labels for each. It serves as a simple test suite to verify the execution of these functions, likely in a graph theory or computational context.
def test_simple(): print('icosahedron') non_three_colourable() print() print('triangle') triangle() print() print('petersen graph') petersen_graph()
def move(self): sin_a = math.sin(self.player_angle) cos_a = math.cos(self.player_angle) delta_x, delta_y = 0, 0 if(self.sprinting): speed = (self.player_speed * 2) * self.game.delta_time else: speed = self.player_speed * self.game.delta_time speed...
The code updates a character's state by assigning a new weapon, triggering movement, healing, shooting checks, mouse control, health bar display, map dot rendering, and setting a shooting cooldown based on the weapon's reload speed.
def update(self, weapon): self.weapon = weapon self.move() self.healing() self.check_shooting(weapon) self.mouse_control() self.show_health_bar() self.show_map_dot() self.shooting_cooldown = weapon.reload_speed * 1000
def process_request_data(client_socket): received_data = receive_larger(client_socket) result_data = None try: utf = True # Try to decode the received data as UTF-8 result_data = received_data.decode("utf-8") # Your text data processing logic here except UnicodeDecodeErr...
The function handles HTTP client requests by managing connection limits, authenticating users via cookies, parsing HTTP methods (GET/HEAD/POST), serving files/download, handling encryption/decryption, managing sessions, and returning appropriate HTTP responses (200, 401, 404, 500, 502, 503). It processes request header...
def handle_client_request(client_socket): global active_connections if active_connections > 5: error_response = "HTTP/1.1 503 Service Unavailable\r\n\r\nServer Overloaded" client_socket.sendall(error_response.encode('utf-8')) return # Increment active connections count when a ne...
def _check_for_new_connections(self): new_client_socket = self._server_socket.check_for_new_clients() if new_client_socket: client = Client(new_client_socket) self._clients[client.uuid] = client self._new_events.append( Event(ServerEvents.NEW_PLAYER, c...
The main task of the code is to update the game state by checking for new players, disconnected players, and incoming messages. It processes these events, then transfers them to a main events list for retrieval via `get_new_players`, `get_disconnected_players`, and `get_commands`. This method must be repeatedly called ...
def update(self): """Checks for new players, disconnected players, and new messages sent from players. This method must be called before up-to-date info can be obtained from the 'get_new_players', 'get_disconnected_players' and 'get_commands' methods. It should be called in a loo...
def welcome(self): self.send("Welcome to Asigna!") self.send("Enter your name: ") def receive(self): while True: try: temp = None temp = self.conn.recv(1024) temp = str(temp, 'ascii') #temp = str(temp) As...
The code initializes a server connection, sets up global variables, and starts two threads: one for receiving data and another for pinging. It assigns the provided server instance to a global variable, invokes a welcome method, creates a receiver thread targeting `self.receive()` with the server, and starts it. A separ...
def __init__(self, addy, the_server): global server, pinger, receiver server = the_server self.welcome() receiver = threading.Thread(target=self.receive(), args=(self, server)) receiver.start() pinger = threading.Thread(target=self.ping(), args=(self, ))
def gold_blue(df, minute=10): players = ['goldblueTop','goldblueJungle','goldblueMiddle','goldblueADC','goldblueSupport'] gold = df['min_'+str(minute)][players]\ .astype(int)\ .sum(axis=1) return gold def gold_red(df, minute=10): players = ['goldredTop','goldredJu...
The code generates a DataFrame of features from input data, calculating gold and earnings-related metrics like gold differences, wealth comparisons between teams, and earnings disparities. It combines results from helper functions to create a structured output for analysis or modeling.
def generate_gold_features(df): features = pd.DataFrame() features['blue_gold'] = gold_blue(df) features['red_gold'] = gold_red(df) features['gold_diff'] = final_gold_diff(df) features['blue_richer'] = features['gold_diff'] >= 0 features['blue_richer_count'] = blue_richer_count(df) features[...
def build_message(message: bytes) -> bytes: message_prefix = append() message_suffix = append() message = message_prefix + message + message_suffix if len(message) % BLOCK_SIZE != 0: message = pkcs7_encode(message) assert len(message) % BLOCK_SIZE == 0 return message def get_random_bytes...
The function encrypts a byte message using either ECB or CBC mode with a random key and IV (for CBC), returning the chosen mode and the encrypted ciphertext.
def encrypt_message(message: bytes) -> Tuple[str, bytes]: message = build_message(message) key = get_random_bytes() if choose(): # use cbc mode = "cbc" iv = get_random_bytes() cipher = cbc_encrypt(message, key, iv) else: mode = "ecb" cipher = ecb_encrypt(m...
def isAnimalHasImage(animalName, id): return os.path.isfile(getAnimalImagePath(animalName, id)) def onCellClicked(animalName, event): if event.args['colId'] == 'id': maybeOpenAnimalImage(animalName, event.args['data']['idPure']) def createFooter(): with ui.element('div').style("text-align:center;pad...
The main task of the code is to render a UI displaying the latest 50 harvests in a sortable, paginated grid. It collects animal data from `saveStructure`, processes it into structured rows with metadata (e.g., type, gender, rating, datetime), and formats it for display. The interface includes a "BACK" button, labels, a...
def home(): with ui.element("div").style("display:grid;grid-template-columns:1fr auto;width:100%"): with ui.element("div"): ui.label("LATEST HARVESTS").style("font-size:30px;color:#666;") with ui.element("div").style("text-align:right"): with ui.link("", "/").style("float:rig...
def isAnimalHasImage(animalName, id): return os.path.isfile(getAnimalImagePath(animalName, id)) def onCellClicked(animalName, event): if event.args['colId'] == 'id': maybeOpenAnimalImage(animalName, event.args['data']['idPure']) def createFooter(): with ui.element('div').style("text-align:center;pad...
The code displays detailed information about a specified animal, including rating statistics, harvest data, and a customizable grid of individual animal entries with attributes like gender, weight, badge, and difficulty. It dynamically generates UI elements, processes data from a structured dataset, and enables user in...
def animal(animalName): if animalName not in saveStructure.animals: saveStructure.animals[animalName] = [] ratingCounts = getRatingCounts(saveStructure.animals[animalName]) harvestsSinceLastDiamond = getHarvestsSinceLastDiamond(saveStructure.animals[animalName]) harvestsCountTookForLastDiamond ...
def import_df_to_db(connection, data_frame, table_name): columns = [] for column_name, dtype in zip(data_frame.columns, data_frame.dtypes): sql_type = dtypes.get(str(dtype), 'TEXT') column_name = column_name.replace(":", "_") column_name = column_name.replace(" ", "") columns.app...
The main task of the code is to build an SQLite database integrating metadata, ontology data, PubMed references, and term mappings. It imports metadata tables, ontology hierarchies, reference details, and ontology-term mappings, then merges mapping counts with ontology labels. The database includes tables for metadata,...
def build_database(metadata_df, dataset_name, ontology_name, resource_col=text2term_mapping_source_term_col, resource_id_col=text2term_mapping_source_term_id_col, output_database_filepath="", ontology_term_iri_col=text2term_mapping_target_term_...
def checkLive(self): if self.live: return True # Try to get dimensions from GLTextureSink self.vid = Vec2f(self.sink.get_property("width"), self.sink.get_property("height")) if self.vid.w > 0 and self.vid.h > 0: self.tex = Vec2f(1.0, 1.0) ...
The code renders a textured rectangle using OpenGL by checking if the app is live and visible, updating shaders if necessary, setting up texture coordinates, and drawing the rectangle with `glDrawArrays`. It handles animation, texture binding, and client state management for rendering.
def draw(self): # First actual frame has arrived? if not self.checkLive(): return # App allows display? if not self.visible: return # App has changed shaders? if gpu.getProgram() != self.prog: self.configShader() self.prog =...
def _draw_dialog(self): self._draw_background() if self.patch: self.patch.texture.alpha = self.alpha self.patch.surround(self.area) elif self.frame: self._draw_frame() self.rects = [] scale = self.text_scale height = self.text_font.height * scale y = self._draw_title() x = self.area.left + sel...
This function handles user input for a dialog interface, updating the selected button index based on horizontal movement, playing sounds for navigation and invalid vertical input, and triggering a callback with the selected button or 'Done' when confirmed or canceled, while managing dialog state and sound feedback.
def _handle_dialog(self, events=None): rvalue = None if self.alive: self._draw_dialog() move, select, events = self._get_input(events) if move.x < 0: self.bselected -= 1 self._play_sound() elif move.x > 0: self.bselected += 1 self._play_sound() self.bselected = self.bselected % len(se...
def _draw_input(self): self._draw_background() if self.patch: self.patch.texture.alpha = self.alpha self.patch.surround(self.area) elif self.frame: self._draw_frame() x = self.area.centerx y = self._draw_title() self.rects = [] r, x, max_width = self._draw_box(self.area.left, y) y = r.center...
This function handles user input for a UI element, processing navigation (left/right movement to select buttons), input validation (converting text to int/float), and triggering callbacks. It updates selection indices, plays sounds on movement, processes text input, and returns validated input values along with the sel...
def _handle_input(self, events=None): rvalue = None, None, None if self.alive: self._draw_input() move, select, events = self._get_input(events) if move.x < 0: self._play_sound() self.bselected -= 1 elif move.x > 0: self._play_sound() self.bselected += 1 self.bselected = self.bselecte...
def _draw_background(self): if self.draw_background: if self.back_func: self.back_func[0](self.back_func[1:]) elif self.back_image: if self.back_tiled: tile_background(self.target, self.back_image) else: self.back_image.draw() else: self.target.draw_color = self.back_color self...
This function renders UI options by drawing backgrounds, patches/frames, titles, and individual options. It positions elements vertically with spacing, handles alpha transparency for patches, and renders buttons if present. The logic differentiates between option types and updates layout coordinates accordingly.
def _draw_options(self, options): self.changeable = False self.rects = [] self._draw_background() if self.patch: self.patch.texture.alpha = self.alpha self.patch.surround(self.area) elif self.frame: self._draw_frame() #if self.sel_patch: # self.sel_patch.texture.alpha = self.alpha x = self.area...
def _draw_options(self, options): self.changeable = False self.rects = [] self._draw_background() if self.patch: self.patch.texture.alpha = self.alpha self.patch.surround(self.area) elif self.frame: self._draw_frame() #if self.sel_patch: # self.sel_patch.texture.alpha = self.alpha x = self.area...
This code handles user input for navigating and selecting options in a UI menu. It updates the selected item based on vertical movement, manages button selections, plays sounds, and triggers callbacks with selected values or button actions. It returns the result of the selection, including key-value pairs or button ide...
def _handle_options(self, events=None): rvalue = None if self.alive: options = self.items self._draw_options(options) if self.buttons: # extra rect for bottom buttons self.rects.append(pg.Rect(0,0,1,1)) move, select, events = self._get_input(events) if move.y < 0: self.selected -= 1 sel...
def wave_func(x=None,n= None): '''A function to calculate the wavefunction of the nth energy level of the 1D quantum harmonic oscillator :param n: int nth energy level :param x: np.ndarray range over which to evaluate the wavefunction :return: returns the w...
The code generates and plots quantum harmonic oscillator (QHO) wavefunctions for $ n = 0 $ to $ 3 $ over $ x = -4 $ to $ 4 $, then plots the $ n = 30 $ wavefunction over $ x = -10 $ to $ 10 $. It calculates the expectation value $ \langle x^2 \rangle $ and RMS uncertainty for the QHO using Gaussian quadrature (part c) ...
def main(): #a: qho wavefunctions for n=0,..,3 and x=-4,..,4 x = np.arange(-4,4,0.1) wavs = [] for n in range(0,4): wavs.append(wave_func(x,n)) plt.plot(x,wavs[n],label='n = %s' %n) plt.title("Quantum Harmonic Oscillator Wavefunctions") plt.xlabel('x') plt.ylabel('$\psi(x)$'...
def image_loader(name): image_dir = os.path.join(IMAGE_PATH, name) return ImageTk.PhotoImage(file=image_dir) def label_maker(frame): """Function to creates the labels in the 5*6 grid.""" return tk.Label( frame, text=" ", font=GRID_FONT, borderwidth=3, padx=20, ...
The main task of the code is to initialize a Hangman game GUI using Tkinter. It sets up the window, loads fonts and images, creates the Hangman display, guess area, and keyboard interface with labeled letters and buttons, then starts the main event loop for user interaction.
def main(): global GRID_FONT global KEYBOARD_FONT global SCRIPT_DIR global IMAGE_PATH window = tk.Tk() window.title("Hangman") window.resizable(False, False) GRID_FONT = font.Font(family="Courier", size=30, weight="bold") KEYBOARD_FONT = font.Font(family="Courier", size=25, weight=...
def get_minimum_f_score_node(self): self.open_set = sorted(self.open_set, key=lambda x: x.f_score) return self.open_set[0] def is_goal(tiles: list, goal: list) -> bool: if tiles == goal: return True return False def print_path(self) -> None: tmp_state = self.current_s...
The code implements the A* algorithm to find the optimal path in a search space. It iteratively selects the node with the minimum f-score (cost + heuristic) from the open set, checks if it matches the goal state, and generates child nodes if not. The current state is then moved to the closed set, ensuring efficient exp...
def a_star_algorithm(self): while self.open_set: self.current_state = self.get_minimum_f_score_node() if self.is_goal(self.current_state.tiles, self.goal): self.print_path() break else: self.create_children(self.current_state) ...
def segments_distance(x11, y11, x12, y12, x21, y21, x22, y22, name1="", name2=""): """ distance between two segments in the plane: one segment is (x11, y11) to (x12, y12) the other is (x21, y21) to (x22, y22) """ if segments_intersect(x11, y11, x12, y12, x21, y21, x22, y22, name1, name2): return 1e-...
This function performs a DBSCAN-like clustering on trajectory segments. It identifies reachable segments within a maximum distance (max_dist) and angular tolerance (max_angle) from a seed segment (seg1). It aggregates segments meeting density criteria (min_weight) by summing weights and collecting closest segments. If ...
def DBScan(seg1, traj_angles, max_dist, min_weight, max_angle): #print seg1.parent.name, seg1, seg1.id, datetime.datetime.now() # reachable_lines = [] reachable_segs = [] sumweight = 0.0 represented_lines = set() for angle in traj_angles: if abs(angle - seg1.parent.angle) > max_angle: ...
def output(s): print (' '+s) def fetch_input(): s = raw_input('$$ ') while (s.split() == []): s = raw_input('$$ ') return s def sem(tr): """translates a syntax tree into a logical lambda expression (in string form)""" rule = top_level_rule(tr) #basically tried to follow the r...
The code processes user dialogues by parsing questions, checking for ambiguity, and retrieving answers from a knowledge base. It handles queries ending with '?' by generating lambda expressions, simplifying them, and finding solutions in the fact base. Statements ending with '.' are processed to update the knowledge ba...
def dialogue(): lx = Lexicon() fb = FactBase() output('') s = fetch_input() while (s.split() == []): s = raw_input('$$ ') while (s != 'exit'): if (s[-1]=='?'): sent = s[:-1] + ' ?' # tolerate absence of space before '?' wds = sent.split() tree...
def rank(hand): ''' (hand) -> list Return ranks ''' ranks = [] for r,s in hand: ranks.append('--23456789TJQKA'.index(r)) ranks.sort(reverse=True) if ranks == [14,5,4,3,2]: ranks = [5,4,3,2,1] return ranks def straight_flush(hand): ''' (hand) -> bool ...
The function `hand_rank` evaluates a poker hand's strength by checking for specific combinations (e.g., straight flush, four of a kind) in descending priority. It returns a tuple indicating the hand's rank category (0–8) and relevant values (e.g., highest card, pairs) for comparison. The tuple structure ensures higher-...
def hand_rank(hand): ''' (hand)-> tuple Return the hand rank of this hand ''' ranks = rank(hand) if straight_flush(hand): return 8, max(ranks) elif kind(4, ranks): return 7, kind(4, ranks) elif full_house(ranks): return 6, kind(3, ranks) elif flush(hand): ...
def parse_header(header): # count = int(header.replace('>', '').replace('_', '')) hw = header.replace('>', '').split('_') count = int(hw[0]) category = hw[1] return count, category def is_main_category(category): ''' Match: delX, insX Do not match: delnotcrispr, insnotcrispr delnotatcut, insnota...
The code processes genotype data from input files by parsing CRISPR-induced insertions, deletions, and counts for specific peptides. It aggregates results into DataFrames, saves them as CSV and pickle files, and is likely used for analyzing variant data in genomics or CRISPR screening experiments.
def genotype_data(inp_dir, out_dir, nm, start, end): print(nm) start, end = int(start), int(end) master_df = pd.DataFrame() # Parse condition-specific settings exp_row = exp_design[exp_design['Name'] == nm].iloc[0] lib_nm = exp_row['Dual library'] target_nm = exp_row['Target'] # Library design globa...
def get_cutsite_idx(read, genome): # Given cutsite position in genome, find idx such that # read[:idx], read[idx:], & # genome[:idx], genome[idx:] # are the CRISPR cut products... # even with starting gaps and arbitrary indels genome_start_idx = genome.index(genome.replace('-', '')[:1]) counter = 0 ...
This function identifies the position and direction of a single deletion in a read relative to the genome, then applies a corresponding left or right shift to adjust the alignment, ensuring exactly one deletion with no insertions.
def shift_single_deletion(read, genome, old_category): # Find where cut should be, with possible starting gaps, but exactly one deletion and no insertions in alignment. cutsite = get_cutsite_idx(read, genome) # seq[:cutsite], seq[cutsite:] gives cut products lr = left_or_right_event(read, cutsite) if lr == '...
def get_cutsite_idx(read, genome): # Given cutsite position in genome, find idx such that # read[:idx], read[idx:], & # genome[:idx], genome[idx:] # are the CRISPR cut products... # even with starting gaps and arbitrary indels genome_start_idx = genome.index(genome.replace('-', '')[:1]) counter = 0 ...
This function identifies the insertion site in a DNA read relative to the genome, determines if the insertion is on the left or right side of the cutsite, and delegates to the corresponding helper function (rightshift or leftshift) to handle the alignment adjustment for a single insertion event, using the provided old_...
def shift_single_insertion(read, genome, old_category): # Find where cut should be, with possible starting gaps, but exactly one deletion and no insertions in alignment. cutsite = get_cutsite_idx(read, genome) # seq[:cutsite], seq[cutsite:] gives cut products lr = left_or_right_event(genome, cutsite) if lr =...
def check_matches_threshold(read, genome): s1, s2 = '', '' for idx in range(len(genome) - 1, -1, -1): if genome[idx] in 'ACGTN': if read[idx] != '-': s1 += read[idx] s2 += genome[idx] if len(s1) == 0: return False match_score = match_rate(s1, s2) if len(s1) <= 5 or match_score <=...
The function categorizes DNA sequence alignments into predefined classes (e.g., homopolymer, hasN, poormatches, pcr_dimer, HDR, wildtype, indel types) based on features like homopolymer status, alignment quality, PCR recombination, and indel patterns. It uses helper functions to detect specific alignment characteristic...
def categorize_alignment(read, genome): # Alignment endgaps are assumed to be meaningless # check if homopolymer if len(set(read.replace('-', ''))) == 1: return 'homopolymer' if 'N' in read: return 'hasN' ''' Detect PCR recombination within context (should be rare). Only anticipated for g...