dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def is_new_book(line): return line.startswith('### ') def new_book_from_line(title_line, line_number): authored_title_line_pattern = re.compile(r'^###\s+(.*)\s+by\s+(.*)$') unauthored_title_line_pattern = re.compile(r'^###\s+(.*)$') m = authored_title_line_pattern.match(title_line) if not m: ...
This function processes a line of text to either start a new book or add content to the current book. It trims whitespace, skips empty lines, checks if the line signifies a new book using `is_new_book()`, and either initializes a new book or appends the line to the existing book. The processed books are stored in `self...
def parseBookLine(self, line, line_number): line = line.rstrip('\n\r ') if not line.lstrip(' '): return if (is_new_book(line)): if self.book: self.books_content['books'].append(self.book) self.book = new_book_from_line(line, line_number) ...
def parseBookLine(self, line, line_number): line = line.rstrip('\n\r ') if not line.lstrip(' '): return if (is_new_book(line)): if self.book: self.books_content['books'].append(self.book) self.book = new_book_from_line(line, line_number) ...
The function parses a line based on the current state, routing it to `parseBookLine`, `parseIntroLine`, or `parseHeaderLine` depending on whether the state is `BOOKS_STATE`, `INTRO_STATE`, or other.
def parseLine(self, line, line_number): if self.state == BOOKS_STATE: self.parseBookLine(line, line_number) elif self.state == INTRO_STATE: self.parseIntroLine(line, line_number) else: self.parseHeaderLine(line, line_number)
def check_if_space_is_empty(self,row,col): #return a True if the piece is empty (' '), else, return a False return self.get_piece(row,col) == ' ' def check_mov_jump_foward(self,pawn): piece = self.get_piece(pawn.row+(self.direction_of_movement*2),pawn.col) #cant jump my own pawns ...
This code checks if a pawn can move forward by validating the target space's emptiness, wall confinement, and potential jumps/diagonal moves. It updates the pawn's position, score, and movement count if valid, handling edge cases like walls and confined spaces.
def check_mov_foward(self,row,col,pawn): #return if the foward wall space is true if pawn.front_wall: return #if the pawn space is not empty if (not self.check_if_space_is_empty(row+(self.direction_of_movement*2),col)): #see if i can jump that pawn as piece ...
def check_if_space_is_empty(self,row,col): #return a True if the piece is empty (' '), else, return a False return self.get_piece(row,col) == ' ' def side_jump(self,pawn,direction): piece_to_jump = self.get_piece(pawn.row,pawn.col+(direction*2)) if piece_to_jump.name == self.side: ...
The function checks if a pawn can move laterally (left/right) by verifying empty spaces, handling potential jumps over opponent pawns, detecting walls, and updating game state variables like position, score, and movement count. It also triggers exit searches if movement is blocked and records valid moves.
def check_side_movement(self,row,col,pawn,direction): #return if has a wall left or right if not self.check_if_space_is_empty(row,col+direction): return #check pawn space if not self.check_if_space_is_empty(row,col+(direction*2)): #check if is the opponent pawn ...
def select(self, node): while not (node.board.has_ended()): if len(node.children) == 0: new_node = self.expand(node) return new_node else: if not node.is_expanded(): return self.expand(node) else: ...
The code performs Monte Carlo Tree Search (MCTS) by iteratively selecting nodes, simulating outcomes, and backpropagating rewards through a tree. After `rollout_times` iterations, it uses UCB (Upper Confidence Bound) to select the optimal child node from the root, returning its action as the best move.
def search(self, rollout_times, root): """ enter point - return best move based on usb """ for _ in range(rollout_times): leave = self.select(root) reward = self.simulate(leave) self.backup(leave, reward) best_child = self.ucb(root, 0) ...
def getPiece(self, x, y): return self.__board[self.__getIndex(x, y)] def printBoard(self): s = "" for x in range(self.__board_size): s += " " * x for y in range(self.__board_size): s += self.getPiece(x, y) + " " s += "\n" print(s) def __getIndex(self, x, y): if x < 0: raise IndexError(f"Expect...
The main task of the code is to place a game piece at coordinates (x, y) on a board only if the position is empty. It first checks if the target cell contains a piece using `getPiece()`. If occupied, it prints the board and raises a `ValueError`. If empty, it updates the internal board array at the calculated index wit...
def __setPiece(self, x, y, value): if self.getPiece(x, y) != self.__empty_value: self.printBoard() raise ValueError(f"There is already a piece at ({x}, {y}).") self.__board[self.__getIndex(x, y)] = value
def select_node(self): node = self.root state = self.board.copy() while len(node.children) > 0: children = node.children.values() max_value = max(children, key = lambda n: n.value(self.EXPL_CONST, self.RAVE_CONST)).value(self.EXPL_CONST, self.RAVE_CONST) max_nodes = [n for n in children if n.value(self...
This code performs a time-limited Monte Carlo Tree Search (MCTS) by iteratively selecting nodes, simulating game outcomes through rollouts, and updating the search tree with results. It runs until the specified time budget is exhausted, tracking the number of rollouts and returning it alongside the tree's node count an...
def search(self, time_budget): start_time = time() num_rollouts = 0 while time() - start_time < time_budget: node, state = self.select_node() turn = state.turn() outcome, red_rave_pts, blue_rave_pts = self.roll_out(state) self.backup(node, turn, outcome, red_rave_pts, blue_rave_pts) num_rollouts +...
def setRedPiece(self, x, y): self.__setPiece(x, y, self.__red_value) def setBluePiece(self, x, y): self.__setPiece(x, y, self.__blue_value) def togglePlayerTurn(self): self.red_turn = not self.red_turn
The code handles a player's move in a two-player game by placing a red or blue piece at coordinates (x, y) based on whose turn it is, then switches the turn to the other player.
def makeMove(self, move): x, y = move if self.red_turn: self.setRedPiece(x, y) else: self.setBluePiece(x, y) self.togglePlayerTurn()
def getHash(file_name): return hashlib.md5(file_name.encode()).hexdigest() def addAnchors(regexStr,flags_re): flags=None ##remove start ^ if len(regexStr)>0 and regexStr[0]=='^': regexStr=regexStr[1:] ###start with flags: if len(regexStr)>4 and regexStr[0]=="(": res=flags_re.matc...
The main task of the code is to process regular expressions (regex) from multiple repositories by reading a CSV file of repository paths, loading regex histories, decoding and modifying regex patterns, generating valid strings based on these patterns, and saving the results as pickle and CSV files. The function handles...
def readGenRegex(k, enforce=False): ### read searched_repos.csv to get all valid repos with open("searched_repos.csv",mode="r") as searchedRepos: reader = csv.reader(searchedRepos) for repo in reader: page,row=int(repo[0]),int(repo[1]) repo_path=str(page)+"_"+str(...
def max_nside(self): N = 1 reso = hp.pixelfunc.nside2resol(nside=N,arcmin=True) while reso > max(self.beam_fwhm): N *= 2 reso = hp.pixelfunc.nside2resol(nside=N,arcmin=True) self.max_Nside = int(N/2) def coverage(self): uvcenter = np.array(hp.ang2vec(self.center_GAL[0], self.center_GAL[1], lonlat=True)...
This code initializes a class to handle frequency band parameters, compute noise models, and build covariance matrices for a sky survey. It processes input parameters, validates consistency, calculates pixel edges, beam properties, and noise RMS. If enabled, it constructs covariance submatrices for all frequency pairs,...
def __init__(self,pars,build_cov=True): self.nus = np.array(pars['nus'])*1e9 self.nbands = len(self.nus) self.bwidths = np.array(pars['bwidths'])*1e9 if len(self.bwidths) != self.nbands: raise ValueError('Incorrect number of bandwidths') self.dnu_nu = self.bwidths/self.nus edges_min = self.nus * (1 - se...
def chi_sq(self): chisq = 0. for i1,f1 in enumerate(self.nus): for stokes1 in range(3): for pix1 in range(self.npix): for pix2 in range(self.npix): ## sum over pixels if pix1 != pix2 and not self.pix_corr: continue for stokes2 in range(3):...
This function performs Metropolis-Hastings MCMC sampling to generate posterior distributions of model parameters. It initializes parameters, computes initial chi-square and prior probabilities, applies covariance preconditioning if specified, runs the sampling chain for given iterations, calculates acceptance rate, and...
def metropolis(self, it=0, burn_in=0, optimize=False): if it != 0: self.it = it if burn_in != 0: self.burn_in = burn_in self.accept_rate = 0 ### Computing initial Chi square print('\033[1m'+'Computing TOTAL initial Chi square'+'\033[0m') self.old_prob = -0.5 * self.chi_sq() + self.prior_cut() ...
def decorr_chi_sq(self,pix,st): chisq = 0. for i1,f1 in enumerate(self.nus): if st != '' and pix == -1: stokes = ['I','Q','U'].index(st) for pix1 in range(self.npix): for pix2 in range(self.npix): ## sum on pixels if pix1 != pix2 and not self.pix_corr: ...
This function performs Metropolis-Hastings MCMC sampling with preconditioning for correlated parameters. It checks for pixel/Stokes correlations, initializes chi-square and acceptance rate, loads covariance matrices if enabled, runs iterative sampling, and computes post-burn-in parameter variances and acceptance rate. ...
def decorr_metropolis(self, pix=-1, stokes = '', it=0, burn_in=0, optimize=False): if pix != -1 and self.pix_corr: raise ValueError("Pixels are correlated, use 'metropolis' function.") if stokes != '' and self.IQU_corr: raise ValueError("IQU are correlated, use 'metropolis' function.") if it ...
def is_zero_vector(self, vec2=None, tolerance=1e-7): """Check if a vector is a zero-vector. If called on a vector and given another vector as parameter, the method checks if either of the 2 vectors is the zero vector. The zero-vector is a vector that has a ma...
The code calculates the angle (in radians) between two vectors using the dot product and magnitudes formula (acos(dot_product/(magnitude1*magnitude2))). It handles edge cases: returns 0 if either vector is zero, raises an error for unequal dimensions, and rounds the result to 4 decimal places. The method ensures valid ...
def radians(self, vec2): """This method calculates the angle between two vectors in radians. The angle is the arc-cosine of the dot-product of the two, vectors, divided by the product of their magnitudes. Usage Example: vec1 = Vector([2,3]) ...
def is_zero_vector(self, vec2=None, tolerance=1e-7): """Check if a vector is a zero-vector. If called on a vector and given another vector as parameter, the method checks if either of the 2 vectors is the zero vector. The zero-vector is a vector that has a ma...
This function calculates the vector component of 'self' that is parallel to the given basis vector 'vec2'. It achieves this by projecting 'self' onto 'vec2' using the dot product of 'self' and the unit vector of 'vec2', then scaling the unit vector by this projection value. The result is a vector in the direction of 'v...
def v_parallel(self, vec2): """Find the component of vector self, parallel to the basis vector(vec2), given that self is projected on vec2. To compute v_parallel, we multiply the unit_vector of vec2(basis vector), by the dot-product of the unit_vector of vec2 and self ...
def is_zero_vector(self, vec2=None, tolerance=1e-7): """Check if a vector is a zero-vector. If called on a vector and given another vector as parameter, the method checks if either of the 2 vectors is the zero vector. The zero-vector is a vector that has a ma...
The code computes the component of the vector `self` that is **orthogonal to `vec2`** by subtracting the **parallel component** of `self` (projected onto `vec2`) from `self`. It ensures vectors have equal dimensions, handles zero vectors, and returns the resulting perpendicular vector. The core task is to decompose `se...
def v_perp(self, vec2): """ Find the component of vector self orthogonal to vec2, given that self is projected on vec2 Any non-zero vector can be represented as the sum of its component orthogonal/perpendicular to the basis vector(vec2) and its component parallel to the ...
def is_zero_vector(self, vec2=None, tolerance=1e-7): """Check if a vector is a zero-vector. If called on a vector and given another vector as parameter, the method checks if either of the 2 vectors is the zero vector. The zero-vector is a vector that has a ma...
The code checks if two vectors are parallel by determining if one is a scalar multiple of the other, including opposite directions (180°) or same direction (0°). It returns `True` if parallel, `False` otherwise, and raises an error for unequal dimensions.
def is_parallel_to(self, vec2): """Check if one vector is a scalar multiple, of the other vector and vice versa Two vectors are parallel if one is a scalar multiple of the other. If the scalar is a negative number, then both vectors will be opposite and have angle of 180...
def is_zero_vector(self, vec2=None, tolerance=1e-7): """Check if a vector is a zero-vector. If called on a vector and given another vector as parameter, the method checks if either of the 2 vectors is the zero vector. The zero-vector is a vector that has a ma...
The function checks if two vectors are orthogonal by verifying if their dot product is zero or if one is a zero-vector. It ensures vectors have equal dimensions and returns `True` for orthogonality, `False` otherwise, or an error message for mismatched dimensions. The angle between vectors is also checked for 90 degree...
def is_orthogonal_to(self, vec2): """Check if two vectors are orthogonal Two vectors are orthogonal if their dot-product is 0. This usually happens if one is a zero-vector or they are at right angles to each other Usage Example: vec1 = Vector([1,2]) ...
def tokenize(sentence): return word_tokenize(sentence) def lemmatize(word_list, stop_words=True): ''' @param: a list of words @param: stop_words (True is to remove stopwords, False otherwise) @return: a list of lemmatized words after removing stopwords ''' wordnet_lemmatizer = WordNetLemmati...
The code extracts multiple text features from sentence pairs for NLP tasks, including POS tags, n-grams, word count differences, bag-of-words, TF-IDF vectors, and cosine similarity. It processes each sentence pair by tokenizing, lemmatizing, and generating structured features for machine learning models.
def extract_features(data): vectorizer = CountVectorizer() s1 = [] s2 = [] s = [] scores = [] pos_feature = [] ngram_feature =[] num_words_diff = [] bag_of_words_feature = [] for line in data: s1.append(line[1]) s2.append(line[2]) s.append(line[1]) ...
def findCoalition(permutation, o1, o2): coa = [] for data_owner in permutation: if (data_owner!=o1 and data_owner!=o2): coa.append(data_owner) else: return sorted(coa) return sorted(coa) def listToString(perm): return ' '.join(str(x) for x in perm) def diffUtility...
The code performs a Monte Carlo simulation to estimate data transfer utilities between entities A and B. It iteratively generates random permutations of data owners, identifies coalitions, transfers data between A and B, calculates utility changes, and stores permutations. The process repeats for 'step_size' rounds, up...
def monteCarloCF(curr_est, permutations_dict, owners, all_train_data, target_data, A, B, step_size, test, util): if (len(owners[A])==1): return [[-1], permutations_dict] A_data = owners[A] B_data = owners[B] # get step_size permutations every round for i in range(step_size): # draw a permu...
def findCoalition(permutation, o1, o2): coa = [] for data_owner in permutation: if (data_owner!=o1 and data_owner!=o2): coa.append(data_owner) else: return sorted(coa) return sorted(coa) def listToString(perm): return ' '.join(str(x) for x in perm) def diffUtility...
The function performs Thompson sampling to select top-k items based on their estimated power, calculated via differential utility. It iteratively samples permutations, updates item power estimates, and refines selections until the top items are statistically distinguishable, returning sorted items, total permutations s...
def topKBaselineCF(permutations_dict, A, B, owners, all_train_data, target_data, other_owner_data, items, step_size, k, delta, test, util): if (len(owners[A])==1): return [items, 0, {}] A_data = owners[A].copy() B_data = owners[B].copy() total_perms = 0 # first round of Thompson sampling if l...
def powerset(s): powerset = list(itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1))) return powerset def flatten(xs): for x in xs: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): yield from flatten(x) else: yield x def...
This function calculates the Shapley value contribution of two parties (A and B) in a cooperative game by iterating over all possible coalitions of other participants. For each coalition, it temporarily augments A and B's data with the coalition's data, computes the utility difference using `diffUtilityCF`, and accumul...
def diffShapleyCF(all_train_data, target_data, test, owners, A, B, util): A_data = owners[A] B_data = owners[B] list_owners = list(owners.keys()) list_owners.remove(A) list_owners.remove(B) coalitions = powerset(list_owners) total = 0 # go through all the powersets in order of size ...
def diffShapleyMCCF(permutations_dict, all_train_data, target_data, owners, A, B, delta, ss_size, test, util): total_samples = [] perms = 0 change = math.inf old_mean = 0.0000000001 while (change > 0.01): perms += ss_size total_samples, permutations_dict = monteCarloCF(total_sample...
The code implements a greedy algorithm to identify the minimal subset of items to transfer from entity A to B, aiming to flip their Shapley values (differential Shapley) to negative. It iteratively selects top-k items, simulates transfers, and evaluates the impact using `diffShapleyMCCF`, stopping when a negative diffe...
def greedyCF(A, B, all_train_data, target_data, owners, ss_size, delta, test, util): # get initial difference between A and B, stop if already negative diff = diffShapleyMCCF({}, all_train_data, target_data, owners, A, B, delta, 50, test, util) if diff[0] < 0: return [[], 0, True, diff[0]] tb...
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The code calculates the accuracy (ACC) metric for binary classification. It converts the input table into true positives (a), false negatives (b), false positives (c), and true negatives (d). The accuracy is computed as (a + d) / (a + b + c + d), with a zero-denominator safeguard to prevent division-by-zero errors.
def metrics_ACC(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(a + d, a + b + c + d)
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The code computes the F1 score for binary classification by converting the input table into true positives (a), false positives (b), false negatives (c), and true negatives (d). It calculates the F1 score using a modified formula to avoid division by zero, returning `a / (a + 0.5 * (b + c))`, which represents the harmo...
def metrics_F1(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(a, a + 0.5 * (b + c))
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The code calculates the Critical Success Index (CSI) for binary classification. It converts the input table into variables a, b, c, d, then computes CSI as a/(a+b+c) using a zero-denominator safeguard to avoid division errors.
def metrics_CSI(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(a, a + b + c)
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The function calculates the Probability of Detection (POD) metric for binary classification. It converts the input table into true positives (a) and false negatives (c), then computes POD as a/(a+c) using a zero-denominator safeguard to prevent division errors. The result represents the ratio of correctly predicted pos...
def metrics_POD(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(a, a + c)
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The function `metrics_MSI` calculates a binary classification metric by converting the input table into four variables (a, b, c, d) using `table2abcd`. It then computes a metric value by dividing `c` by the sum of `a` and `c`, employing a `zero_denominator` function to handle division-by-zero scenarios safely. The resu...
def metrics_MSI(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(c, a + c)
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
This function calculates the False Acceptance Rate (FAR) for binary classification by computing the ratio of false positives (b) to the sum of false positives and false negatives (a+b), using a zero-denominator handling method to avoid division errors. It processes input data through table2abcd to extract confusion mat...
def metrics_FAR(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(b, a + b)
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
This function calculates the Heidke Skill Score (HSS) for binary classification. It converts the input table into confusion matrix components (a, b, c, d), then computes HSS using the formula 2*(a*d - b*c) divided by [(a+c)(c+d) + (a+b)(b+d)], with a zero-denominator safeguard to prevent division errors.
def metrics_HSS(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(2 * (a * d - b * c), (a + c) * (c + d) + (a + b) * (b + d))
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The function `metrics_MAE` calculates a metric by dividing the sum of variables `b` and `c` (derived from the input table) by the total sum of all variables `a`, `b`, `c`, and `d`, using a zero-division-safe division method. This metric likely represents a classification evaluation score, such as accuracy or a custom e...
def metrics_MAE(table): # for binary classification print_log(f"running {currentFuncName()}") a, b, c, d = table2abcd(table) return zero_denominator(b + c, a + b + c + d)
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The main task of the code is to prepare datasets for machine learning by handling data input sources, cleaning old files, and processing data into training, testing, or prediction sets based on the specified `type_data_process` (train/test/predict). It uses configuration files to guide data preparation, ensuring proper...
def prepare_datasets(**kwargs): print_log(f"{currentFuncName()}:") message = "" # use the schema schema = cfg.PrepareDatasetsArgsSchema() # deserialize key-word arguments prepare_datasets_args = schema.load(kwargs) print_log(f"prepare_datasets_args['data_input_source'] == {prepare_datasets_a...
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) with ope...
The main task of the code is to prepare and split time-series data into training, testing, and validation sets for machine learning. It processes raw data from specified sources, merges and filters relevant features (ORPs and measurements), converts numerical values into categorical classes, removes zero-value rows, an...
def prepare_data_train(source_path, dest_path, dest_path_train_file, dest_path_test_file, dest_path_validate_file, config_yaml): try: print_log(f"running {currentFuncName()}") # csv_data_to_one_file ORPs = tuple() for i in range(len(config_yaml['dataset'])): ...
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) with ope...
The function `prepare_data_test` processes and prepares test data by converting raw data from multiple sources into structured CSV files, merging them, and splitting into train/test sets. It uses configuration parameters from a YAML file to generate, classify, and merge data, then saves the test dataset to a specified ...
def prepare_data_test(source_path, dest_path, dest_path_test_file, config_yaml): try: print_log(f"running {currentFuncName()}") # csv_data_to_one_file for i in range(len(config_yaml['dataset'])): make_raw_csv_data(source_path, dest_path, ast.literal_...
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) with ope...
The function `prepare_data_predict` processes and prepares data for machine learning prediction. It aggregates data from multiple sources, merges CSV files based on timestamps, selects relevant features (including ORP lists), converts numerical values into classes using thresholds, and saves the processed dataset for p...
def prepare_data_predict(source_path, dest_path, dest_path_predict_file, config_yaml): try: print_log(f"running {currentFuncName()}") # csv_data_to_one_file ORPs = tuple() for i in range(len(config_yaml['dataset'])): ORPs = ORPs + ast.literal_eval(config_yaml['dataset'][i...
def print_log(log_line, verbose=True, time_stamp=True, log_file=cly.LOG_FILE_PATH): tm = "" if time_stamp: tm = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S: ") if verbose: if log_file is None: print(tm + log_line) else: print(tm + log_line) ...
The function `metrics_RMSE` calculates the Root Mean Squared Error (RMSE) by taking the square root of the Mean Absolute Error (MAE) from the input table. It logs the execution and returns the result as a float. However, this implementation incorrectly uses MAE instead of Mean Squared Error (MSE) for RMSE calculation, ...
def metrics_RMSE(table): # for binary classification print_log(f"running {currentFuncName()}") return float(np.sqrt(metrics_MAE(table)))
def get_metadata(): """ Function to read metadata https://docs.deep-hybrid-datacloud.eu/projects/deepaas/en/latest/user/v2-api.html#deepaas.model.v2.base.BaseModel.get_metadata :return: """ module = __name__.split('.', 1) # module = ["py"] # prepare log file print(f"os.makedirs(os....
This code defines a `main()` function that executes different tasks based on the `args.method` parameter from the command line. It calls functions like `get_metadata()`, `prepare_datasets()`, `validate()`, `predict()`, or `train()` with parsed arguments, prints their results as JSON, and returns them. The primary task ...
def main(): """ Runs above-described methods from CLI (see below an example) """ if args.method == 'get_metadata': meta = get_metadata() print(json.dumps(meta)) return meta elif args.method == 'prepare_datasets': results = prepare_datasets(**vars(args)) p...
def forwardStep(inputs, weights1, weights2): layer1 = getOutputs(inputs, weights1) layer1 = sigmoid(layer1) layer2 = getOutputs(layer1, weights2) return layer1, layer2 def format1dArray(X): arr = [] for i in X: arr += [float(f"{i:.5f}")] return arr def getWeightUpdates(inputs, weights, output): inp ...
The function performs one epoch of backpropagation in a neural network, computing layer outputs, calculating error between predicted and expected values, deriving weighted errors for weight updates, updating weights using gradient descent, and returning new weights along with mean squared error. It processes forward pr...
def oneEpoch(inputs, expected, weights1, weights2): layer1, layer2 = forwardStep(inputs, weights1, weights2) error = [x - y for x, y in zip(expected, layer2)] print(f"Error: {format1dArray(error)}") out = [sum(o) for o in [[layer1[c1] * (1 - layer1[c1]) * dw for dw in [weight * error[c2] for c2, weight in en...
def offer_issues(choices=all_issues): print(f"Please select an Issue:") for b in range(len(choices)): print(f"{b}. {name(choices[b])}") sel = int(input()) return to_issue(choices[sel]) def check_outcome(d=6): return random.randint(1, d) def name(subj): if type(subj) is Pol_Issue or type(subj) is Party or type(s...
The code simulates a political rally where a player uses their "talking points" to influence voters. It checks if the player has talking points, selects an issue, determines the rally's outcome via a random roll, strengthens the selected issue based on the result, and optionally converts voters if the outcome is succes...
def rally(player=current_player): if len(player.talking_points)==0: print("you cannot hold a rally until you introduce some Talking Points; try having an interview first") return 0 sel = offer_issues(player.talking_points) roll = check_outcome() print(f"your efforts to rally the people on {name(sel)} were repor...
def offer_issues(choices=all_issues): print(f"Please select an Issue:") for b in range(len(choices)): print(f"{b}. {name(choices[b])}") sel = int(input()) return to_issue(choices[sel]) def name(subj): if type(subj) is Pol_Issue or type(subj) is Party or type(subj) is Voter_Bloc: return subj.name else: retur...
The function simulates a political interview where a player introduces new issues as talking points to influence voters. It selects issues, adds them to the player's agenda, and checks outcomes. If successful (roll >5), it randomly updates voters' priorities. The loop repeats until outcomes fail (roll ≤4), printing res...
def interview(player=current_player): sel = offer_issues() for e in player.talking_points: print(name(e)) player.add_talking_point(sel) roll = check_outcome() if roll > 5: for v in random.sample(all_voters, k=int_voters(0.025)): v.add_important_issue(sel) print(f"Trying to get people talking about {name(se...
def offer_issues(choices=all_issues): print(f"Please select an Issue:") for b in range(len(choices)): print(f"{b}. {name(choices[b])}") sel = int(input()) return to_issue(choices[sel]) def check_outcome(d=6): return random.randint(1, d) def name(subj): if type(subj) is Pol_Issue or type(subj) is Party or type(s...
The function `speech` simulates a political argument where a player selects an issue stance, rolls an outcome, and influences voters' opinions. Voters are randomly swayed based on the outcome's strength, with additional effects for high or low rolls. High rolls gain more voters, while low rolls risk losing some.
def speech(player=current_player): choices = list(player.stances.keys()) #print(type(choices)) sel = offer_issues(choices) roll = check_outcome() print(f"Your argument for {name(sel)} was hailed as a {outcome_chart[roll]}") for v in random.sample(all_voters, k=int_voters(0.15)): v.sway_opinion(sel, player.stanc...
def offer_issues(choices=all_issues): print(f"Please select an Issue:") for b in range(len(choices)): print(f"{b}. {name(choices[b])}") sel = int(input()) return to_issue(choices[sel]) def name(subj): if type(subj) is Pol_Issue or type(subj) is Party or type(subj) is Voter_Bloc: return subj.name else: retur...
The function allows a player to select a stance on a chosen issue, updating their position and influencing public discourse. If successful (roll ≥3), the issue enters public debate, affecting voters; if roll >5, impact is amplified. The task involves stance selection, outcome evaluation, and modifying game state elemen...
def debate(player=current_player): if len(player.talking_points)==0: print("you cannot attend a debate until you introduce some Talking Points; try having an interview first") return sel = offer_issues(player.talking_points) print(f"When asked about {name(sel)}, you made it clear that your position is...") if s...
def generate_access_flow_array(slice_id,mgnt_network_info): json_flows_array = [] json_data = return_access_flow() json_data['flow'][0]['id'] = slice_id + '_slice-access_network-flow' json_data['flow'][0]['priority'] = '500' json_data['flow'][0]['match']['vlan-match']['vlan-id']['vlan-id'] = get_...
This function generates an array of OpenDaylight JSON flow configurations for a network slice by concatenating access flows, VLAN drop rules, and multiple management/data flow types. It uses provided network info parameters to create flows for access, management (5 types), and data (2 types) traffic, ensuring comprehen...
def generate_opendaylight_json_flows_array(slice_id, mgnt_network_info, data_network_info): flows_array = [] access_flow_array = generate_access_flow_array(slice_id, mgnt_network_info) mgnt_flow_default_vlan_drop_array = generate_mgnt_flow_default_vlan_drop_array(slice_id, mgnt_network_info) data_flow...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--sizes', type=int, nargs="+", default=[100, 100, 100, 100]) parser.add_argument('--p', type=float, default=0.25) parser.add_argument('--q', type=float, default=0.2) parser.add_argument('--permute_rate', type=float, default=0....
The main task of the code is to generate either pair or sequence memberships based on input arguments. It checks if the 'sequence' parameter is absent; if so, it calls `generate_pairs_memberships`, otherwise `generate_sequence_memberships`, using parsed arguments to determine the appropriate membership generation metho...
def main(): args = get_args() if not args.sequence: generate_pairs_memberships(args=args) else: generate_sequence_memberships(args=args)
def menu (self): print('|----------------------------------|') print('| 1: Move') print('| 2: Rotate') print('| 3: Set Orientation') print('| 4: Go to Goal') print('| 5: Spiral') print('| 6: Grid') print('| 7: Reset') print('| Q: Quit') pri...
The code runs a menu-driven application for robot control, allowing users to select actions like moving, rotating, setting orientation, navigating to a goal, or executing predefined patterns (spiral, grid). It processes user input, converts choices into parameters, and invokes corresponding robot movement methods, loop...
def run_app(self): rclpy.spin_once(self) while True: choice = self.menu() if choice == '1': print("Moving...") dist = input("distance: ") direction = int(input("is_forward: 0 or 1: ")) ...
def decode(self, ident, bytes, sep='; '): # Return a string with decoded signals try: sheet_dict = self.__get_sheet_dict(ident) ret_string = '0x'+str(ident)+sep for signal in self.get_msg_struct_list(ident): val = None # Assume the signal to be full bytes only or within one byte if signal[1] > ...
The function decodes a log line from can-utils by splitting the input string to extract message data, converting hexadecimal values to integers, decoding the message, appending a timestamp, and applying filters. It returns the timestamp combined with the filtered decoded message.
def decode_log_line(self, string, keep_time=True, sep='; '): # Decode a line from a log file of the can-utils library msg = string.split()[-1].split('#') msg = self.decode(msg[0], [int('0x'+msg[1][i:i+2], 16) for i in range(0, len(msg[1]), 2)], sep) return self.get_timestamp(string, keep_time, type='log')...
def decode(self, ident, bytes, sep='; '): # Return a string with decoded signals try: sheet_dict = self.__get_sheet_dict(ident) ret_string = '0x'+str(ident)+sep for signal in self.get_msg_struct_list(ident): val = None # Assume the signal to be full bytes only or within one byte if signal[1] > ...
This function decodes a message string by extracting the CAN message ID and data bytes, converting them to hexadecimal format, decoding the message using a class method, appending a timestamp, and applying filters. It processes input strings containing 'ID:' and 'DLC:' identifiers, splits byte data, converts hex values...
def decode_message(self, string, keep_time=True, sep='; '): # Decode a message given as a String bytes = string.split('DLC:')[-1].split() id = string.split('ID:')[-1].split()[0] msg = self.decode(hex(int(id, 16))[2:], [int(bytes[i], 16) for i in range(1, int(bytes[0])+1)], sep)...
def set_board_for_find_a_check() -> chess.Board: while True: board = set_pieces_for_find_a_check() if check_if_either_side_is_in_check(board): continue break board.turn = chess.WHITE return board def convert_board_to_algebraic(board: chess.Board) -> dict: return { ...
The main task of the code is to simulate a checkers/chess game by allowing a user to input moves, validating them, and determining if each move results in a "check" state. The code repeatedly displays the board in algebraic notation, processes user moves, checks for validity, and outputs "Check" or "Not a check" accord...
def main(): board = set_board_for_find_a_check() while True: print("------------------------") print(board) # Show user the position in alg. form print("------------------------") board_alg = convert_board_to_algebraic(board) for color in board_alg: ...
def mkSolver(): solver = cvc5.Solver() # We will ask the solver to produce models and unsat cores, # hence these options should be turned on. solver.setOption("produce-models", "true"); solver.setOption("produce-unsat-cores", "false"); # The simplest way to set a logic for the solver is to choose "ALL". #...
This code evaluates the satisfiability of a logical formula using an SMT solver. It parses input terms, constructs a boolean formula, checks its validity, and returns a boolean result (true/false) based on the solver's output. It handles exceptions and undefined states by defaulting to false.
def run (self,term,data): try: module = term.symbol().getModule(); solver = mkSolver(); arg = next(term.arguments()); arg.reduce() vvs = module.parseTerm("getVVs(" + str(arg) + ",none)") vvs.reduce() vvsMap = dict(); # mkVars only if there are variables. if(str(...
def get_cursor(): loop = cursors_table.get_item( Key={ 'name': 'loop' }, AttributesToGet=[ 'position' ] ) year = cursors_table.get_item( Key={ 'name': 'last_year' }, AttributesToGet=[ 'value' ] ...
This Lambda function processes a list of songs by retrieving data for each entry, constructing a structured item with metadata, and persisting/updating records in a DynamoDB table. It iterates through song entries, handles data persistence via a cursor, and ensures continuous processing within a time limit. Extra field...
def handle(event, context): """ Lambda handler """ if PERSIST_DATA: current_id, last_year = get_cursor() else: current_id = 0 last_year = BEGIN_YEAR response = None now = begin_time = int(time.time()) while now < begin_time + LAMBDA_EXEC_TIME: # needs to...
def find_artists_twitters(artists): artists = [a['name'] for a in artists] found_one = False for i, artist in enumerate(artists): twitter = find_twitter(artist) if twitter: artists[i] = twitter found_one = found_one or True artists = remove_duplicates_insensitiv...
The function `tweet_record` retrieves Spotify track details, fetches associated artists' Twitter handles, and constructs a tweet containing the track name, year, playlist link, and genres. It uses MusicBrainz and Spotify APIs to gather data, then returns a formatted tweet if Twitter handles are found.
def tweet_record(spotify_track, year, playlist_id): musicbrainzngs.set_useragent("Resident Archive", "1.0", "https://residentarchive.com") spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) track = spotify.track(spotify_track) artists, found_one = find_artists_twitters(tra...
def get_request_text_from_selection(self) -> Tuple[str, int]: """Expands the selection to the boundaries of the request.""" selections = self.request_view.sel() pos = selections[0].a contents = self.request_view.substr(sublime.Region(0, self.request_view.size())) return contents,...
This code handles HTTP request execution in Sublime Text by retrieving selected text, parsing it into a request object, and executing it in a separate thread. It validates input, logs status updates, and manages thread execution for asynchronous request handling.
def run(self, *args: Tuple[Any]) -> None: print("Running Sublime REST", args) self.request_view = self.window.active_view() contents, pos = self.get_request_text_from_selection() if contents == "": self.log_to_status("Invalid request text: `{}`".format(contents)) ...
def _get_variables(contents: str) -> Mapping[str, str]: return {name: value for name, value in VARIABLES_RE.findall(contents)} def _get_request_block(contents: str, pos: int) -> str: top = contents.rfind(BOUNDARY, 0, pos) bottom = contents.find(BOUNDARY, pos) start = top if top != -1 else 0 end = bo...
The function `parse` constructs a `Request` object from given content and cursor position, parsing query parameters (same line or indented), headers (after method/URL), and body (with a blank line and required `Content-Type`). It applies variable substitution and handles formatting rules, raising a `ParserError` on inv...
def parse(contents: str, pos: int) -> Request: """ Constructs a Request object from the contents of the view and the position of the cursor in it. Query params can be set on the same line as the method and URL or in the lines immediately following if they are indented. Request headers can be s...
def edit_card(card, cat=card_cat): traits = ("Rename", *TK, "Done") # creates buttons # Display details as str msg = f"**{card[0]}**\n" for index, trait in enumerate(card[1]): msg += f" {TK[index]}: {trait}\n" choice = buttonbox(msg, "Edit Card", choices=traits) if choice == "Rename"...
This function reviews a card by displaying its details and allowing the user to edit, save, or cancel. If "Save" is chosen, the card is updated or added to the catalog. "Cancel" triggers a confirmation to discard changes. The function recursively calls itself after processing, ensuring the catalog is updated or unchang...
def review_card(card, cat=card_cat): # Display details as str msg = f"**{card[0]}**\n" for index, trait in enumerate(card[1]): msg += f" {TK[index]}: {trait}\n" choice = buttonbox(msg, "Review Card", ("Edit", "Save", "Cancel")) if choice == "Edit": card = edit_card(card) elif ...
def get_new_name(msg, title, orig_name=None, cat=card_cat): """Returns a str; the new name""" cards = [card[0] for card in cat] # collect card names new_name = enterbox(msg, title) if not new_name: return None new_name = new_name.capitalize() if new_name not in cards or orig_name and...
The code creates a monster card by prompting the user for a name and traits. It handles cancellations during input, confirms exit intentions, and compiles traits into a card for review. If canceled, it returns the original category; otherwise, it passes the card to a review function.
def create_card(cat=card_cat): title = "Create Card" name = get_new_name("Enter a name for your new monster card", title) if name is None: msgbox("You have exited the Create Card process", title) return cat traits = [] for trait in TK: while True: ...
def read_req(): with open("requirements.txt", "r") as req_file: req = set(line.strip() for line in req_file) return req def check_req(requirements): installed_packages = {pkg.key for pkg in pkg_resources.working_set} end_flag = 0 # Flag to indicate if any package is missing for package in...
The main task of the code is to process a dataset by filtering out existing UUIDs, cleaning text data, and using an API key to run GPT analysis on the remaining entries. It reads configuration parameters, prepares data from a specified input file, appends results to an output CSV, and restores the original working dire...
def main(): # GETTING THE DIRECTORY SET current_directory = os.getcwd() script_directory = os.path.dirname(os.path.realpath(__file__)) os.chdir(script_directory) # CHECKS FOR PACKAGES requirements = read_req() check_req(requirements) # LOAD IN CONFIG config = read_config() api...
def get_op(): op = vm.code[vm.ip] vm.ip += 1 return op def alu(a,op,b): a = value_of(a) b = value_of(b) match op: case '+'|'+=': return a+b case '-'|'-=': return a-b case '*'|'*=': return a*b case '/'|'/=': return a/b case '%'|'%=': return a%b case...
This function executes a virtual machine by processing a series of operations over `n_iters` iterations. It handles control flow commands like `halt`, `return`, `call`, `goto`, and `if`, updating the instruction pointer (vm.ip) and stack as needed. It also processes arithmetic operations via `alu`, storing results in m...
def run(n_iters): for i in range(n_iters): match t := get_op(): case 'halt': vm.ip -= 1 print(f'halt') case 'return': vm.ip = vm.stack.pop() print(f'return') case 'call': addr = get_op() ...
def init_central(self): initname = os.path.join(self.rootdir, self.args.initcentral) if os.path.exists(initname): utils.load_dict(initname, self.central) acc = self.validate_model(self.central) logging.info(f'Init Central--Acc:{(acc):.2f}') self.bestacc = ...
This function performs knowledge distillation in a federated learning setup by initializing local and central models, configuring optimizers/schedulers, training local models across multiple rounds with weighted averaging, and updating the central model. It handles dynamic party selection, learning rate scheduling, and...
def distill_local_central_joint(self): if self.args.initcentral: self.init_central() usecentral = True else: usecentral = False if self.args.C==1: selectN = self.locallist countN = self.countN localweight = countN/countN.sum...
def input_type(data, encoding): if isinstance(data, type(pathlib.Path())): # print("Path as input") # parse the file keep the first element with open(data, "r", encoding=encoding) as ini: for line in ini: missing_val = False # skip index declaratio...
The main task of the code is to convert a JSON input file into a YAML schema, normalize the filename by removing "en_" prefixes and handling "product3" cases, save the generated schema in a specified output directory, and return a YAML reference text pointing to the created schema file.
def yaml_schema(out_folder, in_file_path, output_encoding): start = time.time() if in_file_path.suffix != ".json": print() print("File type is not JSON:") print("\t", in_file_path) print() return data = input_type(in_file_path, output_encoding) # print(data) ...
def parse_file(in_file_path, input_encoding, xml_attribs): """ Parse an xml file with "xmltodict" external module and return the file as a dictionary and the extraction date. Can read the encoding of the file in the xml header if input_encoding=="auto" OR decode the file with the specified encoding. ...
This function converts Orphadata XML files into Elasticsearch-compatible JSON format by parsing input files, modifying data structures (e.g., renaming fields, cleaning text, casting numbers), handling special cases (e.g., product1, orphanomenclature), and outputting results to files or uploading to an Elasticsearch clu...
def process(in_file_path, out_folder, elastic, input_encoding, indent_output, output_encoding): """ Complete Orphadata XML to Elasticsearch JSON process :param in_file_path: input file path :param out_folder: output folder path :param elastic: URI to elastic node, False otherwise :param input_e...
def writeComment(self, cmd: str) -> None: """ Appends the input line as is to the VM code list. Use for comments, blank lines. """ self.code.append(cmd + '\n') def instruction(self, inst: str) -> None: """Writes a single instruction and increments the word count.""" ...
The code implements a function return in assembly by saving the return address, restoring the caller's stack pointer, and reinitializing frame pointers (THAT, THIS, ARG, LCL) from the saved frame, then jumping to the return address. It handles stack manipulation, address calculations, and register assignments to ensure...
def writeReturn(self, cmd: str) -> None: self.writeComment(f'// [{self.words}] {cmd}') # save LCL in R14 self.instruction( '@LCL') self.instruction( 'D=M') self.instruction( '@R14') self.instruction( 'M=D') # save return addr in R13 self.instruction( '@R13...
def SizeReduce(B): """ see Crypto Course """ B_temp = B.copy() # make hardcopy to not modify input matrix Bs = GS_J(B_temp) for i in range(1, len(B_temp)): x = Nearest_Plane(B_temp, B_temp[i] - Bs[i]) # print("x",x) B_temp[i] -= x return B_temp def GS_J(B): """ ...
The code implements the LLL algorithm to reduce a lattice basis. It performs size reduction on the input basis B, then iteratively swaps adjacent vectors if their Gram-Schmidt projections violate the Lovász condition (δ * ||π_i||² > ||π_{i+1}||²). This ensures the basis becomes nearly orthogonal and short. The process ...
def LLL_Crypt(B, delta): """ LLL algorithm see Crypto Course """ B_SR = SizeReduce(B) # print("checking",B_SR) Bs = GS_J(B) for i in range(len(B_SR) - 1): if delta * np.linalg.norm(pi_proj(B_SR[i], i, Bs)) ** 2 > np.linalg.norm(pi_proj(B_SR[i + 1], i, Bs)) ** 2: B_SR[[i,...
def GS_J(B): """ Gram schmidt-orthogonalization """ n = len(B) GS_B = np.zeros_like(B) for i in range(n): GS_B[i] = B[i] - (GS_B[:i] @ B[i] / np.diag(GS_B[:i] @ GS_B[:i].T)) @ GS_B[:i] return GS_B def sampleD(s, c, t, B): GSB=GS_J(B) normalization=np.diag(GSB@GSB.T) c_...
This code initializes a quantum system with parameters sigma, t, and B, setting up a dual basis and Gaussian states. It prepares pre-sampled data using a sampler, defines symplectic structures (J), and initializes logical shifts and partial sums for later computations in quantum error correction or Gaussian boson sampl...
def __init__(self, sigma, t, B, logicals, prestore_samples): self.sigma = sigma self.t = t self.B = B ####dual basis self.len = len(B) self.GSB = GS_J(B) self.sampler = sampleD(1/np.sqrt(2*np.pi*self.sigma**2), np.zeros(len(B)), t, B, self.GSB) self.N = int(len(B...
def Thatsigma(f): temp=np.zeros((len(f), len(f))) for i in range(len(f)): temp[i]=sigma(np.roll(f,-i)) return temp def That(f): temp=np.zeros((len(f), len(f))) for i in range(len(f)): temp[i]=np.roll(f,-i) return temp def pub_basis(h,q,n): pk=That(h) print("...
The code initializes an object for lattice-based cryptographic analysis, loading NTRU-related data (h, f_vec, g_vec) from a file, computing transformed matrices (T_bar_h, That_sigma_f), constructing public and secret basis vectors, and preparing structures for error probability calculations (p_err, p_check) and Babai's...
def __init__(self, sigmas, n, q, p_list, d, prefix, folder, NUM_MAX, precision=8, inv=False): self.folder = folder self.inv = inv self.NUM_MAX = NUM_MAX self.precision = precision self.sigmas = sigmas self.n = n self.p_list = p_list self.d = d se...
def Jsym(n): J1=np.asarray([[0,1],[-1,0]]) J=np.kron(J1,np.eye(n)) return J def sample_err(n,sig,bias,shots): dq=normal(0,sig*bias,size=(shots,n)) dp=normal(0,sig/bias,size=(shots,n)) return np.concatenate([dq,dp],axis=1) def triv_syndrome(e, scale): return balancedmod_ar(e,1) def balan...
The function `simulateNTRU` simulates the NTRU decryption process to evaluate error probabilities and check success rates. It iteratively generates error vectors, computes syndromes, decodes using NTRU parameters, and checks if the results meet expected conditions (e.g., zero syndromes). It counts successful checks and...
def simulateNTRU(sig, M, That_sigma_f, That_sigma_hinv, n, q, p, NUM_max, precision=12): NUM_tot = 0 count_err = 0 count_CHECK = 0 J = Jsym(n) # print(sig) seed(int(sig * 200 * That_sigma_f[2, 2] + int(time())) % 127239) while NUM_tot < NUM_max: NUM_tot += 1 err = sample_er...
def boundary_check(x,y): if x > 9 or x < 0 or y > 9 or y < 0: return False return x, y def current_box(co_ordinate, _board:List[List[boxNode]]): x,y = co_ordinate if not _board[x][y].stench and not _board[x][y].breeze: logic_formulation(co_ordinate, "Blank") if _board[x][y].stench: ...
This function performs a backward-chaining search on a grid to locate a cell with 'glitter'. It uses a fringe (queue) to explore positions, checking adjacent cells recursively. If a cell with glitter is found, it prints coordinates and exits; otherwise, it continues exploring valid neighboring cells until the fringe is...
def backward_chaining(fringe, board): if not fringe.empty(): x, y = fringe.get() #resulation here if board[x][y].glitter ==True: print("Here", x, y) print("Found") exit() valid = [boundary_check(x + 1, y), boundary_check(x, y + 1), boundary_check(x - 1, y), b...
def append_to_stream_log(self, v: str): # short output to avoid flooding logs but show bot is still running and parsing posts self.stream_log += v if len(self.stream_log) > 50: logger.info(self.stream_log) self.stream_log = "" def parse_submission(self, submission: Submis...
The code processes a submission by parsing it, logging debug information if enabled, handling comment-related delays if the submission is commented, and deleting bad comments. The main task is to manage submission handling with logging, comment sleep, and cleanup.
def handle_submission(self, submission: Submission): self.append_to_stream_log("-") commented, msg = self.parse_submission(submission) if msg: if getattr(logging, LOGLEVEL) <= logging.DEBUG: submission_dict = dict(submission.__rich_repr__()) submission...
def open_workbook(self): ''' Tries to open the workbook, gives an error if it fails to open the file ''' try: self.workbook = openpyxl.load_workbook(self.filename, data_only=self.data_only) return self.workbook except PermissionError: #...
The code creates Excel sheets for each month, sorts transactions by total value, and populates category data. It opens a workbook, iterates through monthly transactions, formats sheets, checks data types, and saves the workbook.
def write_month_transactions(self) -> None: ''' create excelsheets for all the months, and writes the categories and theri totals. Then calls the write_column_transactions function to fill out all the transactions per category ''' self.open_workbook() #...
def initDataloader(self,isValSet, val_stride=10, context_slices=3): if isValSet: dataset = Luna2dSegmentationDataset( val_stride=val_stride, isValSet=isValSet, contextSlices=context_slices ) else: dataset = TrainingLuna2...
The main task of the code is to train a model using a training data loader and validate it periodically with a validation data loader. It logs training and validation metrics, saves the model when validation performance improves, and runs validation every 5 epochs or on the first epoch. The loop iterates for a specifie...
def main(self): train_dl = self.initDataloader(False, 10, 3) val_dl = self.initDataloader(True, 10, 3) best_score = 0.0 for epoch_ndx in range(1, self.cli_args.epochs + 1): train_metrics = self.doTraining(epoch_ndx, train_dl) self.logMetrics(epoch_ndx,...
def CubeToString(C): str = ''.join(list(map(hex, C))) return str def TransformRubiks2x2(CubeCorners, Move): NewCubeCorners = CubeCorners[:] match Move: case "T": TransformRubiks2x2_T(CubeCorners, NewCubeCorners) case "T'": TransformRubiks2x2_rT(CubeCorners, NewCub...
The code recursively explores all possible move sequences up to a specified maximum depth to solve a 2x2 Rubik's Cube. It tracks visited cube states and their shortest solution paths to avoid redundant computations. For each state, it applies predefined moves, generates new cube configurations, and recursively continue...
def FindAllSolutionsRecursive(Cube, SolutionsCubes, SolutionsCubePaths, Step, MaxStep, Moves): #print('FindAllSolutionsRecursive', Step) CubeAsString = CubeToString(Cube) #print(CubeAsString) if CubeAsString in SolutionsCubes: #print('Seen Before:') CurrentBestPath = SolutionsCubePaths[C...
def CubeToString(C): str = ''.join(list(map(hex, C))) return str def TransformRubiks2x2(CubeCorners, Move): NewCubeCorners = CubeCorners[:] match Move: case "T": TransformRubiks2x2_T(CubeCorners, NewCubeCorners) case "T'": TransformRubiks2x2_rT(CubeCorners, NewCub...
This recursive function explores all possible move sequences up to MaxStep to find the shortest path solving a 2x2 Rubik's Cube. It tracks visited cube states, avoids redundant paths, and stores optimal move sequences in FoundCubePaths. For each state, it applies all valid moves, recursively explores new states, and pr...
def FindShortestPathsRecursive(Cube, FoundCubes, FoundCubePaths, Step, MaxStep, Moves): #print('FindShortestPathsRecursive', Step) CubeAsString = CubeToString(Cube) #print(CubeAsString) if CubeAsString in FoundCubes: #print('Seen Before:') CurrentBestPath = FoundCubePaths[CubeAsString] ...
def create_security_group(security_group_config, description='my description'): # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2/client/create_security_group.html created_security_group = ec2_client.create_security_group(GroupName=security_group_config["GroupName"], Description=d...
The code deploys clusters by creating security groups, setting up instances, and configuring rules with increasing priorities. It handles AWS authentication errors and other exceptions by tearing down resources and exiting. Finally, it saves deployment details including clusters, rules, and security group IDs for futur...
def run(): clusters = {} # instance ids, target_group_arn rules = {} # rules security_group_ids = [] try: for cluster_config in deployment_configs: print(cluster_config) security_group_id = create_security_group(security_group_config=cluster_config['security_group']) ...
def _init_app_models_file(self, app): if not os.path.isfile(__import__(app).__path__[0] + '/' + self.models_container): models_file = open(__import__(app).__path__[0] + '/' + self.models_container, 'w+') models_file.close() def _process_models_data(self, app): with open(__import_...
The code's main task is to initialize and configure model-related components for each internal application by iterating through a list of internal apps. It performs three key steps per app: initializing model files, processing model data, and building model structures, ensuring each application's data models are proper...
def __init__(self): for app in settings.INTERNAL_APPS: self._init_app_models_file(app) self._process_models_data(app) self._build_models(app)
def instantiate_model(self, block_size: int, vocab_size: int, ): # model = Sequential([ # Embedding(vocab_size, self.n_embd), # FlattenConsecutive(2), Linear(self.n_embd * 2, self.n_hidden, bias=False), BatchN...
This code trains a neural network model on a names dataset by loading the data, initializing the model architecture, setting up training parameters, and executing the training process with specified hyperparameters like block size, learning rate, and maximum steps. It returns trained model parameters, loss history, and...
def __call__(self, block_size: int = 3, max_steps: int = 100, lr: float = 0.1, ): dataset = Dataset(path=r'C:\Users\CD138JR\Documents\GitHub\gpt\names.txt', block_size=block_size) Xtr, Ytr, Xdev, Ydev, Xte, Yte...
def load_custom_metals(drop): # Tries to open the file, if it can't, catches exception and tells user i = 0 try: f = open("data/custom_metals.dat", "rb") # Once the file is open, keeps trying to read it until it reaches the end of the file while 1: try: # ...
The code implements an interactive physics simulation of the photoelectric effect, allowing users to adjust light wavelength, intensity, and metal type via sliders and dropdowns. It handles user input, updates photon/electron behavior, calculates stopping voltage, and renders visual elements. The loop also supports cre...
def game_loop(): # Creating the loop boolean, this is false until the game exits game_exit = False # Starting value definitions wavelength = 0 intensity = 0 # Appends default metals to the metal list Metal.MetalList.append(Metal("Sodium", 3.65 * math.pow(10, -19), (100, 100, 100))) Met...
def convolutional_layer(input_x, shape): W = init_weights(shape) b = init_bias([shape[3]]) return tf.compat.v1.nn.relu(conv2d(input_x, W) + b) def max_pool_2by2(x): return tf.compat.v1.nn.max_pool2d(input=x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') ...
This code defines a convolutional neural network (CNN) model for MNIST digit classification, including two convolutional layers with max pooling, a fully connected layer with dropout regularization, softmax cross-entropy loss, and Adam optimizer, while setting up placeholders for input data, labels, and dropout probabi...
def _build_mnist_model(self): self.image_input = tf.compat.v1.placeholder(tf.float32, shape=[None, 784], name="X") self.actual_label = tf.compat.v1.placeholder(tf.float32, shape=[None, 10], name="y_true") x_image = tf.reshape(self.image_input, [-1, 28, 28, 1]) with tf.name_scope("Conv...
def make_matrix_section(self): confusion_heading_str = "# Confusion Matrix Against Validation Set\n" confusion_desc = "The multi-class confusion matrix captures the true labels along the columns and the predicted labels along the rows. The cells contain counts for the intersection of true labels and p...
The code generates an evaluation report in Markdown format by writing three sections—matrix, ROC curve, and evaluation dataset—into a specified file within the designated directory.
def write_evaluation_report(self, name): with open(f"{self.write_directory}/{name}.md", "w") as report_out: report_out.write(self.make_matrix_section()) report_out.write(self.make_roc_section()) report_out.write(self.make_evaluation_dataset_section())
def make_introduction_section(self): heading = "# Overview \n" introduction = str(self.introduction) + "\n" return heading + introduction def make_hyperparameters_section(self): heading = "# Hyperparameters \n" section_desc = "This section documents the hyperparameters used fo...
The code generates a Markdown report by writing predefined sections—introduction, hyperparameters, metrics, datasets, and examples—into a file named after the provided 'name' argument, saving it in the specified 'write_directory'
def write_report(self, name): with open(f"{self.write_directory}/{name}.md", "w") as report_out: report_out.write(self.make_introduction_section()) report_out.write(self.make_hyperparameters_section()) report_out.write(self.make_metrics_section()) report_out.write...
def render_title(self): text = self.elements['title'] height, width = self.stdscr.getmaxyx() start_y = int((width // 2) - (len(text) // 2) - len(text) % 2) self.stdscr.addstr(0, 0, f"{' ' * self.get_width()}", self.CONTRAST) self.stdscr.addstr(0, start_y, text, self.CONTRAST) def render_chyron(self)...
This code initializes a curses-based terminal interface with color themes, navigation (arrow keys), selection toggling (space), and panel rendering. It manages a menu system where users can navigate options, select items, and trigger actions (Enter). The loop handles input, updates the UI with borders, color-coded elem...
def run(self, stdscr): self.stdscr = stdscr self.stdscr.border( 0 ) self.stdscr.keypad(1) curses.noecho() curses.cbreak() curses.curs_set( 0 ) curses.start_color() curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) ...
def __most_common_label(self,y): counter = Counter(y) most_common = counter.most_common(1)[0][0] return most_common def __best_criteria(self,X,y,feat_idxs): best_gain = -1 split_idx,split_threh = None,None for feat_idx in feat_idxs: X_column = X[:,feat_idx] ...
The code recursively builds a decision tree by splitting data based on selected features until stopping conditions (max depth, single label, or insufficient samples) are met, then returns a node with the best split and child subtrees.
def __grow_tree(self,X,y,depth=0): n_samples, n_features = X.shape n_labels = len(np.unique(y)) # stopping criteria if (depth>=self.max_depth or n_labels==1 or n_samples<self.min_samples_split): leaf_value = self.__most_common_label(y) return Node(value=leaf_value...
def get_speech_input(try_count=0, max_tries=3): if try_count > max_tries: speak("It seems we're having trouble with the connection.I will call you latter. Goodbye!") return None r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) audio = r....
The code's main task is to determine the user's gender from speech input by checking for "male" or "female" keywords. If neither is detected, it recursively prompts the user until a valid input is provided, then returns the identified gender.
def extract_gender(): user_input = get_speech_input().lower() if "male" in user_input: gender = "male" elif "female" in user_input: gender = "female" else: speak("Can't understand. Please provide valid gender (male or female).") return extract_gender() return gender
def get_speech_input(try_count=0, max_tries=3): if try_count > max_tries: speak("It seems we're having trouble with the connection.I will call you latter. Goodbye!") return None r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) audio = r....
The main task of the code is to extract the last numeric value from a user's speech input, converting spoken number words (e.g., "ten") to their numeric equivalents, and returning it as a float or integer. If no valid numeric value is found, it prompts the user again.
def extract_numeric_value(): user_input = get_speech_input() numeric_values = [] numeric_str = "" number_mapping = { "zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8...
def get_speech_input(try_count=0, max_tries=3): if try_count > max_tries: speak("It seems we're having trouble with the connection.I will call you latter. Goodbye!") return None r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) audio = r....
The code extracts the last occurrence of either "yes" or "no" from user speech input, returns the corresponding 3-character substring (e.g., "yes" or "no"), and recursively prompts for input if neither keyword is detected.
def extract_binary_category(): user_input = get_speech_input().lower() if "yes" in user_input or "no" in user_input: last_occurrence_yes = user_input.rfind("yes") last_occurrence_no = user_input.rfind("no") last_occurrence = max(last_occurrence_yes, last_occurrence_no) category_...
def get_speech_input(try_count=0, max_tries=3): if try_count > max_tries: speak("It seems we're having trouble with the connection.I will call you latter. Goodbye!") return None r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) audio = r....
The code extracts a job title from user speech input by checking if any unique job title from a dataset matches the input case-insensitively. If no match is found, it prompts the user to provide a valid job title recursively.
def extract_job_title(): user_input = get_speech_input().lower() job_titles = original_df["job_title"].unique() for job_title in job_titles: if job_title.lower() in user_input: return job_title speak("Can't understand. Please provide a valid job title.") return extract_job_titl...
def speak(response): engine = pyttsx3.init() voice = engine.getProperty("voices") engine.setProperty("voice", voice[1].id) engine.setProperty('rate', 180) engine.setProperty("volume", 0.9) engine.say(response) engine.runAndWait() log_interaction(f"AI said: {response}") def get_speech_inp...
The code extracts hereditary diseases from user input by checking if the response is "yes" or "no". If "yes", it prompts for specific diseases, matches them against a predefined list, and returns the identified diseases. If no match, it requests clarification. If "no", it returns ["NoDisease"]. Invalid inputs trigger r...
def extract_hereditary_diseases(user_hereditary_diseases): user_hereditary_diseases_lower = user_hereditary_diseases.lower().strip() if user_hereditary_diseases_lower == "yes": speak("Could you specify which hereditary diseases are present in your family?") command = get_speech_input() ...
def speak(response): engine = pyttsx3.init() voice = engine.getProperty("voices") engine.setProperty("voice", voice[0].id) engine.setProperty("rate", 180) engine.setProperty("volume", 0.9) engine.say(response) engine.runAndWait() log_interaction(f"AI said: {response}") def get_speech_inp...
This code extracts and converts date-time information from a sentence by replacing relative terms like "tomorrow" and weekdays with specific dates, then parsing the result. It ensures the parsed date is valid and not in the past, prompting for input if invalid.
def extract_date_time(sentence): today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) sentence = sentence.replace( "tomorrow", (today + timedelta(days=1)).strftime("%Y-%m-%d") ) weekdays = [ "monday", "tuesday", "wednesday", "thursday", ...
def find_angle(self, robot_observation, smooth=False, append_to_list=False): angle = self.find_angle_helper(robot_observation) % 1 self.data["unsmoothed_angles"].append(angle) self.data["robot_angles"].append(robot_observation[0] % 1) if not append_to_list: self.data["smoothe...
The code controls a robot's movement by calculating angular acceleration based on observed environmental data (top, left, bottom, right) and adjusting linear acceleration (lin_acc) using edge detection logic (rising/falling edges). It tracks timing and state variables (vroomed, counter_since_vroom) to determine when to...
def get_action(self, robot_observation): self.i += 1 self.counter_since_vroom += self.vroomed angle = self.find_angle(robot_observation, append_to_list=self.vroomed, smooth=self.counter_since_vroom >= 40) ca, top, left, bottom, right = robot_observation self.data["tops"]...
def detectFileFormat(filename): imgend = ['jpg','JPG','png','PNG','JPEG','jpeg'] movend = ['mov','MOV','mp4'] if filename.split('.')[-1] in imgend: fileformat = 'img' elif filename.split('.')[-1] in movend: fileformat = 'mov' else: raise ValueError('invalid file-format') ...
This function detects a white A4 paper in an image or video, extracts the number written on it, and returns the recognized number. For images, it optionally returns the image with a bounding box around the paper. Supported formats include images (jpg, png, etc.) and videos (mov, mp4). Video processing returns only the ...
def detectNum(filename,returnimage=False): ''' Function that detects the white A4 paper and recognises the number written on it input: image or movie supported formats: ['jpg','JPG','png','PNG','JPEG','jpeg','mov','MOV','mp4'] returnimage: optional switch that returns the image with a bounding box a...
def transform(m): sum_list = list(map(sum, m)) bool_indices = list(map(lambda x: x == 0, sum_list)) indices = set([i for i, x in enumerate(bool_indices) if x]) new_mat = [] for i in range(len(m)): new_mat.append(list(map(lambda x: Fraction(0, 1) if(sum_list[i] == 0) else simplify(x, sum_list...
The code solves a matrix equation by transforming the input matrix `m`, splitting it into Q and R matrices, computing the inverse of Q, and multiplying it with R. It then processes the resulting row to compute the least common multiple (LCM) of denominators, converts elements to integers using this LCM, and appends the...
def solution(m): res = transform(m) if res[1] == len(m): return [1, 1] Q, R = splitQRmatrices(*res) inverse = inverseOfMatrixQ(Q) res = matrixMultiply(inverse, R) row = res[0] l = 1 for item in row: l = lcm(l, item.denominator) res = list(map(lambda x: int(x.numerator...
def _process_hosts(self, search_type, action_result, request_params, host_dict): """ Returns dictionary of hosts retrieved and appends quest type to reason field for host """ ret_val, response = self._make_rest_call('/hosts', action_result, params=request_params) if phantom.is_fa...
The main task of this code is to retrieve and process network host data and detections based on configured parameters (tags, scores, detection types), compile results into summaries, and update system status. It queries hosts/detections, converts data to JSON, manages containers, and logs counts of retrieved hosts, det...
def _handle_on_poll(self, param): self.save_progress(('In action handler for: {0}').format(self.get_action_identifier())) action_result = self.add_action_result(ActionResult(dict(param))) config = self.get_config() retrieved_hosts = {} retrieved_detections = {} unblocked_...
def _handle_test_connectivity(self, param): action_result = self.add_action_result(ActionResult(dict(param))) self.save_progress('Connecting to endpoint') ret_val, response = self._make_rest_call('', action_result) if phantom.is_fail(ret_val): self.save_progress(('Test Connec...
The code defines a method `handle_action` that routes incoming requests to specific handler methods based on the action identifier. It retrieves the action ID, logs it, and executes the corresponding private method (`_handle_*`) to process the request. The result from the handler is returned as the method's output, ena...
def handle_action(self, param): ret_val = phantom.APP_SUCCESS action_id = self.get_action_identifier() self.debug_print('action_id', self.get_action_identifier()) if action_id == 'test_connectivity': ret_val = self._handle_test_connectivity(param) elif action_id == 'l...
def _update_domain_seen_count(self,url): if url in self._seen_domains: self._seen_domains[url]['count'] += 1 else: self._add_to_seen_domains(url,1,0) return def _extract_request_documentation(self,api_name,response): data_array = [] for regex in RestReque...
This code parses API documentation from web pages, extracts relevant data, and recursively crawls linked pages while respecting limits (max 500 requests) and allowed domains/schemes. It yields extracted data and follows links to continue parsing, ensuring compliance with domain and URL constraints.
def docs_parse(self,response,api_name,count): if count >= 500: print(response.url,count) return self._update_domain_seen_count(urllib.parse.urlparse(response.url).netloc) data_array = self._extract_request_documentation(api_name,response) for match_dict ...
def docs_parse(self,response,api_name,count): if count >= 500: print(response.url,count) return self._update_domain_seen_count(urllib.parse.urlparse(response.url).netloc) data_array = self._extract_request_documentation(api_name,response) for match_dict ...
The code shuffles API data, generates requests for each API's documentation URL, and yields Scrapy Requests with a callback to parse responses. It adds domains to allowed/seen lists and handles empty URLs by catching TypeErrors.
def start_requests(self): random.shuffle(self.api_data) for api in self.api_data: try: parse_lambda = lambda response,api_name=api['api_name']: self.docs_parse(response,api_name,0) self._add_to_allowed_domains(api['doc_url']) self._add_to_seen_...
def leaf(self, branch): # Take the class value from each sample remaining in the branch print('Making leaf!') counts = [branch[eachRow][41] for eachRow in range(len(branch))] return max(set(counts), key=counts.count) def next_branch(self, data): # The feature used for a branch ...
This function recursively splits a decision tree branch into left and right sub-branches, stopping when depth limits, minimum sample sizes, or empty branches are reached. It assigns leaf nodes when termination conditions are met, otherwise continues splitting recursively, incrementing depth for each new branch.
def branch_split(self, branch, maxDepth, minSize, depth): print('Now with ', depth, ' branches!') includedSamples = float(len(branch['branches'][0]) + len(branch['branches'][1])) print('Partition size', includedSamples) # assign the decided branches for splitting branch['leftBran...
def InitStatisticsParameters(episode_path, INF=1e18): episode_name = FileName(episode_path) episode_name = episode_name[:len(episode_name) - 4] stats = {actor: 0 for actor in reference_people} stats["episode_num"] = episode_name last_frame_detecting_ = {actor: -INF for actor in reference_people} ...
This function processes a video episode to calculate statistics on person locations, updating a DataFrame. It reads frames, updates stats every 'step' frames, displays labeled images, and allows user interaction (space to pause, 0 to stop). Final stats are appended to the output DataFrame, returning it along with a sta...
def CalculateStatsByEpisode(episode_path="", output_df=None, step=200, waiting_time=1): cap, frame_id, stats, last_frame_detecting_ = InitStatisticsParameters(episode_path) while cap.isOpened(): ret, frame = cap.read() if not ret: break if frame_id % step == 0: st...
def __get_values(self, data): if isinstance(data, pd.DataFrame) or isinstance(data, pd.Series): return data.values return data def _loss(self, y, probs): losses = np.zeros((self.n_outputs_, y.shape[0])) for k, y_k in enumerate(self.unique_outputs_): y_i = y == y_k...
The code trains an ensemble of decision trees for probabilistic regression, iteratively minimizing a loss function by updating predictions through residual fitting. It initializes regressors, computes probabilities from current estimates, and fits each tree to residuals of specific output classes. Estimations are adjus...
def fit(self, X, y): X_ = self.__get_values(X) y_ = self.__get_values(y) self.regressors_ = [] self.unique_outputs_ = np.unique(y_) self.n_outputs_ = len(self.unique_outputs_) estimations = np.zeros((self.n_outputs_, len(y_))) self.loss_ = np.inf stable_lo...
def count_class(self, y): # Parameters: y: list, target values. self.class_number_ = max(y) + 1 self.logn_ = np.log(self.class_number_) return def count_var(self, X): # Parameters: X: array-like, shape (n_samples, n_features), the provided dataset. self.var_numb...
This code trains a decision tree classifier by combining input features (X) and target labels (y) into a unified dataset, then constructing a decision tree structure via the build_tree method. It initializes class and feature counts, prepares training data, and returns the trained tree model for prediction.
def fit(self, X, y): # Parameters: X: array-like, shape (n_samples, n_features), the training input data, y: array-like, shape (n_samples,), the target values. # Returns: self: This decision tree object. self.count_class(y) self.count_var(X) # Adds the labels and featur...
def check_label_existence(value_label, usr_utt_tok): in_usr, usr_pos = get_token_pos(usr_utt_tok, value_label) # If no hit even though there should be one, check for value label variants if not in_usr and value_label in LABEL_MAPS: for value_label_variant in LABEL_MAPS[value_label]: in_u...
This function classifies user utterance tokens based on value and inform labels, determining if the value is copied, informed, referred, or unpointable. It marks relevant tokens, identifies informed values, checks slot referrals, and returns classifications along with labeled tokens and slot information.
def get_turn_label(value_label, inform_label, sys_utt_tok, usr_utt_tok, slot, seen_slots, slot_last_occurrence): usr_utt_tok_label = [0 for _ in usr_utt_tok] informed_value = 'none' referred_slot = 'none' if value_label == 'none' or value_label == 'dontcare' or value_label == 'true' or value_label == 'f...
def load_acts(input_file): with open(input_file) as f: acts = json.load(f) s_dict = {} for d in acts: for t in acts[d]: # Only process, if turn has annotation if isinstance(acts[d][t], dict): for a in acts[d][t]: aa = a.lower().spli...
The main task of the code is to process dialogue data from a JSON file into structured DSTExample objects for dialogue state tracking. It extracts utterances, tracks slot modifications, handles delexicalization, manages user-system turn alternation, and constructs examples with labeled spans, historical context, and me...
def create_examples(input_file, acts_file, set_type, slot_list, label_maps={}, append_history=False, use_history_labels=False, swap_utterances=False, label_value_repetitions=False, delexicalize_sys_ut...
def get_args(): """Set up command-line interface and get arguments.""" parser = argparse.ArgumentParser() parser.add_argument("-p", "--predictions_file", type=str, default="/predictions.zip") parser.add_argument("-g", "--goldstandard_file", type=str, defau...
The main task of the code is to validate a submission file (e.g., a ZIP archive containing NIfTI files) against a gold standard, ensuring it meets format requirements (e.g., correct entity type, file structure, and filename patterns). It checks for errors like invalid entity types, missing files, or mismatched patterns...
def main(): """Main function.""" args = get_args() invalid_reasons = [] entity_type = args.entity_type.split(".")[-1] if entity_type != "FileEntity": invalid_reasons.append( f"Submission must be a File, not {entity_type}." ) else: preds = utils.inspect_zip(ar...
def get_relevant_length(values): total_values = len(values) if total_values != 0: return total_values - 1 else: return total_values def track_param_jumping_limit(value, nextValue, maxDelta): if nextValue - value > maxDelta: return False return True def checkInputIsEmpty(values, param...
The function validates a parameter's values by checking if consecutive readings exceed a specified jump threshold and ensures the input is not empty. It iterates through the values, returning False if any adjacent pair violates the threshold, then checks if the input is empty, returning the result accordingly.
def validate_param_reading(values, param_name, param_jump_threshold): last_but_one_reading = get_relevant_length(values) for i in range(last_but_one_reading): if(not track_param_jumping_limit(values[i], values[i + 1], param_jump_threshold)): return False return checkInputIsEmpty(values, param_name)