dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def find_opposite_goal(start, all_goals): return all_goals[(all_goals.index(start) + 1) % len(all_goals)] def process_tri_a_star_node(graph, start, goal, other_goals, frontiers_dict, explored_node_dict, found_paths, heuristic=euclidean_dist_heuristic): if frontiers_dict[start].size()...
The code implements an upgraded tridirectional search algorithm to find the optimal path connecting three goals in an undirected graph. It uses A* search principles with heuristic guidance (e.g., Euclidean distance) and landmark-based optimizations. The algorithm maintains separate frontiers and explored sets for each ...
def tridirectional_upgraded(graph, goals, heuristic=euclidean_dist_heuristic, landmarks=None): """ Exercise 4: Upgraded Tridirectional Search See README.MD for exercise description. Args: graph (ExplorableGraph): Undirected graph to search. goals (list): Key values for the 3 goals ...
def _print_tool_names(self): self._print_green_indented("Active Tools:") for active_tool_name in self._tool_names: self._print_green_indented(f"- {active_tool_name}") def _print_available_tool_names(self): self._print_green_indented("Available Tools:") for available_tool_name...
This function processes tool management commands. It checks for "/tool", "/tool all", "/tool add [name]", and "/tool rm [name]" to list tools, add specific tools (with special handling for "rag" and "git_diff"), or remove tools, returning True if a command is recognized and processed, otherwise False.
def _process_tool_command(self, line: str) -> bool: if line.lower() == "/tool": self._print_tool_names() return True if line.lower() == "/tool all": self._print_available_tool_names() return True if line.lower().startswith("/tool add"): ...
def _process_help_command(self, line: str) -> bool: if line.lower() in ["/?", "/help"]: self._print_all_instructions() return True return False def _process_model_command(self, line: str) -> bool: if line.lower().startswith("/model"): arg = self._get_subcomman...
This function processes user input lines for a command-line interface, handling multiline input mode, command parsing, and execution. It starts/stops multiline mode, collects input lines, processes help/model/tool commands, and returns the line or handles unknown commands by printing errors and instructions.
def _process_input(self, line: str) -> Union[str, None]: if self._is_multiline_mode: if line.lower() == "/end": self._is_multiline_mode = False return "\n".join(self._mutiline_user_inputs) self._mutiline_user_inputs.append(line) return ...
def root_folder(self): return os.path.join( self.parent.grid_search_path(), self.grid_search_name ) def set_param_combos(self): self.param_combos = list(ParameterGrid({ 'units': self.units, 'batch_size': self.batch_size, 'dropout': self.dropout, ...
This code initializes a grid search process by setting up parameters, validating the directory structure, splitting training/validation data, saving configurations, and executing the grid search. It ensures no duplicate grid search runs by checking for existing directories and raises an error if conflicts occur.
def __init__(self, parent, **kwargs): self.parent = parent self.__dict__.update(kwargs) grid_search_path = self.root_folder() if os.path.exists(grid_search_path): raise ValueError( ERROR_GRID_SEARCH_EXISTS.format( grid_search_name=self.gri...
def mr_egger(beta_e, se_e, beta_o, se_o, correlation_matrix=None): """ MR Egger implementation Args ----- beta_e: numpy array of beta-coefficient values for genetic associations with the exposure trait se_e: numpy array of the standard error associated with beta_e beta_o: numpy array of the beta-coeffi...
The function computes the MR-Trio negative squared error statistic by predicting outcome values using a Two-Stage Least Squares (2SLS) approach. It leverages genetic associations (beta coefficients and standard errors) for exposure and outcome traits, applies the specified MR method (IVW, Egger, Median, Mode) to estima...
def compute_statistic(beta_e, se_e, beta_o, se_o, genotypes, outcome_trait, mr_method, mr_est=None): """ Computes the MR-Trio negative squared error test statistic. Outcome values are predicted via a Two-Stage Least Squares (2SLS) style approach using the input genotypes, and the negative squared error against th...
def mr_ivw(beta_e, se_e, beta_o, se_o): """ MR IVW implementation Args ----- beta_e: numpy array of beta-coefficient values for genetic associations with the exposure trait se_e: numpy array of the standard error associated with beta_e beta_o: numpy array of the beta-coefficient values for genetic as...
The function `mr_all_methods` performs multiple Mendelian Randomization (MR) analyses by calling four distinct methods—IVW, median, Egger, and mode—to estimate causal effects using genetic instruments. It returns results from each method, incorporating parameters like weighting, iterations, correlation matrices, and ph...
def mr_all_methods(beta_e, se_e, beta_o, se_o, weighted_p=True, it_p=10000, correlation_matrix=None, phi=1): ivw = mr_ivw(beta_e, se_e, beta_o, se_o) median = mr_median(beta_e, se_e, beta_o, se_o, it=it_p, weighted=weighted_p) egger = mr_egger(beta_e, se_e, beta_o, se_o, correlation_matrix) mode = mr_mode(beta_e, s...
def mr_egger(beta_e, se_e, beta_o, se_o, correlation_matrix=None): """ MR Egger implementation Args ----- beta_e: numpy array of beta-coefficient values for genetic associations with the exposure trait se_e: numpy array of the standard error associated with beta_e beta_o: numpy array of the beta-coeffi...
The function computes the MR-Trio negative squared error test statistic by predicting outcome values using a Two-Stage Least Squares (2SLS) approach with input genotypes and MR estimates. It calculates the negative squared error between predicted and true outcome values, using precomputed MR estimates (via IVW, Egger, ...
def compute_statistic(beta_e, se_e, beta_o, se_o, genotypes, outcome_trait, mr_method, mr_est=None): """ Computes the MR-Trio negative squared error test statistic. Outcome values are predicted via a Two-Stage Least Squares (2SLS) style approach using the input genotypes, and the negative squared error against th...
def mr_ivw(beta_e, se_e, beta_o, se_o): """ MR IVW implementation Args ----- beta_e: numpy array of beta-coefficient values for genetic associations with the exposure trait se_e: numpy array of the standard error associated with beta_e beta_o: numpy array of the beta-coefficient values for genetic as...
This function performs multiple Mendelian Randomization (MR) analyses using four distinct methods—IVW, median, Egger, and mode—on provided effect sizes and standard errors from exposure and outcome data. It returns results from each method, enabling comparison of causal effect estimates while accounting for potential b...
def mr_all_methods(beta_e, se_e, beta_o, se_o, weighted_p=True, it_p=10000, correlation_matrix=None, phi=1): ivw = mr_ivw(beta_e, se_e, beta_o, se_o) median = mr_median(beta_e, se_e, beta_o, se_o, it=it_p, weighted=weighted_p) egger = mr_egger(beta_e, se_e, beta_o, se_o, correlation_matrix) mode = mr_mode(beta_e, s...
def row_winner(board): return any(winning_line(row) for row in board) def column_winner(board): return row_winner(zip(*board)) def diagonal_winner(board): return main_diagonal_winner(board) or main_diagonal_winner(reversed(board))
The main task of the code is to determine the winner of a game by checking if any row, column, or diagonal on the provided board contains a winning condition. It combines results from three helper functions—row_winner, column_winner, and diagonal_winner—to identify and return the winner if one exists.
def winner(board): return row_winner(board) or column_winner(board) or diagonal_winner(board)
def get_connection(connection_file: str): """ Connect to the PostgreSQL database. Parameters: - connection_file: json file path to create a connection to PostgreSQL database - default_schema: Name of default schema """ with open(connection_file, "r") as f: conn_config = json...
The main task of the code is to download Wikimedia dump files for a specified date, convert them to CSV format, and import the data into a PostgreSQL database. It creates a raw data table, stores raw files in 'data/raw', CSV files in 'data/csv', and uses a connection file to interact with the database. The process incl...
def main(year: int, month: int, day: int, connection_file: str, table_name: str, hours = None): """ Download dump files from wikimedia source and convert them to csv, import them to PostgreSQL server. Create a raw data table based on the files downloaded. Raw dump files are saved in data/raw, CSV f...
def get_comb_bin(n, k): combs = [] for comb in range(1, int(pow(2, n))): if wanted_in_number(comb, k): s = [] for bit in range(n): s.append(get_bit(comb, bit)) combs.append(s[::-1]) return combs def get_coord_from_comb(coords, comb): ret = [] ...
The code calculates the maximum radius of non-overlapping triangles formed by selecting 3 points from a coordinate list, ensuring no other points lie inside the triangle. It generates all combinations of 3 points, checks for nested points, computes valid triangle radii, and returns the largest radius. If no valid trian...
def wifi(n, coords): radius = [] # get the list of all combinaisons (binairy list, ex : [0, 0, 1, 1, 0, 0, 1]) k = 3 combs = get_comb_bin(n, k) for i in combs: pos = get_coord_from_comb(coords, i) # check that the triangle has no nested point (dont ask why it's empirical) ...
def load_data(self): self.trades_data_df = pd.read_excel(self.xls_location, sheet_name='trade_data') self.summary_data_df = pd.read_excel(self.xls_location, sheet_name='summary_data') def generate_trade_duration_df(self): pd.set_option("plotting.backend", "plotly") #? duration_dataset ...
The main task of the code is to generate a comprehensive financial report by loading data, creating dataframes for trade duration, account balance, monthly trades, and profits, then compiling these into an HTML report. Each method processes specific data aspects, culminating in a structured, visualized summary for anal...
def generate_report(self): self.load_data() self.generate_trade_duration_df() self.generate_account_balance_df() self.generate_monthly_trades_df() self.generate_monthly_profits_df() self.build_html_report()
def fingerprint(item, fp_size=8): # take first fp_size bits as fingerprint to minimize false positives fp = mmh3.hash(item, signed=False) # default hash returns 32-bit fp = fp >> (HASH_SIZE-fp_size) # no need for mask for msb's if (fp == 0): fp = 1 # empty fingerprints are r...
The code checks if an item's fingerprint exists in a data structure using two hash functions and two blocks. It computes the fingerprint, hashes the item to determine block/bucket indices, checks the first block's OTA bit and matches. If not found, it uses a second hash to check a second block. Returns True if a match ...
def check(self,item,verbose=False): fp = fingerprint(item,self.fingerprint_size) glbi1 = self.h1(item) block1 = self.Blocks[glbi1//self.no_buckets] lbi1 = glbi1 % self.no_buckets ota_bit = block1.get_OTA(lbi1) if verbose: print(f"fp = {(int(fp,2))}, block1 = {...
def check_candidate_bucket(self,glbi,fp,verbose=False): """Returns true if candidate bucket is available.""" alternate_bucket = self.h_prime(glbi,fp) if (alternate_bucket == self.no_buckets*self.no_blocks): # indexing starts at 0 # raises ListIndexOutOfRange otherwise ...
This function resolves a fingerprint insertion conflict by evicting existing fingerprints to make space for a new fingerprint (fp) in a specified block and bucket. It iterates up to 8000 times, checking if candidate fingerprints can be moved to their alternate buckets. If no candidates are available, it randomly select...
def res_conflict(self,blk1,lbi1,fp,verbose=False): # we want to insert fp in its blk1 and lbi1 position max_count = 8000 # max times we can try evicting a fingerprint count = 0 # current count evicted = False fp = BitArray(fp) while(count<max_count and not evicted): ...
def fingerprint(item, fp_size=8): # take first fp_size bits as fingerprint to minimize false positives fp = mmh3.hash(item, signed=False) # default hash returns 32-bit fp = fp >> (HASH_SIZE-fp_size) # no need for mask for msb's if (fp == 0): fp = 1 # empty fingerprints are r...
The code implements an insertion operation in a Bloom filter using cuckoo hashing. It checks if an item exists, computes two hash values (h1, h2), and inserts the item's fingerprint into the corresponding bucket. If the primary bucket (h1) is full, it attempts insertion via the secondary hash (h2). If both buckets are ...
def insert(self,item,verbose=False): fp = fingerprint(item,self.fingerprint_size) if (self.check(item)): if verbose: print(f"item: {item} already in filter") return # if item seems already in the filter,don't add it again # that would cause duplicates ...
def calculate_valid_moves(self, char): valid_moves = [] for row in range(8): for col in range(8): if self.board[row][col] != '-': continue for row_dir in range(-1, 2): for col_dir in range(-1, 2): ...
This function prompts the user for a valid move based on the current player's available options, validates the input against precomputed moves, and returns the chosen move after ensuring it is合法. It handles turn announcements, move validation, and user input correction in a game context.
def query_for_valid_move(self, char): print("Looks like it is {}'s turn!".format(char)) valid_moves = self.calculate_valid_moves(char) if len(valid_moves) == 0: print("There are no moves available for them :(") return None self.print_self(valid_moves) mov...
def score_board(self, board): score = 0 # use value matrix to calculate score if self.pieces_remaining > 40: for row in range(8): for col in range(8): if board[row][col] == self.whitechar: score += self.early_matrix[row][col...
This function implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a player in a strategic board game. It evaluates all valid moves recursively, alternating between maximizing and minimizing players, and uses pruning to improve efficiency by cutting off branches where the score can...
def minimax(self, board, depth, alpha, beta, is_maximizing): if depth == 0: return self.score_board(board) if is_maximizing: char = self.whitechar else: char = self.blackchar valid_moves = self.calculate_valid_moves(board, char) if len(valid_...
def count_pieces(self, board): pieces_remaining = 64 for row in range(8): for col in range(8): if board[row][col] == self.whitechar or board[row][col] == self.blackchar: pieces_remaining -= 1 return pieces_remaining def copy_board(self, board): ...
The function determines the optimal move for a player in a board game using the minimax algorithm with alpha-beta pruning. It evaluates each valid move by simulating the game state, calculates scores recursively, and selects the move with the highest (for white) or lowest (for black) score. The depth of the search adju...
def get_ideal_move(self, char : str, valid_moves : list, board): self.complete = False self.pieces_remaining = self.count_pieces(board) if char == self.whitechar: self.our_color = self.whitechar else: self.our_color = self.blackchar if len(valid_moves) =...
def get_json(self, url: str) -> Union[List,Dict]: self.logger.debug(f"fetching json: {url}") try: r = requests.get(url) if r.status_code == 200: return r.json() except requests.exceptions.ConnectionError as e: self.logger.error(f"connection er...
The code processes an account by fetching its data from a URL, saving the JSON data to a local directory, and then processing all associated characters. It logs the start and completion of the account processing task.
def process_account(self, account_id: str): self.logger.info(f"processing account: {account_id}") data = self.get_json(f'{self.base_url}/{account_id}') account_path = self.data_path / str(account_id) account_path.mkdir(exist_ok=True) (account_path / f"_.json").write_text(self....
def navigate_to_checkout_step_one(driver, items): navigate_to_cart(driver, items) clickById(driver, CHECKOUT) def enter_user_details(driver, first, last, postal_code): driver.find_element(By.ID, FIRST_NAME).send_keys(first) driver.find_element(By.ID, LAST_NAME).send_keys(last) driver.find_element(By...
The function automates navigating from checkout step one to step two by entering user details (first name, last name, postal code) and clicking the "Continue" button, facilitating a web checkout process.
def navigate_to_checkout_step_two(driver, items, first="P.A.", last="Consulting", postal_code="EC1M 3HE"): navigate_to_checkout_step_one(driver, items) enter_user_details(driver, first, last, postal_code) clickById(driver, CONTINUE)
def print_welcome(): """ Prints a welcome message describing what the program does. :return: None """ print("Welcome to the Electricity Usage Calculator\n") print("This program will determine the electricity usage and energy costs" "of\nyour electrical devices, taking the price of your...
The code calculates and displays energy consumption and costs for multiple devices by collecting user input on device usage, computing individual and total watt hours, energy costs, and averages, then outputting detailed device data and aggregated totals including converted energy prices.
def main(): device = None total_hours_used = 0.00 total_watt_hours = 0.00 avg_watt_hours = 0.00 energy_price_kWh = 0.00 another = True devices = [] print_welcome() energy_price_kWh = prompt_energy_price() while (another == True): # Inputs device = get_device(de...
def print_message(ask, prefix='', speed=0.04): print(prefix, end='') for i in range(len(ask)): sys.stdout.flush() print(ask[i], end='') sleep(speed) return sleep(0.3) def request(ask, hide_input=False): return input(f'{ask}: ') if hide_input else input(f'{ask}: ') def create_cred...
The function displays a user's accounts. If none exist, it prompts to create one; if accounts exist, it lists them. Returns True if accounts are present or creation is initiated, else False.
def show_accounts(user): accounts = user.view_accounts() if not accounts: print_message("\nYou have no accounts\n\n") action = request("Do you want to create one? [Y/n]") if action == 'y' or action == '': return create_credentials(user, request("Enter name of the account")) ...
def request(ask, hide_input=False): return input(f'{ask}: ') if hide_input else input(f'{ask}: ') def print_message(ask, prefix='', speed=0.04): print(prefix, end='') for i in range(len(ask)): sys.stdout.flush() print(ask[i], end='') sleep(speed) return sleep(0.3) def print_accou...
The main task of the code is to allow a user to edit an existing account's username and password by prompting for input, updating the account if it exists, and handling errors if the account is not found, with a recursive retry mechanism.
def edit_account(user, count_error=0): account_name = request("Which account do you want to edit?") user, account = user.get_account(account_name) if account: username = request(f"Enter new username for {account_name}") password = request(f"Enter new password {account_name}") new_a...
def request(ask, hide_input=False): return input(f'{ask}: ') if hide_input else input(f'{ask}: ') def print_message(ask, prefix='', speed=0.04): print(prefix, end='') for i in range(len(ask)): sys.stdout.flush() print(ask[i], end='') sleep(speed) return sleep(0.3) def show_accoun...
The main task of the code is to delete a specified account from a user's account list. It prompts for an account name, attempts deletion via the `delete_account` method, and displays success or error messages. If deletion fails (no such account), it recursively re-prompts the user to try again, ensuring the account lis...
def delete_account(user): account_name = request("Enter account name to delete") accounts, deleted = user.delete_account(account_name) if deleted: print_message( f"{account_name} account deleted successfully!\n") show_accounts(user) else: print_message("No such accoun...
def print_message(ask, prefix='', speed=0.04): print(prefix, end='') for i in range(len(ask)): sys.stdout.flush() print(ask[i], end='') sleep(speed) return sleep(0.3) def create_user(): email = request('Enter email address') password = request('Enter password') new_user =...
The code implements a Pass Locker App with user registration, login, and account management features. It allows users to create, view, edit, delete accounts, and navigate via shortcodes (c, s, e, d, q). The app clears the console, displays messages with delays, and handles user interactions through a loop with specific...
def main(): os.system('cls|clear') sleep(0.8) print_message("Hello! ") sleep(0.8) print_message("Welcome to Pass Locker App\n") sleep(0.8) print_message('Please register below\n\n') create_user() print("\nPlease login...") user, logged_in = user_login() os.system('cls|clear'...
def possible_codon(self, key, alleles): '''generate a list of possible codon with given position and allele list''' codon = {} possible_cdn_list = [] ref = key.split("-")[2] print(key) possible_cdn_freq_list = [] possible_cdn_list = [] if not ref: ...
The main task of the code is to calculate the dn/ds ratio by analyzing variant and codon data. It reads variant information from a TSV file, processes codon data, identifies synonymous and non-synonymous mutations, computes site counts and differences, and finally calculates the dn/ds ratio using these statistics.
def generate_statistics(self, varinat_info_file, codon_info_file, all_possible_codon): ''' :param varinat_info_file: :param codon_info_file: :param all_possible_codon: :return: ''' '''read data from variant_info.tsv file''' data_dict = {} with ope...
def check_counterexample_negative_target(model, args, neg_target, nb_updated_extensions,semantics): args, atts = decode_model_as_af_struct(model,args,nb_updated_extensions) for neg_arg in neg_target: if solvers.credulous_acceptability(args,atts,neg_arg,semantics): return True return Fals...
The function checks for counterexamples in a model by evaluating three conditions: negative targets, conjunctive positives, and conjunctive negatives. It combines results using logical OR, returning True if any check identifies a counterexample. Parameters include the model, arguments, target, conjunctive clauses, upda...
def check_counterexample(model, args, neg_target, conjunctive_positive, conjunctive_negative, nb_updated_extensions, semantics): return check_counterexample_negative_target(model, args, neg_target, nb_updated_extensions,semantics) or check_counterexample_conjunctive_positive(model, args, conjunctive_positive, nb_up...
def findattackmode(self,var): if var == 0: return None elif var == 1: return 'selfish' elif var == 2: return 'stubborn' else: print("Enter Valid Attack Type") exit(0) def setnodes(self, var): #calculate number of nodes f...
This code initializes a class by reading parameters from a file, setting configuration values (e.g., node counts, time limits, attack modes), constructing data structures (lists, graphs), and preparing simulation components like peer networks, node classifications, and initial blockchain states. It processes input data...
def __init__(self, path): # Open the file at the given path file = open(path, "r") # Initialize an empty list called parameter_list parameter_list = [] for line in file: # If the first character in the line is not a "#" character if line[0] != "#": ...
def selfishattack(self, prevhash): if self.lead != 0: self.notBroadcasted.sort() blkdict = self.notBroadcasted[0][1] for _, blk in blkdict.items(): parent = blk['previous_hash'] if parent == prevhash: if self.lead == 1: ...
This function integrates a new block into the blockchain by checking if the node is selfish or stubborn, potentially generating blocks to broadcast. It adds the block to the BlockTree, verifies its validity, and processes parent blocks from a record. If valid, it updates the blockchain, ensuring the longest chain is ma...
def AddBlocktoBlockTree(self, blockdata, blockhash, prevhash, currenttime): #check if selfish block has to broadcast or not. if self.ishonest == False: broadcastlist = [] res = self.selfishattack(prevhash) if res: broadcastlist.extend(r...
def UpdateAccountStatus(self, blockhash): parent = blockhash AccountStatus = {} #parent of current chain generator = self.BlockTree[parent][0]['generator'] #loop untill Genesis block reached while(parent != 'Root'): #check if transactions are present in block,...
This code processes incoming blockchain events (transactions or blocks) by validating and adding them to the blockchain structure. It checks for duplicates, verifies block transactions against parent chain data, and conditionally adds valid blocks to the BlockTree while handling dishonest node behavior.
def ReceiveEvent(self, Event): DataId = Event[6] #check if event is block or Transaction if Event[4] == 'Tx': if DataId not in self.Transactions: #add to transactions list self.Transactions[DataId] = Event[5] return True, None ...
def indiceNod(self, n): if len(n) == 4: return int(n[2:4]) else: return int(n[2]) def poateIesi(self, broscuta, w): if broscuta[0] is not None: i = self.indiceNod(broscuta[0]) dist = self.lista_h[i] print(dist) if dist <= (...
This function performs backtracking to explore possible moves of frogs (broscute) on lily pads (frunze), generating new states by either exiting directly or jumping between pads. It recursively explores all valid transitions, tracks state changes, and calculates path costs (g) and heuristic values (h) to create new nod...
def backt(self, k, stare_broscute, stare_frunze, nodCurent): print("pas", k) if k < len(stare_broscute): print(k, stare_broscute[k][0]) for i in range(len(stare_frunze)): print(k) if stare_broscute[k][0] is not None: id_frunza_c...
def print(*args, **kwargs): if gShowMsg: return __builtin__.print(*args, **kwargs) def ParseBlock( blockBytes, compressed, crcBytes ): if compressed == 1: blockBytes = snappy.uncompress( blockBytes ) kvPair = dict() try: numRestarts = blockBytes[ -1 ] stream2 = io.BytesIO( blockBytes[ : -1 * (1 + 4 * numRe...
The code parses an LDB file by validating its footer, extracting meta-index and index blocks using varint decoding, parsing their contents with ParseBlock, and dumping key-value pairs. It returns the parsed index block data after verifying the file's integrity and structure.
def ParseLdbFile( fLdb ): try: with open( fLdb, "rb" ) as f: ldbBytes = f.read() except Exception as e: print( "[E] Can't read file " + fLdb + " (" + str( e ) + ")" ) return None if ldbBytes[ -8 : ] != LDB_FOOTER_BYTES: print( "[E] Not a valid LDB file: can't find footer!" ) return None print( 'Dump ...
def DownloadSheetExist(): return os.path.isfile( os.path.join( gOutDir, DOWNLOAD_SHEET ) ) def DeleteBook( bookId ): if not bookId in gBookData.keys(): print( "[E] Can't delete book: wrong book ID " + bookId ) return False print( " Delete book: " + bookId ) result = True bookFile = os.path.join( gOutDir...
The main task of the code is to parse a download sheet file, categorize book IDs into deletion, decryption, and download lists based on markers, execute these operations (delete, decrypt, download), track results, and rename the processed sheet as a backup. It handles errors, logs statuses, and ensures directory struct...
def ProcessDownloadSheet(): if not DownloadSheetExist(): print( "[E] Download sheet not exist!" ) return False dls = os.path.abspath( os.path.join( gOutDir, DOWNLOAD_SHEET ) ) print( "[I] Parse download sheet" ) todl = [] torm = [] todec = [] try: for line in open( dls, "r", encoding="utf8" ): if line...
def DownloadSheetExist(): return os.path.isfile( os.path.join( gOutDir, DOWNLOAD_SHEET ) ) def DeleteBook( bookId ): if not bookId in gLibraryItems.keys(): print( "[E] Can't delete book: wrong book ID " + bookId ) return False print( " Delete book: " + bookId ) result = True bookFile = os.path.join( gOu...
The main task of the code is to process a download sheet file to manage book operations (deletion, decryption, and downloading) based on marked entries. It checks directory existence, parses the sheet's entries, categorizes book IDs into action lists, executes corresponding operations (delete, decrypt, download), and t...
def ProcessDownloadSheet(): if not DownloadSheetExist(): print( "[E] Download sheet not exist!" ) return False bookDir = os.path.join( gOutDir, ENC_BOOKS_DIR ) if not os.path.isdir( bookDir ): try: os.makedirs( bookDir ) except: print( "[E] Can't create directory: " + os.path.abspath( bookDir ) ) r...
def encode_inputs(config, bert_config_file, bert_check_point_file, adapter_size=None): """Creates a classification model.""" inputs = [] modality_outputs = [] image_models = [] has_bert_modality = False if "bert" in config["text_models"]: has_bert_modality = True if has_bert_modal...
This code creates a multi-modal classification model by fusing input features through dense layers, batch normalization, and ReLU activation. It integrates BERT for text processing, dynamically adjusts feature dimensions, and applies softmax for two-class classification. The model uses specified optimizers, loads pre-t...
def get_model(config, bert_config_file, bert_check_point_file, adapter_size=None): """Creates a classification model.""" inputs, modality_outputs, has_bert_modality, bert = encode_inputs(config, bert_config_file, bert_check_point_file, adapter_size) outputs = [] if len(modality_outputs) > 1: co...
def apply_oversampling(ids, labels, text_docs): count = {'HOF':0, 'NOT':0} label_to_ids = {'HOF':[], 'NOT':[]} c = 0 for l in labels: count[l] +=1 id = ids[c] label_to_ids[l].append(id) c+=1 oversampled_ids, oversampled_labels, oversampled_text_docs = [], [], [] ...
This function processes text data for machine learning by extracting features using specified models (BERT, hate words, character embeddings), applying normalization and oversampling if configured, encoding labels, and returning processed features, labels, and document IDs for model training/evaluation.
def load_split(config, df, bert_tokenizer, hate_words, text_preprocessor, oversample:bool): X, y = {}, {} ids = df["id"].tolist() labels = df["label"].tolist() text_docs = df["text"].tolist() if oversample: ids, labels, text_docs = apply_oversampling(ids, labels, text_docs) if config[...
def keplerian_elements_from_rv(r,v,GM): """ Find orbital parameters and phase of an orbit, given position and velocity (vectors). INPUTS: r : position vector v : velocity vector GM : gravitational parameter, acceleration = -GM/r^2 OUTPUTS: ecc_vec : eccentricity vector ...
The function simulates the hierarchical motion of three bodies by independently advancing the outer and inner orbits using Keplerian elements. It calculates the center of mass and relative positions/velocities for both binaries, computes their orbital parameters, flips the outer orbit's true anomaly, and advances the i...
def double_keplerian_motion(R,V,i,M,G): """ Given 3 bodies in an hierarchical triplet, advance the outer orbit to the point reflected by semi-major axis (f -> 2*pi-f), in an unpertubed way (i.e., not interaction between inner and outer orbits). Advance inner orbit according to the time passes. ...
def get_ecr_repositories( client: boto3.client, registry: str ) -> list: # pragma: no cover """ :param client boto3.client: :param registry str: Gets a list of image repositories in a registry :return repositories list: """ logging.debug("Attempting to retrieve a list of repositories in...
The main task of the code is to identify and delete unused Amazon ECR container images not referenced by Kubernetes workloads. It retrieves ECR repositories/images, compares them against Kubernetes workload images, separates deletable/keepable images, logs results, and deletes unused ECR images while handling AWS confi...
def main(): # pragma: no cover deletable_images = [] keepable_images = [] try: config.load_kube_config() except config.config_exception.ConfigException: config.load_incluster_config() client = boto3.client("ecr") if os.getenv("AWS_REGISTRY_ID"): registry_id = os.getenv(...
def createInitState(self, frontier): p = self.map.getCell(self.map.p) q = self.map.getCell(self.map.q) frontier.append(StateB(p, q, None, None, len(self.map), None, 0)) self.startPoint = frontier[0] def getAdjacents(self, curState): res = deque([]) p = curState.p ...
This code implements a breadth-first search (BFS) algorithm to find a target node with a result of 0. It tracks metrics like search depth, number of expanded nodes, and maximum fringe size. The algorithm initializes the frontier, explores nodes level-by-level, and records the path if the target is found. If no path exi...
def run(self): tic = time.time() visited = set() frontier = deque([]) self.createInitState(frontier) while frontier.__len__(): curNode = frontier.popleft() visited.add(curNode) # print(curNode.depth) if curNode.result == 0: ...
def createInitState(self): p = self.map.getCell(self.map.p) q = self.map.getCell(self.map.q) self.startPoint = StateA(p, q, None, None, len(self.map), None, 0) def astar(self): frontier = [self.startPoint] heapify(frontier) came_from = {self.startPoint: None} cost...
The code's main task is to execute the A* algorithm, measure its runtime, and display the solution path and performance metrics. It initializes the problem state, runs the A* search, records execution time, retrieves the found path, and outputs the results and performance analysis.
def run(self): print("Let's rock") self.createInitState() # Let's rock tic = time.time() self.astar() print('OK I found something :)') self.getPath() toc = time.time() self.show_performance(toc - tic) self.showResult()
def load_data(): X1 = [] X2 = [] X3 = [] X4 = [] ClassName = [] file_name = open("E:\\books\\last year\\ANN\\Labs\\Lab3\\Task\\Task1\\IrisData.txt", "r") file_name.readline(); for line in file_name: split_line = line.split(",") ...
The code preprocesses data for a perceptron classifier by separating features and labels of two classes, splitting data into training/test sets, training the model with specified parameters, evaluating performance, and returning confusion matrix and accuracy.
def Preprocssing (Class1,Class2,feature1,feature2,epochs ,learning_Rate,bias): #extract classes & features X1,X2,X3,X4,ClassName=load_data() X_Dictionary={"X1":X1,"X2":X2,"X3":X3,"X4":X4} ClassName1=[] ClassName2=[] feature1_C1=[] feature2_C1=[] feature1_...
def stock_watch_event(self, jsonObject): isin = jsonObject.isin if isin not in self.candidates: if isin not in self.portfolio: return if isin in self.candidates: print(" [x] Market Data (StockWatch) of candidate Received %r" % jsonObject) candi...
This function processes incoming market data messages by parsing JSON content and triggering specific event handlers based on the data type: stock trades, bid/ask quotes, or client info, ensuring proper routing of market updates for further processing.
def marketDataCallBack(self, ch, method, properties, body): try: # print(" [x] Market Data Received %r" % json.loads(body)) jsonStr = json.loads(body) # if 'instrumentId' in jsonStr: # self._trade_event_process(jsonStr) if 'lastTrade' in jsonStr: ...
def create_quick_panel_file_list(self, files_obj): quick_panel_files = [".."] if len(files_obj) == 0: ignore_patterns = self.settings.get("ignore_patterns", []) files_list = list_package_files(self.package, ignore_patterns) for entry in files_list: sel...
This function handles user selection from a package list by retrieving the selected package, applying ignore patterns, generating a file list for quick panel display, updating the file path tracking, and opening a quick panel for further file navigation or actions.
def package_list_callback(self, index): if index == -1: return self.package = self.packages[index] ignore_patterns = self.settings.get("ignore_patterns", []) self.package_files = {} self.quick_panel_files = self.create_quick_panel_file_list(self.package_files) ...
def pop_entry_from_path_obj(self): if len(self.path_objs) > 0: if len(self.path) > 0: self.path.pop() self.path_objs.pop() def show_quick_panel(self, options, done_callback, index=None): if index is None or not IS_ST3 or not self.settings.get("return_to_previous",...
This code handles file navigation in a package by updating the UI based on user selection. It processes directory traversal ("..") to backtrack, opens files when selected, and updates the quick panel with file lists from the current directory. It manages path tracking, file checks, and view setup for opened files, supp...
def package_file_callback(self, index): if index == -1: return entry = self.quick_panel_files[index] if entry == "..": if len(self.path_index) != 0: index = self.path_index.pop() self.pop_entry_from_path_obj() if len(self.path_objs...
def send_command(self, command): self.digital_write(self.dc_pin, 0) self.digital_write(self.cs_pin, 0) self.spi_writebyte([command]) self.digital_write(self.cs_pin, 1) def send_data1(self, data): self.digital_write(self.dc_pin, 1) self.digital_write(self.cs_pin, 0) ...
The code's main task is to display two images (black and red) on a screen by sending them to the display via specific commands (0x10 and 0x13) after validating their existence, then enabling the display.
def display(self, imageBlack, imageRed): if (imageBlack == None or imageRed == None): return self.send_command(0x10) # WRITE_RAM self.send_data1(imageBlack) self.send_command(0x13) # WRITE_RAM self.send_data1(imageRed) self.TurnOnDisplay()
def send_command(self, command): self.digital_write(self.dc_pin, 0) self.digital_write(self.cs_pin, 0) self.spi_writebyte([command]) self.digital_write(self.cs_pin, 1) def send_data1(self, data): self.digital_write(self.dc_pin, 1) self.digital_write(self.cs_pin, 0) ...
The code clears a display by writing black and red pixel data to specific memory areas. It sends commands to write RAM, iterates over columns (width/8), and fills each column with black or red pixels repeated for the height. Finally, it activates the display to show the cleared content.
def Clear(self, colorBalck, colorRed): self.send_command(0x10) # WRITE_RAM for i in range(0, int(self.width / 8)): self.send_data1([colorBalck] * self.height) self.send_command(0x13) # WRITE_RAM for i in range(0, int(self.width / 8)): self.send_data1(...
def get_auth_requirements(server, username, password): r = requests.post('https://' + server + '/cvpservice/login/authenticate.do', auth=(username, password), verify=True is False) r.json()['sessionId'] token = r.json()['sessionId'] with open("cvp.crt", "w") as f: f.write(...
This script processes a CSV file to create, apply, or remove tags in Arista CloudVision (CVP) for configuring L3 Leaf-Spine switches. It connects to CVP using credentials or a token, maps device tags from the CSV, retrieves device serial numbers, and applies or removes tags based on the specified action ("apply" or "re...
def main(): parser = argparse.ArgumentParser(description="This script will create/apply or remove " \ "the tags required for CloudVision's L3 Leaf-Spine studio " \ "to generate configuration for a switch") parser.add_argument("--csv-file", ...
def __create_temp_reach_dict(self, num_reaches): """Create a dict to initialize numpy arrays for reach-level priors.""" sos = Dataset(self.sos_file, 'r') gbpriors = sos["gbpriors"]["reach"] reach_dict = { "river_type" : gbpriors["river_type"][:].filled(self.INT_FILL), ...
This method processes SWOT data files to compute geoBAM priors for reaches and nodes. It initializes temporary storage, iterates through SWOT files, extracts reach/node data, runs the GB algorithm, calculates priors, and stores them in dictionaries. Exceptions are handled by skipping failed files. Final priors are save...
def run_gb(self): """Executes geoBAM on reach and node data and stores priors.""" num_reaches = self.sos_dict["reach_id"].shape[0] num_nodes = self.sos_dict["node_id"].shape[0] reach_temp_dict = self.__create_temp_reach_dict(num_reaches) node_temp_dict = self.__create_node_temp_...
def draw_roads(self): for road in self.simulation.roads: self.draw_box(road.start, (road.length, 3.7), sin=road.sin, cos=road.cos, color=(180, 180, 220), centered=False) if road.length > 5: for i in np.arange(-0.5 * road.length, 0.5 * road.lengt...
The code's main task is to render a visual scene by clearing the screen with a background color and sequentially drawing roads, vehicles, traffic signs, RSUs (Roadside Units), and status elements. This function updates the display for a simulation or graphical interface, ensuring all components are rendered in the corr...
def draw(self): self.screen.fill(self.background_color) self.draw_roads() self.draw_vehicles() self.draw_signs() self.draw_rsus() self.draw_status()
def check_movement(self, ch): """Checks if an arrow key or movement was pressed and carries out movement""" # Movement if ch == curses.KEY_UP: # Up self.csr.up(self.buf) self.win.up(self.csr) self.win.horizontal_scroll(self.csr) ...
This code processes editing commands in a text editor using the curses library. It handles movement, insertion of printable characters, deletion, and exit/save operations. The function modifies the text buffer based on user input, updates the cursor position, and returns status codes for different actions like saving o...
def do_command(self, ch): """Taken from Python curses.textpad module. Process single editing command""" # Movement if self.check_movement(ch): return 1 # Printable if ch == ord('\n'): # Newline self.buf.split(se...
def _checkInputName(self, name): try: i = self.extNames.index(name) except: raise ValueError('Input name must be in {}'.format(self.extNames)) return i def getMap(self, name): """Extracts an image from the Fits file. The image is referenced by its ext...
This function subtracts a kernel-shaped source from an image by fitting a Gaussian to determine the source's position and amplitude (if enabled), generating a scaled kernel via interpolation, and subtracting it from a local image cutout. It uses input parameters or defaults, retrieves necessary data, and returns the mo...
def subtractKernelFromImage(self, name, image=None, sourcePos=None, sourceAmp=None, fitForVals=False): """Subtract a kernel shaped source from an image. Inputs: - name (string), the EXTNAME of the image or corresponding WCS. ...
def _checkInputName(self, name): try: i = self.extNames.index(name) except: raise ValueError('Input name must be in {}'.format(self.extNames)) return i def getMap(self, name): """Extracts an image from the Fits file. The image is referenced by its ext...
This function adds a kernel-shaped source to an image using specified parameters. It retrieves the image, defaults to the image's center if no position is provided, constructs a kernel via interpolation, scales it by the given amplitude, and returns the modified image with the kernel added.
def addKernelToImage(self, name, image=None, sourcePos=None, sourceAmp=1.0): """Add a kernel shaped source from an image. Inputs: - name (string), the EXTNAME of the image or corresponding WCS. - image [array], optional - an input image with same WCS as "name" ...
def _checkInputName(self, name): try: i = self.extNames.index(name) except: raise ValueError('Input name must be in {}'.format(self.extNames)) return i def getMap(self, name): """Extracts an image from the Fits file. The image is referenced by its ext...
This function subtracts kernel-shaped sources from an image using a PyBDSF catalog, applying flux correction and thresholding. It reads catalog data, converts source positions to pixel coordinates, and iteratively subtracts qualifying sources (above flux limit) from the image using a kernel subtraction method, returnin...
def removeBdsfCatalogFromImage(self, name, image=None, catFile=None, fluxLimit=0., fluxCorr=1.0): """Subtract a kernel shaped source from an image. Inputs: - name (string), the EXTNAME of th...
def rand_color(self): r = random.randint(1,255) g = random.randint(1,255) b = random.randint(1,255) return (r,g,b) def unpackeging(self,l,data): strct = '1s 2s 1s 1s 2s 2s ' # +id + pointy s = '1s 1s 2s 2s' o = '1s' # + direction for projectile p...
This code implements a UDP-based multiplayer game thread using Pygame. It initializes game elements, handles UDP communication for player/projectile data exchange, updates game state, renders graphics, and maintains a 30 FPS loop. The thread sends player positions, receives and processes game data, updates entities, di...
def udp_thread(self): print("[GAME STARTED]") print("[STARTED UDP]") pygame.init() screen = pygame.display.set_mode((int(self.weight), int(self.weight))) font = pygame.font.SysFont("comicsans", 80) score = pygame.font.SysFont("comicsans", 30, True) # visibility ? ...
def added_call_time_Adjuster(self, added_call, timeStamp): # Added the timeStamp to adjust by call_src = added_call.originFloor call_dest = added_call.destFloor stop_time = self.stoptime + self.opentime + self.speed start_time = self.starttime + self.closetime + self.speed floor...
This function adds a new call to a system, either as the first call (when the call list and floor timestamps are empty) or when the call is within the system's range. It adjusts the call's timestamp using `added_call_time_Adjuster` and updates the call list and count. If the list isn't empty, it directly appends the ca...
def addCall(self, call): if len(self.callList) == 0: # If the list is empty empty = True for i in range(self.minFloor, self.maxFloor + 1): if self.floor_timestamp_dict[i] != 0.0: empty = False if empty: # call is a FIRST call and dict is ...
def make_df(file): # creating the csv file dataframe = pd.read_csv(file) # now we are going to sort out the columns # making header columns so we can work with the csv col = dataframe.columns # saving all the columns names dataframe.loc[-1] = [col[0], float(col[1]), int(col[2]), int(col[3]), 0,...
The code processes elevator call requests from a CSV file and assigns each call to an appropriate elevator in a building. It initializes building and elevator data, iterates through calls, and determines the optimal elevator for each request based on direction (UP/DOWN), timestamps, and elevator schedules. The algorith...
def Ex1(Building_json, call_csv): building_b = Building(Building_json) # WORKS elev_list = building_b.ElevatorList # WORKS call_file = make_df(call_csv) # WORKS # call_file.to_csv("call_file", index=False)/////////////////////////////// size = len(call_file) # size = 100 # WORKS data = {'sta...
def fitGaussian(self, x, y, num_features, num_mixture_components): alpha = [0] * num_mixture_components mu = [np.zeros((num_features, 1))] * num_mixture_components sigma = [np.zeros((num_features, num_features))] * num_mixture_components for i in range(x.shape[0]): #if is_lab...
This code implements a semi-supervised Gaussian Mixture Model (GMM) with PCA dimensionality reduction. It initializes Gaussian components based on labeled data, iteratively predicts labels for unlabeled samples using current component probabilities, refines GMM parameters via maximum likelihood, and stops when validati...
def fit(self, x, y): # Assuming there are as many mixture components as labels num_mixture_components = np.max(y) + 1 num_samples = x.shape[0] num_features = self.PCA_dim print(x.shape) print(y.shape) x,y = shuffle(x, y) # standardize input if ...
def stripExt(name): index= name.rfind('.') if index != -1: return name[ : index ] else: return name def load_obj(filepath, context): print(' INFO: Start Geometry') time_main= time.time() scene= bpy.context.scene SCL = scene.SCL verts_loc= [] verts_tex= [] faces= [] vertex_groups = {} #pri...
This code imports 3D scene data by setting the scene path, adjusting scale parameters, and loading geometry (.obj), scene (.scn) files, and animation data based on context properties. It strips file extensions, handles conditional imports, joins materials, and outputs completion status.
def execute(self, context): scene = context.scene scene.path = self.properties.filepath if scene.SCL< 0.01 : scene.SCL=0.01 namefile=stripExt(self.properties.filepath) print(namefile) if scene.IMPORT_GEOMETRY: load_obj(namefile+'.obj', context) load_Scn(namefile+'.scn') ###parent(namefile+'.sc...
def word_input(input): word_list = input.split(' ') for data in word_list: letter_writer(data) writer('space') def writer(letter): global gap, _ if letter == '\n': pass else: letter.lower() if letter == "": return cases = Image.open(f"{FONT...
The code converts text from a file into images using a specified font, splits the text into chunks, generates PNG images for each chunk, compiles them into a PDF, and returns the list of image paths. It handles text processing, image creation, and PDF generation, using a background image and dynamic file management.
def converter(font="font"): global BG, sizeOfSheet, allowedChars, gap, FONT FONT = font p = 0 export_path = str(uuid.uuid4()) if not os.path.exists(export_path): os.mkdir(export_path) try: with open(f'{OUTPUT_FILE}', 'r') as file: data = file.read().replace('\n', ' ')...
def update_possible(self, brute_force = False): for row in range(9): for col in range(9): if self.__solver_grid[row, col] == 0: self.possible_values.iat[row, col] = self.get_possible(row, col) else: self.possib...
This function solves a Sudoku puzzle using a brute-force approach by generating permutations of possible values for the current row, checking for uniqueness and validity, and recursively solving subsequent rows until the grid is fully solved or all possibilities are exhausted.
def solve_bruteforce_aux(self, current_row): print("Trying row: ", current_row) row = self.possible_values.iloc[current_row, :] missing_lists = [val for val in row if val is not None] permutations = list(itertools.product(*missing_lists)) grid = self.__solver_grid.copy() ...
def get_possible(self, row, col): possible_values = set(range(1, 10)) whole_row = self.__solver_grid[row, :] whole_col = self.__solver_grid[:, col] whole_box = self.get_box(row, col) available = possible_values - set(np.concatenate((whole_row[whole_row>0], whole_col[whole_col>...
The main task of the code is to solve a Sudoku puzzle by iteratively filling empty cells with valid numbers. It checks each cell for possible values, assigns them if unique, and applies constraints (rows, columns, boxes) to eliminate invalid options. If stuck, it prints the state and exits unless guessing is enabled. T...
def solve(self, guess = False): while not self.__solved: added = False for row in range(9): for col in range(9): if self.__solver_grid[row, col] == 0: available_values = self.get_possible(row, col) # I...
def update_possible(self, brute_force = False): for row in range(9): for col in range(9): if self.__solver_grid[row, col] == 0: self.possible_values.iat[row, col] = self.get_possible(row, col) else: self.possib...
This code implements a brute-force Sudoku solver. It first fills in cells with only one possible value (if add_easy is True). Then, it generates permutations of missing numbers for the first row, tests each permutation by filling the row, and recursively solves the rest of the grid. If a valid solution is found, it pri...
def solve_bruteforce(self, start=0, add_easy = False): if add_easy: while True: self.update_possible() added = False for row in range(9): for col in range(9): val = self.possible_values.iloc[row, col] ...
def instatiateNets(self, applyEmbedder, applyClassifier, load_prev:bool, ckpt_dir='model'): self.rng = jax.random.PRNGKey(42) # self.conv_net = hk.transform(CNN) self.applyClassifier = hk.transform(applyClassifier) self.applyEmbedder = hk.transform(applyEmbedder) # paramsCNN =...
This code trains an embedder and classifier networks using gradient descent. It iterates over epochs, processes data in batches, computes losses, updates model parameters with gradients, records training losses, saves checkpoints every 10 epochs, and visualizes loss curves. The core task is joint optimization of embedd...
def trainingLoop(self,applyEmbedder, applyClassifier, epochs=30, batch_size=256, learning_rate=1/1e4, ckpt_dir='model'): # params = self.conv_net.init(self.rng, self.X_train[:5]) print("Starting Training...") if not self.wasInitiated: params_classifier, params_...
def instatiateNets(self, applyEmbedder, applyClassifier, load_prev:bool, ckpt_dir='model'): self.rng = jax.random.PRNGKey(42) # self.conv_net = hk.transform(CNN) self.applyClassifier = hk.transform(applyClassifier) self.applyEmbedder = hk.transform(applyEmbedder) # paramsCNN =...
This code evaluates a trained model by predicting on training and test datasets, calculates accuracy scores, and generates a classification report. It restores model parameters from a checkpoint, processes predictions, and compares them against true labels to assess performance.
def predictionAndTest(self, ckpt_dir='model'): if not self.wasInitiated: _, _ = self.instatiateNets(applyEmbedder, applyClassifier, load_prev=False) params_classifier, params_embedder = self.restore_model(ckpt_dir=ckpt_dir) train_preds = self.MakePredictions(params_classifier...
def init_pop(population,fitness,start_point,end_point,chromosome_size,pop_size,grid): for i in range(pop_size): # Initialize a chromosome with random genes genes = [] for _ in range(chromosome_size): gene = (random.randint(0, 39), random.randint(0, 39)) while is_ob...
This code implements a genetic algorithm to find the optimal path on a grid from a start to end point. It initializes a population of chromosomes, evaluates fitness, selects parents via roulette wheel, generates offspring through crossover and mutation, and replaces the population with the fittest individuals. The algo...
def GA(grid,goal_val,cost): # ----------------------------STEP 1: Initilaize Population-------------------- # Defined the size of the population and chromosome pop_size = 60 num_parents = int(pop_size*0.3) chromosome_size = 8 # Excluding start and end points population = [] fitness = ...
def get_random_expansion_idx(self): exist_idxs = self.get_exist_idxs() # Either the grid is full if self.check_full(): print("Grid is full!") return_idx = None # Or there is exist at least one tile elif len(exist_idxs) > 0: random_expand_idx ...
The code expands an image grid by either randomly sampling or optimizing a tile at a specified index, using constraints from neighboring tiles. If no constraints exist, it samples randomly; otherwise, it optimizes the tile to fit constraints. The optimized result is stored, and the grid is optionally plotted. The funct...
def expand(self, idx=None, opposite_transform=False, reduce_black_and_white=False, plot_losses=True, log_every=100, plot_grid_after=True): if idx is None: idx = self.get_random_expansion_idx() print(f"Random expansion to idx = {idx}") row, col = self.idx_to_row_co...
def load_model(self): MODEL_FILE = f'rf_model_{self.prompt}.pickle' if os.path.isfile(os.path.join(MODEL_DIR, MODEL_FILE)): with open(os.path.join(MODEL_DIR, MODEL_FILE), 'rb') as f: self.regressor = cPickle.load(f) return True else: # File doe...
The code performs inference by combining text and prompt features, using a preloaded model to predict a score. It loads the model, generates features from the input text and prompt, combines them, and applies a regression model to output a predicted score.
def infer(self, prompt, text): self.prompt = prompt self.texts = [text] self.we.load_model() if not self.load_model(): print(f'[ERROR] Couldnt find model file for prompt {prompt}') feat_mat = self.create_meta_features() vect_mat = self.create_vect_features() ...
def load_essays(self): df = pd.read_csv(os.path.join(DATA_DIR, TRAIN_FILE), sep='\t', encoding='ISO-8859-1') df = df.dropna(axis=1) df['target'] = (df['rater1_domain1'] + df['rater2_domain1'])/2 df = df.drop(columns=['rater1_domain1', ...
The code trains a regression model using features derived from essays. It loads essays, processes text into meta and word vector features, combines them, performs optional cross-validation, splits data, trains a regressor, evaluates accuracy on a test set, and saves the model if enabled.
def train(self, prompt=1): self.prompt = prompt print('Trainning has started ...\n') print( f'1) Loading essays for prompt {prompt} ... ', end='', flush=True) self.load_essays() print('[OK]') if False: print(f'2) Trainnig word embeddings model .....
def _unidentified_user(self, user_id, keyword): result = [] if user_id: user_info = { 'user_id': user_id, 'state': 'UNIDENTIFIED' } result.append(user_info) else: raise ERROR_NOT_SUPPORT_KEYWORD_SEARCH() retu...
This function searches for user information via an API using either a user ID or keyword. It authenticates with a token, constructs a request URL, fetches data, and returns parsed results. If no user data is provided or the request fails, it raises appropriate errors.
def find(self, options, secret_data, schema, user_id, keyword): field_mapper = options.get('field_mapper', DEFAULT_FIELD_MAPPER) user_id_field = field_mapper['user_id'] # UserInfo if secret_data == {}: # not support find return self._unidentified_user(user_id, ke...
def generate_edges(graph): edges = [] for node in graph: for neighbour in graph[node]: if (node,neighbour) and (neighbour, node) not in edges: edges.append((node,neighbour)) return edges def gen_subsets(set_, k): curr_subset = [] res = [] generate_subsets(set_...
This function computes a minimal vertex cover of a graph using a brute-force approach. It generates all subsets of vertices in increasing size, checks each subset to see if it covers all edges, and returns the first valid subset found. The result is stored in the 'res' list.
def vertex_cover_brute(graph, res): vertices = list(dict(graph).keys()) k = len(vertices) # generate all edges present in graph edges = generate_edges(graph) for i in range(1, k): # generate all subset of size i from set vertices subsets_ = gen_subsets(vertices, i) for s in s...
def found_email(email, text, context, url): global email_set email_set.add(email.lower()) print(f'Found new email address: {email}') row = [email, text, context, url] with open(results_file, mode='a', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(ro...
The code scrapes email addresses from web pages by processing URLs from a queue. It parses HTML, extracts links, filters out non-HTML content, and identifies emails from both mailto: links and text. It avoids revisiting URLs, respects depth limits, and logs statistics on discovered links and emails, ensuring efficient ...
def scrape_email_addresses(queue): while not queue.empty(): work_item = queue.get() url = work_item[0] depth = work_item[1] try: response = get(url, headers=request_headers) except Exception as e: print(f'REQUEST ERROR: {url}\n{getattr(e, "message", repr(e))}') ...
def fixup_env(script_path, args): os.environ["PYTHONPATH"] = os.pathsep.join(get_python_path(script_path, 0)) # Set the "LXBUILDENV_REEXEC" variable to prevent the script from continuously # reinvoking itself. os.environ["LXBUILDENV_REEXEC"] = "1" # Python randomizes the order in which it traverse...
This code manages a development environment by handling environment setup, dependency checks, script execution, and project initialization. It supports printing environment details, managing Git submodules, running specified scripts with configurations, and initializing projects with Git, binary tools, and a default ma...
def lx_main(args): if args.lx_print_env: fixup_env(script_path, args) elif args.lx_print_deps: lx_print_deps() elif args.lx_run is not None: script_name=args.lx_run[0] config = read_configuration(script_name, args) fixup_env(script_path, args) if not config...
def update_user_data(username): """ This function takes a username as input and updates the USER_DATA dictionary with the corresponding information about the games played and games won by that user. If the user is already present in the dictionary, their games played count is incremented, and if not, a ...
This function updates the winner's user data, calculates their win percentage, generates a leaderboard string, sends it to clients, and writes the updated user data to a CSV file.
def update_csv_and_send_leaderboard(winner_name): """ This function updates the user data for the winner of the game, calculates the win percentage :param winner_name: """ update_user_data(winner_name) calculate_win_percentage() leaderboard_string = get_leaderboard() send_message_to_clie...
def listen_for_offers(): """ This function listens for incoming UDP broadcast messages containing offer requests from game servers. When an offer request is received, the function validates the message and extracts the server name and TCP port. It then attempts to connect to the game server. @re...
The main task of the code is to run a client program that continuously listens for game server offers, connects to them via TCP, and handles incoming messages. It registers a keyboard event callback for user input and maintains a loop to process server interactions, including establishing connections and managing commu...
def main(): """ The main function of the client program. It listens for offer requests from game servers, """ global ANS_THREAD # Register the callback function for key events keyboard.on_press(on_key_event) while True: ANS_THREAD = None server_ip, tcp_port = listen_for_offer...
def send_start_game_message(): """ Function to send a message to all connected clients that the game is starting. """ message = f"Welcome to the {SERVER_NAME} server, where we are answering trivia questions\n" count = 1 # Send a welcome message to all clients for client in CLIENTS: m...
This code manages a trivia game by sending random questions to connected clients, collecting their answers via threads, checking for correct responses, handling timeouts, determining winners, updating a leaderboard, and disconnecting clients once the game concludes.
def start_game(): """ Function to start the trivia game. """ global GAME_READY_EVENT # Send a message to all clients that the game is starting send_start_game_message() # flag for finishing game game_finished = False # Now we need to start sending questions while not game_finishe...
def client_connect(): """ Function to start the accept incoming connections from clients thread. """ # Accept incoming connection client_socket, client_address = TCP_SOCKET.accept() colored_print(f"New connection from {client_address}") # Start a new thread to handle the connection threa...
This function waits for at least one TCP client to connect, using a 10-second timeout. It increments a connection counter upon successful client acceptance. If no clients connect within the timeout and the counter remains zero, it continues waiting. Once a client connects, it disables the timeout, signals game readines...
def tcp_connect_clients(): """ Function to start getting connections """ global TCP_SOCKET, GAME_READY_EVENT # we need to wait for at least one client to connect count_clients = 0 # Wait for clients to connect while True: try: client_connect() # Set the ti...
def _parse_get_from(self, map: dict): if "url_match" in map.keys(): url_match = map["url_match"] else: url_match = True if "wait" in map.keys(): wait = map["wait"] else: wait = None self.get(url=map["url"], url_match=url_match, wait...
The code's main task is to execute a sequence of web automation commands (e.g., navigating URLs, clicking elements, sending keys) by parsing each dictionary in the input list and invoking corresponding private methods like `_parse_get_from` or `_parse_send_keys_from`. It processes actions step-by-step to automate brows...
def execute(self, sequences: list[dict]): """Execute the commands in sequences. Usage: sequences = [ {"get": {"url", "https://www.google.com"}} {"click": {"by": By.XPATH, "value": "//textarea[@title='Search']"}} {"send_keys": {"by": By.XPAT...
def forward(self, inputs): #print(f"Inputs: {inputs}") weighted_sum = self.dot_product_single_layer(inputs, self.weights[:-1]) + self.weights[-1] return self.activation_sigmoid(weighted_sum) def binary_cross_entropy(y_true, y_pred): bce = -(y_true * math.log(y_pred) + (1 - y_true) * math.log...
This code trains a neural network using gradient descent with binary cross-entropy loss. It iterates over epochs, shuffles training data, computes predictions, calculates loss, updates weights and bias based on error gradients, tracks training/test losses, and plots them. The model trains on input-label pairs, adjusts ...
def train(self, training_inputs, labels, test_inputs, test_labels, epochs): loss_per_epoch = [] self.train_losses = [] self.test_losses = [] for epoch in range(epochs): shuffle_data = list(zip(training_inputs, labels)) random.shuffle(shuffle_data) to...
def forward(self,inputs): #hidden_input = np.dot(inputs, self.w_hj[:-1])+ self.w_hj[-1] hidden_input = dot_product(transpose(self.w_hj[:-1]), inputs) + self.w_hj[-1] self.z_h = self.sigmoid(hidden_input) self.y_i = dot_product(self.z_h, self.v_ih[:-1]) + self.v_ih[-1] return self...
The code trains a model by iterating over epochs, shuffling training data, computing binary cross-entropy loss for each training and test sample, averaging losses per epoch, logging them in lists, and plotting training/test loss curves. It returns the recorded loss values for analysis.
def train(self, training_inputs, labels, test_inputs, test_labels, epochs): self.train_losses = [] self.test_losses = [] for epoch in range(epochs): shuffle_data = list(zip(training_inputs, labels)) random.shuffle(shuffle_data) total_loss = 0 #for...
def load_data(file_path): data = [] with open(file_path, 'r') as file: reader = csv.reader(file) next(reader) for row in reader: data.append([int(pixel) for pixel in row[1:]]) return data def k_means_clustering(data, k, max_iterations=10, convergence_threshold=1e-4): ...
The main task of the code is to extract the Fashion-MNIST dataset from a ZIP file, load its data, perform K-means clustering for multiple k-values (10, 20, 30), visualize cluster centroids during and after convergence, track reconstruction loss for each k, and plot the loss comparison across k-values to evaluate cluste...
def main(): zip_path = './fashion_mnist.zip' extract_path = './extracted_data' os.makedirs(extract_path, exist_ok=True) with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_path) csv_file_path = os.path.join(extract_path, 'fashion_mnist.csv') data = load_data(csv...
def generate_samples(sentence, n_samples, NMTAttn=None, temperature=0.6): """Generates samples using sampling_decode() Args: sentence (str): sentence to translate. n_samples (int): number of samples to generate NMTAttn (tl.Serial): An LSTM sequence-to-sequence model with attention. ...
The function performs Minimum Bayes Risk (MBR) decoding to translate a sentence by generating multiple samples using an LSTM sequence-to-sequence model. It scores these samples with ROUGE-1 similarity, selects the highest-scoring sample, and returns its detokenized version. The process balances sampling diversity (via ...
def mbr_decode(sentence, n_samples, NMTAttn=None, temperature=0.6): """Returns the translated sentence using Minimum Bayes Risk decoding Args: sentence (str): sentence to translate. n_samples (int): number of samples to generate NMTAttn (tl.Serial): An LSTM sequence-to-sequence model wit...
def update_key_image(deck, key, state): # Determine what icon and label to use on the generated key. key_style = get_key_style(deck, key, state) # Generate the custom key with the requested image and label. image = render_key_image(deck, key_style["icon"], key_style["font"], key_style["label"]) # ...
This callback function handles key press events on a deck device, toggling boolean states for grid/column/row selections, updating UI visuals, and modifying network table entries to reflect target/marking states. It ensures exclusive selection of single targets, resets others, and updates system indicators for grid pos...
def key_change_callback(deck, key, state): global grid0 global grid1 global grid2 global column0 global column1 global column2 global row0 global row1 global row2 global setTgt global markGrid global toggleMark global fellLow global resetTgt # Print new k...
def get_headers(self, ref=True, ref_cid: Conversation = None) -> dict: _h = { "Accept": "*/*", "Connection": "keep-alive", "Host": "huggingface.co", "Origin": "https://huggingface.co", "Sec-Fetch-Site": "same-origin", "Content-Type": "appli...
The main task of the code is to create a new conversation by selecting a model (default or specified via modelIndex), optionally using an assistant (by ID or object), and sending a POST request to a server to generate a conversation object. It handles error retries, applies system prompts if no assistant is used, and o...
def new_conversation( self, modelIndex: int = None, system_prompt: str = "", switch_to: bool = False, assistant: Union[str, Assistant] = None, ) -> Conversation: """ Create a new conversation. Return a conversation object. modelIndex: int, get it fro...
def _get_cookie_path(self, cookie_dir_path) -> str: if not cookie_dir_path.endswith("/"): cookie_dir_path += "/" if not os.path.exists(cookie_dir_path): return "" files = os.listdir(cookie_dir_path) for i in files: if i == f"{self.email}.json": ...
The function logs into huggingface.co using email/password, either by loading existing cookies from a specified path or performing a new login. It validates cookies, saves them if requested, and returns the cookie jar on success. If cookies are invalid or login fails, exceptions are raised.
def login(self, cookie_dir_path: str = None, save_cookies: bool = False) -> requests.sessions.RequestsCookieJar: ''' Login to huggingface.co with given email and password. - If cookie_dir_path is given, load cookies from the path. If path is not exist, raise an exception. - If save_cooki...
def get_hc_session(self) -> Session: session = Session() # set cookies session.cookies.update(self.cookies) session.get(self.hf_base_url + "/chat") return session def get_remote_llms(self) -> list: """ Fetches all possible LLMs that could be used. Returns the LLMs...
This code initializes a ChatBot object by handling authentication via cookies (either directly or from a file), setting up session parameters, loading available language models (LLMs), selecting a default model, and initializing a conversation with a system prompt. It validates input parameters, processes cookies into ...
def __init__( self, cookies: Union[dict, None, RequestsCookieJar] = None, cookie_path: str = "", default_llm: Union[int, str] = 0, system_prompt: str = "", ) -> None: """ Returns a ChatBot object default_llm: name or index """ if cookie...
def collect_data(self): """ Collect the Grype data from a file or stdin. Returns ------- dict The parsed JSON data. """ filename = self.filename() if filename: stream = open(filename) grype_data = json.load(stream) ...
The `report` method generates a report on non-tolerated vulnerabilities by analyzing scan data. It checks for allowed vulnerabilities not detected in the scan, logging warnings. It evaluates the maximum severity level of identified vulnerabilities against a predefined tolerance threshold. If the severity exceeds tolera...
def report(self): """ Create a report of the non-tolerated vulnerabilities. Returns ------- int Zero if all vulnerabilities have a tolerance less than or equal to the specified tolerance. Non-zero otherwise. """ grype_data = self.collect_...
def get_arg(arg): for i in sys.argv: if arg in i: return i.split('=')[-1] return -1 def set_driver(**kwargs): headless=kwargs.get("headless",False) image_disable=kwargs.get("image_disable",False) use_chrome=True chrome_driver='../drivers/chromedriver.exe' if check_argv(["...
The main task of the code is to search for a title using a web driver, display search results, allow user selection of specific items, and return the chosen results or None if no valid selection is made. It handles input validation, web scraping, and driver management to retrieve and process data based on the provided ...
def main_block(title="",cho=0): st = 1 #os.environ["WDM_LOG_LEVEL"] = str(logging.WARNING) while st == 1: if(cho==0): os.system("cls") if get_arg("title")!=-1: find=get_arg('title') else: find = input('Enter Name :').strip() ...
def get_prior(actual): prior = get_probability(data_actual, BINS_ACTUAL, RANGE_ACTUAL, actual) return prior def get_likelihood(hist_table, actual, measured): bin_index_actual = get_bin_index(BINS_ACTUAL, RANGE_ACTUAL, actual) bin_index_measured = get_bin_index(BINS_MEASURED, RANGE_MEASURED, measured) ...
The code calculates the posterior probability using Bayes' theorem. It computes the prior probability of the actual value, the likelihood of the measured data given the actual value, and the marginal likelihood of the measured data. The posterior is derived by multiplying the likelihood and prior, then dividing by the ...
def get_posterior(hist_table, actual, measured): prior = get_prior(actual) likelihood = get_likelihood(hist_table, actual, measured) marginal_likelihood = get_marginal_likelihood(hist_table, measured) if marginal_likelihood == 0: posterior = 0 else: posterior = likelihood * prior / m...
def parse_edges(self,edges:list,output:dict,key:str): result = list(output[key]) #loop over edges for edge in edges: edge=edge['node'] #extract type type={ "from":"posts", "type":"image" } if edge['is_vid...
This code parses Instagram profile data by extracting user information and media counts from a response, handling pagination for IGTV and regular posts. It uses BeautifulSoup to parse HTML, extracts structured JSON data, and makes additional GraphQL requests for paginated content. The output is a dictionary with user d...
def parse(self, response): #convert response to dict bs=self.BeautifulSoup(response.text,features="lxml") body = bs.find('body') script = body.find('script', text=lambda t: t.startswith('window._sharedData')).text json_string = script.strip().split(' = ')[1][:-1] input ...
def get_count_of_selections(): count = 0 for year in selectable_years: if year in st.session_state: for day in range(1, get_num_days_available(year) + 1): if f"{year}-{day}" in st.session_state: if st.session_state[f"{year}-{day}"]: ...
The main task of the code is to download selected Advent of Code (AOC) day inputs and questions into a ZIP file, tracking progress via session state. It iterates through specified years and days, checks user selections, throttles requests, and adds files to the ZIP based on flags. The function initializes progress, cou...
def retrieve_info(): with st.spinner("Retrieving info..."): if not st.session_state["progress"]: st.session_state["progress"] = 0 st.session_state["total_to_download"] = get_count_of_selections() with ZipFile( f"{st.session_state['ST_SESSION_ID']}-aoc.zip", "w" ...
def adv(self, ): self.tok_idx += 1 if self.tok_idx < len(self.tokens): self.current_tok = self.tokens[self.tok_idx] return self.current_tok def power(self): return self.bOp(self.atom, (power,), self.factor)
This function parses a 'factor' in an expression, handling addition/subtraction by recursively evaluating operands and operators, then delegating to 'power()' for other operations. It uses a parser result object to track errors and returns parsed operations or results accordingly.
def factor(self): res = pRes() tok = self.current_tok if tok.type in (add, subtract): res.store(self.adv()) factor = res.store(self.factor()) if res.error: return res return res.success(uOps(tok, factor)) return self.power()
def model_signal(conf, model_name, src, restore=False): print("model_signal", conf, model_name, src.shape) random.seed(1) c = munchify(conf) tf.reset_default_graph() with tf.Graph().as_default() as g: if restore: saver = tf.train.import_meta_graph(model_name + ".meta") el...
This function tests a poisoning attack on a time-series model by generating and applying synthetic poison data, evaluating its effectiveness, and saving results. It configures attack parameters, runs the attack (if not in test-only mode), checks for successful poisoning, and validates the attack's impact using MATLAB i...
def run_te_test(conf, x_train_full, extended_att_len, x_att, start_poison, field_names, scaler, all_columns, test_model_only): start_time = time.time() model_name = "./tmp/te_attack_%d_seq_%d" % (conf["att_num"], conf["seq_len"]) # remove old intermediate models for f in glob.glob("." + os.sep + "tmp" +...
def change_current_dir(arguments, set_vars): """ Change current directory per case @param: arguments: cd command's arguments @param: set_vars: dictionary of variables """ if arguments: check_and_move_dir(arguments[0], set_vars) else: if 'HOME' in set_vars: chec...
This function processes user commands in a shell environment by parsing the input into a command and arguments, executing built-in operations like directory changes, environment variable management, and history display, or delegating unknown commands to external execution while utilizing a variables dictionary for stat...
def run_command(user_input, set_vars): """ Run command according to input from user @param: user_input: input from user @param: set_vars: dictionary of variables """ if user_input: command, arguments = user_input[0], user_input[1:] if command == 'cd': change_curren...
def tally(target, guess): if verifyGuessLength(target, guess): raise ValueError(target, guess, "Invalid guess") return [tallyforposition(i, target, guess) for i in range(len(target))] def determine_status(response, turns): return Status.WON if response == [ Match.EXACT] * WORD_SIZE else Sta...
The code implements a game loop where a player guesses a target, receives feedback on their guess, and the game state is displayed. It iterates up to MAX_TRIALS, using `readGuess` to get input, `tally` to evaluate correctness, `determine_status` to check win/loss conditions, and `display` to show results. The loop term...
def play(target, readGuess, display): for turns in range(1, MAX_TRIES + 1): guess = readGuess() response = tally(target, guess) status = determine_status(response, turns) display(turns, status, response, create_message(turns, status, target)) if status != Status.IN_PROGRESS: ...
def handleThreads(url): forms = getForms(url) threads = [] # handeling forms def scan_form(form): scanner(url, [form]) # threads for each form for form in forms: thread = threading.Thread(target=scan_form, args=(form,)) threads.append(thread) thread.start() ...
The code defines a function `runFunction` that handles different tasks based on user input. It scans URLs, generates SQL injection payloads, creates reports, or exits the program. Options 1–4 correspond to scanning, payload generation, report creation, and termination, respectively.
def runFunction(option): if option == '1': url = input("Enter url to scan >>> ") handleThreads(url) elif option == '2': t = input("Enter table name >>>") c = input("Enter column name >>>") output = payloadGen(t,c) print("\033[92m" + "Generating Payloads..." + "\0...
def cust_search(db, id, labels, order, store): data = db.fetch("Customers", id, "") order.customer = customer.Customer(data[0][1], data[0][2], data[0][3], data[0][4]) order.customer.id = data[0][0] order.del_fee = order.customer.dist * store.del_ppm #labels display active customer information labels[0].confi...
This code creates a GUI for order management, allowing users to search for customers and furniture items, view details, add/remove items from an order, submit the order, or cancel. It initializes a window with input fields, labels, and buttons to interact with a database, updating order information dynamically.
def ord_screen(db, store): window = comp.newWindow("Order Options") #starts an empty order ord_in_prog = Order(customer.Customer("","","", 0), store) title = comp.newLabel(window, "Orders", 16) title.grid(column=2, row=0,) labels = [] fields = [] #customer search labels, text fields and button ...
def authenticate(): reddit = praw.Reddit("PunOfTheDayBot", user_agent="PunOfTheDayBot v1.0") print("Authenticated as {}".format(reddit.user.me())) return reddit def load_comments_replied(filename): try: with open(filename, "r") as f: return json.load(f) except BaseException: ...
The main task of the code is to run a Reddit bot that continuously monitors and replies to comments. It authenticates with Reddit, loads a list of previously replied comments from a file, and enters a loop where it executes the bot's logic to check for new comments. The bot avoids replying to already addressed comments...
def main(): reddit = authenticate() comments_replied = load_comments_replied(filename) while True: run_bot(reddit, comments_replied) time.sleep(20)
def resid_group(file_name): prev_resid = (-1,None) resid_atoms = [] for atom_data in gen_data(file_name): res_number,res_name,atom_number,atom_name = atom_data if prev_resid[0] < 0: prev_resid = (res_number,res_name) resid_atoms.append((atom_number,atom_name)) ...
The main task of the code is to process a cpptraj atominfo file, grouping atoms by residue. It separates main and side chains for residues not in a specified list, while keeping all atoms grouped for residues in the list. The script outputs atom groups with names based on residue numbers and types, handling user-define...
def main(): import sys if len(sys.argv) < 2: print('USAGE : ./gen_atomgroup.py [cpptraj atominfo file] [No separate residue number]\n') print('residue in [No separate residue number] are not separated in side chian and main chain.') print(' example : "ACE","NME" or Ligand,Cofactor\n') ...
def Cnx(qc,n,q,controls,w,targ): for i in range(n): if controls[i]==0: qc.x(q[i]) qc.ccx(q[0],q[1],w[0]) for i in range(n-2): qc.ccx(q[i+2],w[i],w[i+1]) qc.cx(w[n-2],targ) for i in reversed(range(n-2)): qc.c...
The main task of the code is to simulate a quantum process involving particle counting, conditional operations, and state adjustments. It calculates time-dependent parameters (t_up, t_mid, t_low), applies conditional quantum gates (Cnx, Cn) based on particle counts and states, computes emission probabilities via Delta_...
def step1(qc,gA,gB): ## Simulation of the first step ## t_up = eps**((0)/2) t_mid = eps**((0+0.5)/2) t_low = eps**((0+1)/2) # count particles qcount = [p0[0],p0[1],p0[2]] cCount1 = [0,0,1] cCount2 = [1,0,1] w1 = [w...
def Delta_f(t, g): return math.exp(P_f(t,g)) def Delta_phi(t, gA, gB): return math.exp(P_phi(t,gA,gB)) def Cn(qc,entry,n,q,controls,w,targ): for i in range(n): if controls[i]==0: qc.x(q[i]) qc.ccx(q[0],q[1],w[0]) for i in range(n-2): ...
The main task of this code is to simulate a quantum process involving particle interactions and emissions. It applies controlled operations (CNOT, Toffoli gates) and conditional probabilities (via delta calculations) to model particle state transitions, history tracking, and emission adjustments using parameters gA and...
def step2(qc,gA,gB): ## Simulation of the first step ## t_up = eps**((1)/2) t_mid = eps**((1+0.5)/2) t_low = eps**((1+1)/2) # count particles qc.x(p0[0]) qc.ccx(p0[0],p0[2],a[0]) qc.x(p0[0]) qc.ccx(p0[0],p...