dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def run_command(command_body, cwd=OS_CWD, ignore_error=True, except_in=MyException.command_error): if (DRY_RUN): return dummy_run_result() else: with settings(warn_only=True): command_to_run = 'cd {} && {}'.format(cwd, command_body) command_result = local(command_to_run, capture=True) pri...
This function processes a feature branch by cloning it, merging into a 'pre-merge' branch, and conditionally pushing the merged commit. It clones the repository using the provided URI and branch, merges changes into a pre-merge branch, and pushes the result to the remote repository unless 'no_push_uri' is True.
def process_feature_branch(PUSH_URI, feature_branch_in, cwd, no_push_uri = False): branch_name = get_branch_name(feature_branch_in) pre_merge_branch = 'pre-merge/'+branch_name # CAUTION: using cwd inside run_command run_command('git clone -b {} {} .'.format(feature_branch_in, PUSH_URI), cwd) merge_to_pre...
def run_command(command_body, cwd=OS_CWD, ignore_error=True, except_in=MyException.command_error): if (DRY_RUN): return dummy_run_result() else: with settings(warn_only=True): command_to_run = 'cd {} && {}'.format(cwd, command_body) command_result = local(command_to_run, capture=True) pri...
The function `process_fix_branch` clones a repository branch, merges it into a pre-merge branch, and optionally pushes the merged changes. It takes a branch name, repository URI, working directory, and a flag to skip pushing. Key steps include cloning the branch, merging into a pre-merge branch, and conditionally pushi...
def process_fix_branch(PUSH_URI, fix_branch_in, cwd, no_push_uri = False): branch_name = get_branch_name(fix_branch_in) pre_merge_branch = 'pre-merge/'+branch_name # CAUTION: using cwd inside run_command run_command('git clone -b {} {} .'.format(fix_branch_in, PUSH_URI), cwd) merge_to_pre_merge_branch(fix_...
def categorize_branch(branch_to_test): if branch_to_test[0:4] == 'fix/': return CONST_BRANCH_FIX elif branch_to_test == 'develop': print('findme') return CONST_BRANCH_DEVELOP elif branch_to_test == 'pre-merge-master': return CONST_BRANCH_PRE_MERGE_MASTER elif branch_to_test[0:8] == 'feature/': ...
The main task of the code is to determine the type of the triggering branch and execute the corresponding merge process. It routes branches like test, feature, fix, or pre-merge to specific processing functions, directing merges to target branches (e.g., feature → pre-merge, develop → pre-merge-master). It handles depe...
def main(PUSH_URI, TEMP_DIR): print('starting merger') print(f'triggering branch {TRIGGERING_BRANCH}') if categorize_branch(TRIGGERING_BRANCH) == CONST_BRANCH_TEST: # test branch will merge to feature branch print("this is test branch, will checkout to feature branch") process_test_branch(PUSH_URI, ...
def style(self): font_color = '#d4d4d4' background_dark = '#303030' background_light = '#3a3e40' selection_color = '#324d80' error_msg_color = '#a13030' style = ttk.Style() style.theme_use('default') style.configure('test.TFrame', background='red') #All f...
The code initializes a Tkinter GUI application for a sleep wellness initiative, setting up the main window, loading data, configuring UI style, and displaying either a login screen or dashboard based on a debug flag. It prepares the interface for user interaction and data handling.
def __init__(self) -> None: self.root = tk.Tk() self.root.title('SleepWell - Trivselsinitiativ') self.root.geometry('1280x900') self.data = Data() self.current_occupation = 'All' self.style() self.display_page_layout() skiplogin = False # Debug: Set t...
def permute(table, src_width, src): tb_length = len(table) result = [0]*tb_length for i, location in enumerate(table): result[i] = src[location-1] #table start from 1 return ''.join(result) def transformation(table, i, direction, c, d):#pass in PC2 table if direction == 'left': shift...
The code implements the Data Encryption Standard (DES) algorithm. It converts hexadecimal inputs (message and key) to binary, applies initial permutations, processes the key through 16 rounds of transformations (including XOR operations and function f), and performs a final permutation to produce a 64-bit ciphertext. T...
def DES_encrypt(msg, key): try: msg = int(msg, 16) bi_msg = bin(msg)[2:].zfill(64) print('msg', bi_msg) except: print('Plain text has to be a valid hex') try: key = int(key, 16) bi_key = bin(key)[2:].zfill(64) print('key', bi_key) except: ...
def shifting_rules_r(): shift_nums = [26]*16 one_bit_round = [2,9,16] shift_nums[0]=28 for elem in one_bit_round: shift_nums[elem-1] = 27 return shift_nums def permute(table, src_width, src): tb_length = len(table) result = [0]*tb_length for i, location in enumerate(table): ...
The code implements the Data Encryption Standard (DES) decryption algorithm. It converts hexadecimal inputs to binary, applies initial permutation, splits data into halves, performs 16 rounds of Feistel network operations using a key schedule, and applies final permutation to produce decrypted output in hexadecimal for...
def DES_decrypt(cipher, key): try: cipher = int(cipher, 16) bi_cipher = bin(cipher)[2:].zfill(64) print('cipher', bi_cipher) except: print('Plain text has to be a valid hex') try: key = int(key, 16) bi_key = bin(key)[2:].zfill(64) print('key', bi_key)...
def create_random_list(length, max_value): return [random.randint(0, max_value) for _ in range(length)] def quicksort(L): copy = quicksort_copy(L) for i in range(len(L)): L[i] = copy[i] def mergesort(L): if len(L) <= 1: return mid = len(L) // 2 left, right = L[:mid], L[mid:] ...
The code `experimentOne` compares the performance of three sorting algorithms (Quicksort, Mergesort, Heapsort) by measuring their average execution time over `n` trials on random lists of size `size`. For each trial, it generates three identical lists, sorts each using a different algorithm, records the time taken, and...
def experimentOne(size, n): totalQuick = 0 totalMerge = 0 totalHeap = 0 for _ in range(n): L1 = create_random_list(size, 1000) L2 = L1.copy() L3 = L1.copy() ## Quicksort start = timeit.default_timer() quicksort(L1) end = timeit.default_timer...
def create_near_sorted_list(length, max_value, swaps): L = create_random_list(length, max_value) L.sort() for _ in range(swaps): r1 = random.randint(0, length - 1) r2 = random.randint(0, length - 1) swap(L, r1, r2) return L def quicksort(L): copy = quicksort_copy(L) for i...
The code compares the performance of Quicksort, Mergesort, and Heapsort by measuring their average runtime over `n` trials. Each trial generates a nearly sorted list with `swaps` random swaps. The function runs each sorting algorithm on copied lists, records their execution times, and accumulates totals. Finally, it re...
def experimentTwo(swaps, n): totalQuick = 0 totalMerge = 0 totalHeap = 0 for _ in range(n): L1 = create_near_sorted_list(1000, 1000, swaps) L2 = L1.copy() L3 = L1.copy() ## Quicksort start = timeit.default_timer() quicksort(L1) end = timeit.defa...
def create_random_list(length, max_value): return [random.randint(0, max_value) for _ in range(length)] def insertion_sort(L): for i in range(1, len(L)): insert(L, i) def selection_sort(L): for i in range(len(L)): min_index = find_min_index(L, i) swap(L, i, min_index) def bubble_sort...
The code measures and compares the average performance of insertion sort, selection sort, and bubble sort by running each algorithm on multiple random lists of specified size, accumulating their execution times over `n` trials, and returning the total time for each sort.
def experimentOne(size, n): totalBub = 0 totalIns = 0 totalSel = 0 for _ in range(n): L = create_random_list(size, 1000) # (# of elements, max value) L2 = L.copy() L3 = L.copy() # Insertion sort start = timeit.default_timer() insertion_sort(L) end...
def create_near_sorted_list(length, max_value, swaps): L = create_random_list(length, max_value) L.sort() for _ in range(swaps): r1 = random.randint(0, length - 1) r2 = random.randint(0, length - 1) swap(L, r1, r2) return L def bubble_sort(L): for i in range(len(L)): ...
The function `experimentTwo` compares the average time complexity of Bubble Sort, Insertion Sort, and Selection Sort by running each algorithm on a list with a specified number of swaps, repeated `n` times. It measures the total execution time for each sort across all iterations and returns the aggregated results. The ...
def experimentTwo(swaps, n): totalBub = 0 totalIns = 0 totalSel = 0 for _ in range(n): L1 = create_near_sorted_list(1000, 1000, swaps) L2 = L1.copy() L3 = L1.copy() ## Bubble Sort start = timeit.default_timer() bubble_sort(L1) end = timeit.defaul...
def node(self, modid: str, default: _T = ...) -> ModNode | _T: if default is ...: return self.nodes[modid] return self.nodes.get(modid, default) def assert_acyclic_pending(self): try: cycle = nx.find_cycle(self.pending_view()) except nx.NetworkXNoCycle: ...
The code synchronizes a graph structure with configuration data by updating node states (locked/enabled), adding dependencies, removing invalid nodes, ensuring acyclicity, and propagating enabled states topologically. It enforces dependency constraints and config overrides, setting mod states based on ancestor status o...
def sync(self): # sync locks with config for modid, enabled in self.config.overrides.items(): node = self.node(modid) node |= {"locked": True, "enabled": enabled} # sync deps with config for modid, dependencies in self.config.extra_deps.items(): for d...
def count_nodes(self) -> tuple[int, int, int]: """-> (enabled, disabled, total)""" enabled = disabled = total = 0 for node in self.nodes.values(): total += 1 if node["locked"]: continue if node["enabled"]: enabled += 1 ...
The code disables approximately half of the enabled nodes in a topological order, skipping locked nodes, until the target number is reached, then prints the result and returns the instance.
def bisect(self): enabled, _, total = self.count_nodes() to_disable = enabled // 2 newly_disabled = 0 for modid in nx.topological_sort(self.G): if self.node(modid)["locked"]: continue enabled -= 1 if not self.disable(modid): ...
def pending_nodes(self) -> dict[str, ModNode]: return {modid: node for modid, node in self.pending_view().nodes.items()} def enable(self, modid: str): return self.set_enabled(modid, True) def disable(self, modid: str): return self.set_enabled(modid, False) def lock(self, modid: str): sel...
This function adjusts module states in a graph: enables disabled modules and their descendants, disables previously enabled modules, and locks them. It processes pending nodes, separating them into sets to enable or disable, then applies changes accordingly.
def set_enabled_good(self): """ disabled -> enabled enabled + parent of disabled -> enabled other -> disabled + bad """ to_enable = set[str]() to_disable = set[str]() for modid, node in self.pending_nodes().items(): if node["enabled"]: ...
def renderWidget(self, elem, padx = 1): if elem.type==SECTION: elem.widget.grid(row=self.counter, sticky=W) else: elem.widget.grid(row=self.counter, sticky=W, padx=padx) self.bindMouse(elem.widget) self.counter += 1 def onFrameConfigure(self, canvas): self.canvas.configure(scrollregion=self.canvas.b...
This method updates the graphical interface by rendering elements based on the current mode (Moodle simulator or category-sorted). It iterates through elements, rendering each and expanding/collapsing subfolders by showing/hiding their child elements. It binds frame configuration and mouse interactions to ensure dynami...
def updateGraphics(self): self.counter = 0 iterable = None if self.mode == MOODLESIMULATOR: iterable = self.moodleElements elif self.mode == CATEGORYSORTED: iterable = self.categorySortedElements for elem in iterable: self.renderWidget(elem) if (elem.type==SUBFOLDER): if elem.expand==True: ...
def isPolicyPage(self): return "/user/policy.php" in self.driver.current_url def isEnrolPage(self): return "/enrol/" in self.driver.current_url def clickLogin(self): elem = self.driver.find_element_by_class_name("login") self.clickLinkInsideInnerHTML(elem, 5) def clickShibbox(self): ...
The code's main task is to authenticate a user into a course page (courseURL) by either reusing valid cookies from a file or performing a login sequence. It checks for pre-saved cookies, validates their expiry, and reuses them if valid. If invalid, it navigates to the course URL, handles login prompts, retrieves creden...
def login(self, courseURL): flag = False if (isFile("driver.pkl")): try: with open("driver.pkl", "rb") as f: date, cookies = pickle.load(f) if (time.time()-date<COOKIE_EXPIRY_ESTIMATE): print("COOKIES are accepta...
def configureCanvasToBeScrollable(self): self.bindMouse(self.canvas) vsb = tk.Scrollbar(self.root, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=vsb.set) vsb.pack(side="right", fill="y") def addElement(self, title, link): var = IntVar() fg = "black" if "chimica" in li...
This code initializes a scrollable GUI window using Tkinter, loads course data from a text file, and displays each course's title and link. It creates a window, sets up a scrollable canvas, reads lines from "courseslist.txt", parses title-link pairs, adds them to the interface, and updates graphics.
def __init__(self): self.root = tk.Tk() self.root.geometry("800x600") self.canvas = tk.Canvas(self.root) self.configureCanvasToBeScrollable() self.frame = tk.Frame(self.canvas) self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4, 4), window=self.frame, anchor="nw") ...
def _choosePlayerCount(self) -> int: ''' Get player count from user ''' player_count = getInput('How many players (or [q]uit)?', '23456', 'q') return int(player_count) def _chooseCourse(self) -> 'Course': ''' Select a Course and return it as an object ''' ...
The main task of the code is to initialize a game board by gathering user inputs for player count and course selection, then adding players accordingly. The `setUp` method orchestrates this setup process, calling private methods to determine the number of players, select a course, and add players to the game, preparing...
def setUp(self) -> None: ''' Initializing function to set up the game board. ''' # Ask for input and set player count self.player_count = self._choosePlayerCount() # Ask for input and choose course self.course = self._chooseCourse() # Add players s...
def drawCourse(self) -> str: ''' Build a string representation of the board state (as a straight line) Use three lines (one for each potential lane) ''' first_line = second_line = third_line = '>' for i, space in enumerate(self.course.spaces): if space.type ...
The main task of the code is to have each player select a rider and play a card in two rounds. It returns a dictionary mapping riders to their movement values from played cards. During the first round, it tracks card selections as strings, while the second round displays prior plays before selecting new cards. Players ...
def _cardSelectionRounds(self) -> dict: ''' Have each player select one rider ande play one card. Return a dictionary with riders as keys and movement values as values. ''' # Initialize dict of riders and played cards riders_and_cards = {rider: None for rider in self.cour...
def _initialPlacement(self) -> None: ''' Gets input from players to place their riders behind the start line ''' valid_start_pos = [str(self.course.spaces.index(space)) for space in self.course.spaces if space.type in ['start', 'breakaway']] for player in self.course.players: ...
The main task of the code is to simulate a racing game loop, handling rider movement, card effects, slipstream mechanics, and exhaustion. It processes each turn by selecting cards, updating rider positions, applying game effects, checking for finished riders, and managing game progression until the race concludes. The ...
def gameLoop(self) -> list: ''' Main game loop. Returns the final positions after race is over ''' print(f'The race is about to begin! Course: {self.course.name}') # Initial placement of riders self._initialPlacement() # Initialize turn counter (is an ins...
def read_input(): n, m = map(int, input().split()) edges = [list(map(int, input().split())) for i in range(m)] return n, edges def initialize_data(n): clauses = [] positions = range(1, n + 1) adj = [[] for _ in range(n)] return clauses, positions, adj def create_adjacency_list(n, edges): ...
The code converts a graph problem into a Conjunctive Normal Form (CNF) formula for a SAT solver. It reads input parameters (n, edges), constructs an adjacency list, generates CNF clauses representing constraints, and outputs the clauses in DIMACS format. The main task is to translate graph-related constraints into logi...
def main(): # Read input n, edges = read_input() # Initialize data structures clauses, positions, adj = initialize_data(n) # Create an adjacency list adj = create_adjacency_list(n, edges) # Generate CNF clauses clauses = generate_cnf_clauses(n, positions, adj) num_variables = n * n ...
def edge_length(self, vertex1, vertex2): point1 = self.points[vertex1] point2 = self.points[vertex2] return self.calculate_distance(point1, point2) def calculate_tour_length(self): return sum(self.edge_length(v1, v2) for v1, v2 in zip(self.tour[:-1], self.tour[1:])) def __str__(self): ...
The code implements a greedy algorithm to solve the Traveling Salesman Problem (TSP). It starts at point 0, iteratively appends the nearest unvisited point to the current path, and returns to the starting point. The goal is to construct a tour with minimal total edge length by always choosing the closest available node...
def greedy(self): self.tour = [0] # Start with the first point remaining_points = set(self.tour[1:-1]) # Remaining points to visit while remaining_points: current_vertex = self.tour[-1] nearest_neighbor = min( remaining_points, key=lambd...
def PSNR(path_a, path_b): img1 = cv2.imread(path_a) img2 = cv2.imread(path_b) psnr = cv2.PSNR(img1, img2) return psnr def structural_sim(path_a, path_b): ''' Measure the structural similarity between two images @args: {str} path_a: the path to an image file {str} path_b: the path to an ima...
The code computes and prints five image similarity metrics—PSNR, structural similarity, pixel similarity, SIFT similarity, and Earth Mover's Distance—between two images specified by their file paths, providing a comprehensive comparison of their visual and structural characteristics.
def similarity(path_a, path_b): psnr = PSNR(path_a, path_b) structural_simi = structural_sim(path_a, path_b) pixel_simi = pixel_sim(path_a, path_b) sift_simi = sift_sim(path_a, path_b) emdi = earth_movers_distance(path_a, path_b) print(psnr) print(structural_simi) print(pixel_simi) p...
def _normalize(self, user_id: int, user_ratings: np.ndarray) -> np.ndarray: """ Normalizes user ratings by subtracting the mean of non-zero ratings. Args: user_id (int): User ID. user_ratings (np.ndarray): User ratings. Returns: np.ndarray: Normalize...
This function trains a matrix factorization model using gradient descent (BGD, SGD, or MBGD) to minimize RMSE on a utility matrix. It initializes latent factors, normalizes input data, iteratively updates parameters, tracks RMSE history, and employs early stopping if progress stalls for a specified patience period.
def train( self, M: np.ndarray, d: int, learning_rate: float, max_iterations: int, reg_factor: float = 0.01, patience: int = 50, GD_type: str = "BGD", batch_size: int = None, verbose: bool = True, ): """ Train the model....
def run_fit_linear(init_k1): '''Function performing the actual fit using the residual_linear function defined earlier ''' # init_k1 : Intial guess param_init = np.array([ init_k1 ]) print("**********************************************************") #print("Testing the residual function with d...
The function `run_all_fit` executes polynomial fitting tasks (linear to quartic) using predefined coefficients, computes residuals for each fit, and returns them as a NumPy array. It calls `run_fit_linear`, `run_fit_quadratic`, `run_fit_cubic`, and `run_fit_quartic` with specific coefficient values, stores their residu...
def run_all_fit(): ''' Runs the fitting from linear to quartic polynomial Returns : np array of residuals, with 4 elements ''' resd_1 = 0 resd_2 = 0 resd_3 = 0 resd_4 = 0 # modify the input coefs as required run_fit_linear( 1.04586) resd_1 = run_fit_linear( -1.04586) ...
def is_over(self) -> bool: return True if self.is_winner() or self.is_tie() else False def get_desired_position(self): self.player_selection = input("Please select a position to place your mark.\n") if self.player_selection not in [str(i) for i in range(1, 10)]: self.reset_player_se...
The code's main task is to handle a player's turn in a game. It checks if the game is not over, retrieves the desired position for the move, updates the game board state, and displays the updated board to reflect the current game progress.
def take_turn(self): if not self.is_over(): self.get_desired_position() self.update_board() self.display_board()
def generate_stan_input_collapsed(data_filename, design_matrix_filename, replicate_information_filename, batch_size=None, lambda_filename=None): # read the count data file data_pd = pd.read_table(data_filename, sep='\t', header=0) logging....
The code performs Bayesian analysis on CRISPR guide data using Stan, filtering guides by species, generating Stan input data, running MCMC inference with CmdStanPy, and saving posterior estimates and deviations. It handles input processing, model execution, and output storage for statistical analysis of guide efficienc...
def analyze(count_filename, design_matrix_filename, replicate_information_filename, sample_file_prefix, n_chains, n_samples, batch_size, n_batches, output_filename, logfilename, outfile_devs, species, target_file, spacers_file, lambda_filename=None): install_cmdstan() if s...
def login(self, username: str, password: str) -> bool: if username not in self.db['users']: return False user = self.db['users'][username] salt = user['salt'] blindPassword = self.blindPassword(password, salt, username) print(f"Login attempt with {blindPassword}") ...
The main task of the code is to change a user's password by verifying the old password, removing the old blinded hash from storage, generating a new salt, creating a new blinded hash with the new password and salt, updating the user's salt in the database, and adding the new blinded hash to the storage. It returns True...
def changePassword(self, username: str, oldPassword: str, newPassword: str) -> bool: if not self.login(username, oldPassword): return False self.passwords.remove(self.blindPassword(oldPassword, self.db['users'][username]['salt'], username)) salt = self.generateSalt() ...
def get_args(): parser = argparse.ArgumentParser(description="pre-process data.") parser.add_argument("-n", dest="name", type=str, default='') return parser.parse_args() def jasparDict(jaspar): with open(jaspar) as f: lines = f.readlines() jaspar_dict = {} for i, line in enumerate(lines...
The main task of the code is to preprocess genomic data by integrating motif, chromatin, and Hi-C features for two cell lines (GM12878 and K562). It extracts motif features from PPI and JASPAR data, encodes DNA sequences with one-hot encoding, loads chromatin data (e.g., DNase, histone marks), and processes Hi-C intera...
def main(): params = get_args() name = params.name root = osp.dirname(__file__) + '/GK' data_dir = osp.join(root, name) out_dir = osp.join(data_dir, 'data') if not osp.exists(out_dir): os.mkdir(out_dir) # motif ppi = osp.join(data_dir, 'PPI/string_interactions.tsv') jaspar = ...
def read_hic_header(hicfile): if not os.path.exists(hicfile): return None # probably a cool URI req = open(hicfile, 'rb') # print(req.read(3)) magic_string = struct.unpack('<3s', req.read(3))[0] # print(magic_string) req.read(1) if magic_string != b"HIC": return None # th...
This function extracts genomic features from HiC or cooler data matrices. It reads a BED file to define genomic coordinates, loads HiC/cooler data, retrieves contact matrices (balanced or not), and generates features using a specified resolution and number of features. The output is a feature matrix derived from contac...
def get_hic_feature(bed, path, resolution, number, balance=True): # more robust to check if a file is .hic hic_info = read_hic_header(path) if hic_info is None: hic = False else: hic = True # coords = parsebed(bed, res=resolution) if not hic: Lib = cooler.Cooler(pa...
def read_hic_header(hicfile): if not os.path.exists(hicfile): return None # probably a cool URI req = open(hicfile, 'rb') # print(req.read(3)) magic_string = struct.unpack('<3s', req.read(3))[0] # print(magic_string) req.read(1) if magic_string != b"HIC": return None # th...
This function loads Hi-C contact matrices from a file, handling both HiC and cooler formats. It skips chrY and chrM, applies balance normalization if enabled, and returns a dictionary mapping chromosomes to sparse matrices.
def load_hic(hic_file, resolution, balance=True): # more robust to check if a file is .hic hic_info = read_hic_header(hic_file) if hic_info is None: hic = False else: hic = True # if not hic: Lib = cooler.Cooler(hic_file) chromosomes = Lib.chromnames[:] else...
def q1a(): T = 1000 c = 1 eta_0_vec = np.logspace(-6, 3, num=10) accur_avgs = [] for eta_0 in eta_0_vec: accur_lst = [] for i in range(10): w = SGD_hinge(train_data, train_labels, c, eta_0, T) accur = calc_accuracy(validation_data, validation_labels, w) ...
The main task of the code is to sequentially execute multiple sub-functions (`q1a` to `q1d` and `q2a` to `q2c`) within the `main()` function. This structure likely organizes tasks or operations into modular components, where each function handles a specific subtask. The `main()` function acts as a controller, ensuring ...
def main(): q1a() q1b() q1c() q1d() q2a() q2b() q2c() return
def to_qt(qt): if not qt.startswith("qt"): return "qt" + qt return qt def to_arch(arch): return { "32": ARCH_32, "64": ARCH_64, ARCH_32: ARCH_32, ARCH_64: ARCH_64 }[arch] def to_compiler(qt, compiler, arch): if compiler ...
This function filters and processes compiler configurations from a list of tuples. It converts components, checks for optimal MSVC 2019 setups, validates Mingw URLs, and returns valid entries while logging unsupported cases.
def filter_optimal(flavours): res = [] for qt, compiler, arch in flavours: qt = to_qt(qt) arch = to_arch(arch) compiler = to_compiler(qt, compiler, arch) if compiler == MSVC_2019: if is_msvc_optimal(qt, compiler, arch): ...
def fig_from_json(fig): """Method that transforms a plot to json.""" if fig == None: return dash.no_update else: try: fig = from_json(fig) except: pass finally: return fig def return_var_plot(result, attr_name, attr_type, option=0): """...
The function updates or generates plots based on session data. It loads existing plots from a JSON file if available, otherwise generates new plots from data files. It uses file locking to safely update the plots JSON, converting figures to JSON format for storage. The function returns either pre-existing plots or newl...
def update_plots_general(sel, field, attr_name, attr_type, session_id): """Method that returns or generates a general plot.""" with open('output/plots_{}.json'.format(session_id), 'r') as f: plots = json.load(f) if plots[1][field][sel][0] is not None: return [fig_from_json(fig) for fig in pl...
def check_list(object): if isinstance(object, list): object = object[0] while isinstance(object, Pair): object = cdr(object) # if isinstance(object, Pair): # return check_list([cdr(object)]) if object == "nil": return "#t" else: return "#f" def list_len(pa...
The code applies a given function to each element of a list, constructing a new list using Scheme-style Pair objects and "nil" as the empty list. It validates the input is a list, recursively processes each element with `car` and `cdr`, and raises an error if the input is invalid.
def map_list(func, list): """ Given a list and function, return a new list that applied the function to each of the list's elements. """ if check_list(list) == "#f": raise Scheme.EvaluationError("argument passed in is not a list") if list_len(list) == 0: return "nil" else: ...
def check_list(object): if isinstance(object, list): object = object[0] while isinstance(object, Pair): object = cdr(object) # if isinstance(object, Pair): # return check_list([cdr(object)]) if object == "nil": return "#t" else: return "#f" def list_len(pa...
The code implements a `filter` function that processes a list, retaining only elements that satisfy a given predicate function. It checks if the input is a valid list, handles empty lists by returning "nil", and recursively constructs a new list by including elements that evaluate to true (`#t`) under the predicate. El...
def filter(func, list): """ Given a list and function, return a new list for which each element satisfies the parameter 'func'. """ if check_list(list) == "#f": raise Scheme.EvaluationError("argument passed in is not a list") if list_len(list) == 0: return "nil" else: ...
def check_list(object): if isinstance(object, list): object = object[0] while isinstance(object, Pair): object = cdr(object) # if isinstance(object, Pair): # return check_list([cdr(object)]) if object == "nil": return "#t" else: return "#f" def list_len(pa...
This function recursively applies a given function to an initial value and each element of a list, reducing the list to a single accumulated value. It first checks if the input is a valid list and handles empty lists by returning the initial value. Otherwise, it combines the initial value with the first list element us...
def reduce(func, list, init): """ Applied the function to the init value with every value in the list. Returns a value which applies every element of the list to the init. """ if check_list(list) == "#f": raise Scheme.EvaluationError("argument passed in is not a list") if list_len(list)...
def get_empty_row(board, column): for i in range(ROWS - 1, -1, -1): if board[i][column] == -1: return i return -1 def draw_circles(board): for row in range(ROWS): for col in range(COLS): if board[row][col] == -1: color = WHITE elif board[ro...
The main task of the code is to run a Connect Four game where a human player interacts with an AI (using AlphaBeta, MiniMax, or RL algorithms) or resets the game. It handles user input, updates the game state, renders the board, checks for wins/draws, and displays results. The AI makes moves based on the specified game...
def main(board, player, game_type): current_cell = [5, random.choice(list(range(7)))] if game_type == "RL": board[current_cell[0]][current_cell[1]] = 1 clock = pygame.time.Clock() run = True while run: clock.tick(FPS) for event in pygame.event.get(): if event...
def choose_action(board, current_cell): row = current_cell[0] col = current_cell[1] max_action = float('-inf') valid = get_valid_columns(board) actions = q_table[row][col][:] action_index = float('-inf') for index, action in enumerate(actions): if action > max_action and index in val...
The code simulates a two-player game where Player 1 uses an epsilon-greedy strategy based on a Q-table to select actions, while Player 2 employs the minimax algorithm. The game updates the Q-table with rewards after each move, tracking wins, draws, or ongoing play. The function returns the final reward, reflecting the ...
def play_game(epsilon): board = np.zeros((ROWS, COLS)) current_player = 1 game_over = False max_index = np.unravel_index(np.argmax(q_table[5]), q_table[5].shape) current_cell = [5, max_index[0]] board[current_cell[0]][current_cell[1]] = current_player current_player = 2 while not ga...
def play_rl(board, current_cell): col = choose_action(board, current_cell) row = get_empty_row(board, col) board[row][col] = 1 return [row, col] def play_minimax(board, max_depth): col = minimax(board,0, 2, max_depth)[0] row = get_empty_row(board, col) board[row][col] = 2 def check_win(board...
This function simulates a two-player game where Player 1 uses a reinforcement learning strategy (play_rl) and Player 2 uses the minimax algorithm (play_minimax). The game alternates turns starting from the given current_cell, checking for wins or draws after each move. It returns 1 if Player 1 wins, 2 if Player 2 wins,...
def play_against(current_cell): board = np.zeros((ROWS, COLS)) game_over = False current_player = 1 board[current_cell[0]][current_cell[1]] = current_player max_depth = 1 current_player = 2 while not game_over: if current_player == 1: res = play_rl(board, current_cel...
def get_mapped_fedex_data(self): if self.data.get('errors') is not None: return ERROR_MESSAGE self.data = self.data['output']['completeTrackResults'][0] if self.data['trackResults'][0].get('error') is not None: return { 'trackingNumber': self.data['tracki...
The main task of the code is to create a deep copy of the base data and map it according to the carrier's specific requirements by delegating to carrier-specific methods like get_mapped_fedex_data(), ensuring data is transformed appropriately for different shipping providers.
def get_mapped_data(self): self.mapped_data = copy.deepcopy(self.base) if self.carrier is Carrier.fedex: return self.get_mapped_fedex_data() elif self.carrier is Carrier.usps: return self.get_mapped_usps_data() elif self.carrier is Carrier.dhl: return ...
def parse_args(args=None): d = "Read list of files and count how many missions a Tag has" parser = argparse.ArgumentParser(description=d) parser.add_argument( "files", type=argparse.FileType("r"), nargs="+", help="list of files to read", ) parser.add_argument( ...
The main task of the code is to generate a localized markdown table summarizing mission counts from specified files. It processes command-line arguments for localization, handles optional flags like --ante-bellum, collects search directories, generates localized strings, formats mission data, and outputs a sorted table...
def main(args=None) -> int: args = parse_args(args) if args.ante_bellum: # We were passed --ante-bellum, enable ANTE_BELLUM specific # code handling global ANTE_BELLUM ANTE_BELLUM = True if not args.localise: if args.extra_dir is not None: print("-d|--ex...
def load_model(model, pretrained_path, load_to_cpu): # print('Loading pretrained model from {}'.format(pretrained_path)) if load_to_cpu: pretrained_dict = torch.load( pretrained_path, map_location=lambda storage, loc: storage) else: device = torch.cuda.current_device() pr...
This function detects anime faces in an input image using the FaceBoxes SSD model. It loads a pre-trained model, processes the image tensor, performs forward inference to get bounding box predictions, applies confidence thresholding, non-max suppression (NMS), and returns detected face coordinates. The implementation u...
def ssd_anime_face_detect_from_cv2_Image(imgOrig, model_path): cfg = { 'name': 'FaceBoxes', #'min_dim': 1024, #'feature_maps': [[32, 32], [16, 16], [8, 8]], # 'aspect_ratios': [[1], [1], [1]], 'min_sizes': [[32, 64, 128], [256], [512]], 'steps': [32, 64, 128], ...
def pvp(joc, interfata, stare_curenta, q, end): """Joc player vs player Args: joc (Joc): jocul curent interfata (Interfata): interfata pe care e desenat jocul stare_curenta (Stare): starea initiala q ([queue]): coada prin care se primesc informatii de la threadul mouse_control ...
The main task of the code is to run a game loop that initializes a game interface, processes player interactions via a thread, handles different game modes (PVP/PVE), executes game logic, and displays the final result. It creates game states, manages player turns, and terminates the game with a winner announcement.
def main(): interfata = Interfata() while True: joc = Joc(Table()) Joc.seteaza_interfata(interfata) interfata.meniu(joc) interfata.stare_initiala() joc.JMAX = 'CAINE' if joc.JMIN == 'JAGUAR' else 'JAGUAR' stare_curenta = Stare(joc, j_curent='JAGUAR', adancime=j...
def decisionTreeClassifier(x, y): model = DecisionTreeClassifier() standardSet(model, x, y) def kNeighborsClassifier(x, y): scores = [] mses = [] for k in wholeValues: model = KNeighborsClassifier(n_neighbors=k) accuracy, mse = runSet(model, x, y) scores.append(accuracy) ...
The code loads a dataset of songs, processes it into features (x) and labels (y), trains multiple machine learning classifiers (e.g., Decision Tree, k-NN, SVM, Logistic Regression), evaluates their performance, and generates comparison graphs to visualize results.
def main(): with open('./data/11k_songs_tso_dataset.json') as f: data = json.load(f) # max_genres = 2 # x, y = parse_data_multi_output_full(data, max_genres) x, y = parse_data_single_output_full(data, True) # bernoulliNB(x, y) decisionTreeClassifier(x, y) # extraTreeClassifier(x, y...
def _parse_options(options: to_pdf_options) -> to_pdf_options: """Parse options""" default_options: to_pdf_options = { 'author': '', 'output': '000_outputFile.pdf', 'page_size': PageSize.image, 'image_size': ImageSize.image, 'page_orientation': 'P', } for key, val...
The main task of the code is to convert a list of images into a PDF document by dynamically adjusting page sizes for each image, setting metadata like the author, and saving the output to a specified file. It processes each image, adds it as a page, tracks progress, and generates the final PDF with the given options.
def create_pdf(image_list: List[str], options: to_pdf_options) -> None: """Convert images to pdf""" options = _parse_options(options) pdf = FPDF('P', 'mm', 'A4') pdf.set_author(options['author']) for index, image_name in enumerate(image_list, start=1): width, height = _get_page_size(image_na...
def create_nodes( nodes_config: list[dict[str, Any]] ) -> tuple[dict[str, Task], list[str]]: nodes = {} initiator_nodes = [] for node_config in nodes_config: task_id, task = create_node(node_config) if task_id in nodes: raise Exception("Task id: %s already exists!" % task_id)...
The function processes a configuration to construct a network of nodes and links, identifies initiator nodes, and returns the initiator task, list of initiator nodes, and all nodes. It creates nodes from the config, establishes links between them, determines initiators based on link connections, and organizes the node ...
def config_injest(config: Any) -> tuple[Task, list[Task], list[Task]]: nodes, initiator_node_ids = create_nodes(config["nodes"]) links = create_links(nodes, config["links"]) initiator = link_initatior(nodes, initiator_node_ids, links) set_children(nodes, links) initiator_nodes = [nodes[node_id] for...
def encode(txt: str): ba = bitarray() ba.frombytes(txt.encode('utf-8')) return ba def ham_encode(data: bitarray): data_length = len(data) num_parity_bits = _num_parity_bits_needed(data_length) encoded_length = data_length + num_parity_bits + 1 encoded = bitarray(encoded_length) for par...
The function encodes text into Hamming-coded bytes, applying error injection based on the `mode` parameter. It divides the bitstream into chunks, encodes each with Hamming code, and introduces single or multiple bit errors in specific segments depending on the mode. It tracks error counts (`cnt0err`, `cnt1err`, `cntMul...
def text_hamming_bytes(text, mode=0, len_word=70): bits = encode(text) hamming = [] cnt1err, cnt0err, cntMultiErr = 0, 0, 0 for i in range(int(len(bits) / len_word) + 1): if i == int(len(bits) / len_word): hamming.append(ham_encode(bits[i * len_word:])) else: hamm...
def _extract_data(encoded: bitarray): data = bitarray() for i in range(3, len(encoded)): if not _is_power_of_two(i): data.append(encoded[i]) return data def _calculate_parity(data: bitarray, parity: int): retval = 0 # 0 is the XOR identity if parity == 0: # special case - comp...
The code decodes a Hamming-encoded bitarray by calculating parity bits, detecting errors, and correcting them. It determines the number of parity bits, checks overall parity, and verifies each parity bit's validity. If discrepancies are found, it identifies the error index and adjusts the encoded data. The function als...
def ham_decode(encoded: bitarray): encoded_length = len(encoded) num_parity_bits = floor(log2( encoded_length - 1)) + 1 index_of_error = 0 decoded = _extract_data(encoded) overall_expected = _calculate_parity(encoded[1:], 0) overall_actual = encoded[0] overall_correct = overall_exp...
def load_message(): with open('message.txt', 'r', encoding='utf-8') as file: data = file.read().replace('\n', '') return data def text_hamming_bytes(text, mode=0, len_word=70): bits = encode(text) hamming = [] cnt1err, cnt0err, cntMultiErr = 0, 0, 0 for i in range(int(len(bits) / len_wor...
The code launches a client that connects to a server, sends encoded data using Hamming codes (with error counts), receives responses, and processes results by extracting error statistics and decoded text from byte data.
def launch_client(mode=0): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) msg = load_message() sock.connect(('localhost', 9090)) cnt0err, cnt1err, cntMultiErr, code = text_hamming_bytes(msg, mode=mode) print(f"0 mistakes: {cnt0err}") print(f"1 mistakes: {cnt1err}") print(f"Multi m...
def byte2bit(b: bytes): ba = bitarray() ba.frombytes(b) return ba def ham_decode(encoded: bitarray): encoded_length = len(encoded) num_parity_bits = floor(log2( encoded_length - 1)) + 1 index_of_error = 0 decoded = _extract_data(encoded) overall_expected = _calculate_parity(enc...
This function decodes a byte stream using Hamming code by splitting bits into chunks of specified length (78 default), decoding each chunk to detect/correct errors, tallying total errors, correct/incorrect decodes, and returning these metrics alongside the decoded byte data.
def bytes_hamming_bytes(bytes, len_word=78): bits = byte2bit(bytes) hamming = [] tot1Err, totCorrDecode, totIncorrDecode = 0, 0, 0 for i in range(int(len(bits) / len_word) + 1): if i == int(len(bits) / len_word): cnt1Err, cntCorrectDecode, cntIncorrectDecode, arr = ham_decode(bits[i ...
def _add_single_league_button(self) -> None: single_league_button = QPushButton('Single League') single_league_button.clicked.connect(self._window.switch_to_single_league_menu) self._layout.addWidget(single_league_button) def _add_double_league_button(self) -> None: double_league_button ...
The code initializes a GUI component by setting up a vertical layout, connecting to a window and database, and adding UI elements like buttons for league interactions and a table for player statistics. It prepares the interface for managing and displaying league data and player information through interactive component...
def __init__(self, window, database: LeagueDatabase): super().__init__() self._window = window self._database = database self._layout = QVBoxLayout() self._add_single_league_button() self._add_double_league_button() self._add_player_data_interaction() self...
def as_boolean(val, default=False): truthy = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) falsy = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, False)) if val in truthy: return True if val in falsy: return False return default def oxtrust_config(): # keeping redunde...
The code initializes LDAP settings by storing configuration values in Consul, disables oxTrust config generation, executes oxTrust configuration, renders LDIF files, imports them into LDAP, applies a custom schema, and performs cleanup. The main task is to configure and populate an LDAP directory with predefined and cu...
def run(): if as_boolean(GLUU_LDAP_INIT): consul.kv.set('ldap_init_host', GLUU_LDAP_INIT_HOST) consul.kv.set('ldap_init_port', GLUU_LDAP_INIT_PORT) consul.kv.set("oxTrustConfigGeneration", False) oxtrust_config() logger.info('start rendering of ldif files') render_ld...
def getReducedModel(self): # print('----------------------------' ) # logging.info(x) x = self.XList[: len(self.XList) - 1] ReducedModel = LinearRegression(self.y, *x) return ReducedModel def SSE(self): E = self.Residuals() SSE = np.dot(E, np.transpose(E)) ...
The code calculates the F-statistic for comparing two models by computing the difference in sum of squared errors (SSE) between a reduced model and the full model, divided by the mean squared error (MSE). This value is used in hypothesis testing to determine if the additional variables in the full model significantly i...
def Ftest(self): return (self.getReducedModel().SSE() - self.SSE())/ self.MSE()
def InitialiseByFilePath(self, FilePath): df = pd.read_csv(FilePath) data = df.values self.y = data[:, -1] self.X = np.array(data[:, :-1]) self.n = df.shape[0] col = [list(data[:, i]) for i in range(df.shape[1] - 1)] # for i in range(df.shape[1]): # pr...
This code initializes a statistical model by either loading data from a file or direct input, fits the model to compute parameters (BVector), calculates key statistics (SSE, SST, residuals), determines degrees of freedom, generates a correlation matrix, and extracts predictor variable information. It prepares the model...
def __init__(self, *args): self.BaseXs = None self.logs = "" if len(args) == 1 and isinstance(args[0], str): self.InitialiseByFilePath(args[0]) else: self.InitialiseByDirectPythonTypes(args[0], args[1:]) # print("Xlist : ") # logging.criti...
def first_code_ln(code_list, re_pattern=None, lang='python'): if re_pattern is None: re_pattern = _dir_pre(lang) "get first line number where code occurs, where `code_list` is a list of code" return first(i for i,o in enumerate(code_list) if o.strip() != '' and not re.match(re_pattern, o)) def _norm_quarto(...
This function extracts leading comment directives from a code cell's source, processes them by removing `#|` markers (if `remove=True`), and returns them as a dictionary. It identifies directives using language-specific patterns, preserves Quarto directives if `remove=True`, and modifies the cell's source by removing p...
def extract_directives(cell, remove=True, lang='python'): "Take leading comment directives from lines of code in `ss`, remove `#|`, and split" if cell.source: ss = cell.source.splitlines(True) first_code = first_code_ln(ss, lang=lang) if not ss or first_code==0: return {} pre = s...
def pypi(ver_bump=True): "Create and upload python package to pypi." _dist() system(f'twine upload --repository pypi {_dir()}/dist/*') if ver_bump: _c(nbprocess_bump_version) def conda(ver_bump=True): "Create and upload a conda package." system(f'fastrelease_conda_package --mambabuild --upload_...
The main task of the code is to release both conda and pypi packages without version bumping, by calling pypi() and conda() with ver_bump=False, and executing an additional process via _c(nbprocess_bump_version).
def release(): "Release both conda and pypi packages." pypi(ver_bump=False) conda(ver_bump=False) _c(nbprocess_bump_version)
def _quarto_installed(): return bool(shutil.which('quarto')) def install(): "Install quarto and the current library." install_quarto() if (get_config().path('lib_path')/'__init__.py').exists(): system(f'pip install -e "{_dir()}[dev]"') def _c(f, *args, **kwargs): return f.__wrapped__(*args, **kwargs...
The main task of the code is to generate documentation by checking if Quarto is installed, installing it if necessary, and then processing a notebook using the `_c` function with `nbprocess_quarto` as input.
def docs(): "Generate the docs." if not _quarto_installed(): install() _c(nbprocess_quarto)
def _quarto_installed(): return bool(shutil.which('quarto')) def install(): "Install quarto and the current library." install_quarto() if (get_config().path('lib_path')/'__init__.py').exists(): system(f'pip install -e "{_dir()}[dev]"') def _c(f, *args, **kwargs): return f.__wrapped__(*args, **kwargs...
The code's main task is to start a local documentation webserver. It checks if Quarto is installed, installs it if missing, then launches the server with sidebar support and enables preview mode for real-time rendering of documentation content.
def preview(): "Start a local docs webserver." if not _quarto_installed(): install() _c(nbprocess_sidebar) _c(nbprocess_quarto, preview=True)
def opt_set(var, newval): "newval if newval else var" return newval if newval else var def extract_directives(cell, remove=True, lang='python'): "Take leading comment directives from lines of code in `ss`, remove `#|`, and split" if cell.source: ss = cell.source.splitlines(True) first_co...
This code processes a notebook by applying preprocessing steps, extracting directives from cells, processing each cell individually, applying postprocessing steps, and filtering out cells with missing source content. It updates cell indices, modifies notebook metadata through processors, and ensures only valid cells wi...
def process(self): "Process all cells with `process_cell`" for proc in self.preprocs: self.nb = opt_set(self.nb, proc(self.nb)) for i,cell in enumerate(self.nb.cells): cell.idx_ = i for cell in self.nb.cells: cell.directives_ = extract_directives(cell, remove=self.rm_dire...
def readVenuesFromFile(file): with open(file) as f: jsonVenues = json.load(f) print(jsonVenues) for venue in jsonVenues['venues']: print(venue) addVenueToFirebase(venue['name'],venue['location']) return def parseEvents(icsFile): start = date(2020,11,2) end = date(202...
The main task of the code is to parse events from a test ICS file and add specific test events to a Firebase database, with conditional execution limited by false checks for other operations like reading venues or adding venues to Firebase.
def main(): if(1==0): readVenuesFromFile('venues.json') if(1==1): parseEvents('TestICS.ics') if(1 == 0): addVenueToFirebase("Turtle Jack's Yonge", "11740 Yonge St, Richmond Hill, ON L4E 0K4") if(1 == 0): # addEventToVenue("Patria", "478 King St W, Toronto, ON M5V 1L7",eve...
def getVenues(numReqQueries): totalVenues = [] numQueries = numReqQueries for i in range(0,ceil(numReqQueries/50),1): if(numQueries > 50): venues = yelp_api.search_query(categories= 'bars,pubs', latitude=43.648360,longitude=-79.388940, radius=2000, limit=50, offset=(50*i)) if(len(totalVenues) != 0): tot...
The main task of the code is to initialize a list of venues by retrieving them, processing each venue, validating it, and appending valid venues to a collection. It then uploads the collected venues to a specified Firebase path. The function returns the populated venues collection after processing and uploading.
def initializeVenuesInFirebase(fb_path): Venues = VenuesClass() venues = getVenues(120) for venue in venues: Venue = initializeVenue(venue) if (Venue != None): print("venue added: ", Venue.name) Venues.appendVenue(Venue) else: print("venue not added!") uploadVenuesToFirebase(Venues.getAllVenues(), fb...
def initializeVenuesInFirebase(fb_path): Venues = VenuesClass() venues = getVenues(120) for venue in venues: Venue = initializeVenue(venue) if (Venue != None): print("venue added: ", Venue.name) Venues.appendVenue(Venue) else: print("venue not added!") uploadVenuesToFirebase(Venues.getAllVenues(), fb...
The main task of the code is to initialize and manage Firebase data by creating venues and users, updating venue information using user data, and uploading/synchronizing these updates to both private and public Firebase paths. It conditionally initializes new venues/users, syncs existing data, and ensures venue updates...
def main(): print("Starting firebase manager...") if(1 == 1): #run this to initialize venues and post them to FB **************************************************************** Venues = initializeVenuesInFirebase(privateVenueFirebasePath) # Venues.printAllVenues() # ***************************************...
def get_args(): parser = argparse.ArgumentParser() # Data parser.add_argument('--src-fname', type=str, required=True) parser.add_argument('--tgt-fname', type=str, required=True) # Model parser.add_argument('--language', type=str, required=True, choices=constants.LANGUAGES) return parser.par...
The main task of the code is to evaluate word prediction models on different cleaned datasets. It reads prediction data, removes words with punctuation or non-alphabet characters progressively, evaluates model performance at each cleaning stage, and saves results to a file. The process compares predictor effectiveness ...
def main(): args = get_args() df = read_predictions(args.src_fname) # Get predictions' correlations results = evaluate_predictors(df, clean_method='none') # Remove words that contain punctuation df = df[~df.word.str.contains('[%s]' % string.punctuation)] results += evaluate_predictors(df, ...
def genSqfliteCreateTableQuery(self): return '"CREATE TABLE IF NOT EXISTS ' + self.theName + ' ("' + \ ''.join(['\n' + self.genSqfliteCreateMember(i) for i in range(self.elementsCount())]) + \ '\n")"' def genSQLInsertItems(self): '''generate insert SQL query from theDF and theNam...
This code generates a Dart class for SQLite database operations, creating a `DBQuery` class with static SQL queries and constants. It dynamically inserts values like the database file name, table name, and generated SQL statements (e.g., create table, insert, delete) into a template string, returning the formatted Dart...
def toSqfliteDBQueryClass(self): rs = """import '%s.dart'; class DBQuery { static const DATA_FILE_NAME = "%s.db"; static const TABLE_NAME = "%s"; static const CREATE_TABLE = %s; static const GET_MAX_ID = "SELECT MAX(id)+1 as id FROM " + TABLE_NAME; static const INSERT_NEW = %s; static const D...
def getWmsCapabilitiesUrl(dataset): return getWmsUrl(dataset)+'?request=GetCapabilities&service=WMS&version=1.3.0' def getOpenDapUrl(dataset): return settings.THREDDS['host']+'dodsC/'+dataset
The main task of the code is to retrieve WMS capabilities from a dataset by fetching a URL, handling potential redirects recursively, and parsing the XML response. It uses delays between requests, checks for redirects via the 'location' header, and retries if necessary, ultimately returning the parsed XML content as a ...
def getWmsCapabilities(dataset): url=getWmsCapabilitiesUrl(dataset) # print(url) sleep(0.2) session.get(getOpenDapUrl(dataset)) sleep(0.1) res = session.get(url) if res.status_code != 200: if res.headers.get('location'): r = session.get(res.headers.get('location')) ...
def parse_message(self, received_msg): parts = received_msg.split(' ') prefix=None user=None channel=None irc_command=None irc_args=None text=None text_command=None text_args=None if parts[0].startswith(':'): prefix = parts[0...
The main task of the code is to process incoming IRC messages. It checks if the message is non-empty, parses it, and prints the content. For 'PING' commands, it responds with 'PONG'. For 'PRIVMSG' commands, it checks if the message matches predefined template commands and triggers corresponding handling logic using `ha...
def handle_message(self, received_msg): if len(received_msg) == 0: return message = self.parse_message(received_msg) print(f'> {message}') if message.irc_command == 'PING': self.send_command('PONG :tmi.twitch.tv') if message.irc_command == 'PRIVMSG': ...
def send_command(self, command): if 'PASS' not in command: print(f'< {command}') self.irc.send((command + '\r\n').encode()) def send_privmsg(self, channel, msg): self.send_command(f'PRIVMSG #{channel} :{msg}') def loop_for_messages(self): while True: received_msgs...
The main task of the code is to connect to an IRC server, authenticate using an OAuth token, join specified channels, send a greeting message to each channel, and initiate a loop to process incoming messages.
def connect(self): self.irc = socket.socket() self.irc.connect((self.irc_server, self.irc_port)) self.send_command(f'PASS {self.oauth_token}') self.send_command(f'NICK {self.username}') for channel in self.channels: self.send_command(f'JOIN #{channel}') se...
def updateText(obj, formatFunc, txt): newText = formatFunc(txt) obj.text = newText def setEnabled(button, isEnabled): button.disabled = not isEnabled def checkForExistingDatabase(self, database_directory): if not os.path.exists(database_directory): os.mkdir(database_directory) return False else: return...
This code handles post-load initialization by updating UI elements, disabling the start button, and scheduling a database check. It verifies if an existing "pulsar_database" exists, then triggers either setup_existingDatabase or setup_generateDatabase based on the result, managing progress and text updates during the p...
def _on_load_complete(self, dt): # kivy objects progressBar = self.ids.progress loading_text = self.ids.loadingText startButton = self.ids.startButton # lambda functions generateLoadingText = self.generateLoadingText generateButtonText = self.generateButtonText # initialize updateText(startButton,...
def is_terminal_state(game_state, uuid): """ Given a game state and a player's uuid, returns True if the player is done for that round. Else, returns False. """ game_finished = game_state["street"] == Const.Street.FINISHED return game_finished def expand(self): """ Generates...
The main task of the code is to simulate a game round by randomly selecting actions for the agent and opponents until a terminal state is reached. It expands the current node, runs the emulator to the round's end, updates the node's playout count, calculates the resulting state's value, and propagates this value back t...
def simulate_playout(self): """ Runs simulated playouts of the round by selecting random actions (for both the agent and its opponents) until a terminal state is reached (the simulated round is over). """ if not is_terminal_state(self.game_state, self.uuid): next_node...
def player_death(): print("That wasn't very effective...") print("He stares at you with an amused expression before casting a spell on you with his wand-") print("You are now helplessly in pain - as if you were brutally stung by millions of angry wasps.") print("You slowly and painfully begi...
The code simulates a game scenario where a player faces a randomly assigned weapon (rock, rope, crowbar, or magical wand) and must choose between fighting or using persuasion tactics. The main task involves generating a weapon, handling player choices, awarding coins, and triggering different outcomes like death or suc...
def murder(): #comp picks random number - (1-30 = rock, 30-60 = rope, 60-90 = crowbar, 90-100 = magical wand) print("Your bravery is commended by the Gods! You have earned one gold coin.") global total_coins total_coins += 1 print(f"Your total number of coins is {total_coins}.") ...
def item_found(): print(f"Sighing with relief, {user} brings the item outside. Minus is waiting expectantly for them.") print("They hear a familiar voice yell their name and turn to see their grandmother, unharmed..for now.") print("'Not so fast,' Minus says, and a spherical green forcefield sur...
The main task of the code is to handle user decisions in a text-based game: prompting the player to pick up an item, verifying if it matches a target object (obj), and managing hallway/room navigation if the player declines to pick up the item. It enforces input validation for hallway/room choices and progresses the ga...
def pick_up(item): pick_up = input("If you believe this is the required item, will you pick it up?") if pick_up == "yes": #print(item, obj) # checking if item == obj: print("You have found the item, congratulations.") item_found() else: print("You hav...
def predict_action(self, img): b, g, r = cv2.split(img) # For BGR image img = np.dstack((r, g, b)) img_array = tf.expand_dims(img, 0) # Create a batch predictions = self.human_model.predict(img_array) score = predictions[0] # score = score[0] i...
The code processes an action in a multi-agent environment, validating and applying moves for both computer and human agents. It updates the game state, awards rewards for cleaning dirt, penalizes invalid actions, checks for game completion (no remaining dirt), and returns the new state, rewards, termination status, and...
def step(self, action): # Apply action # 0: "Stay" # 1: "Left" # 2: "Up" # 3: "Right" # 4: "Down" computer_reward = 0 human_reward = 0 self.step_num += 1 # Assert that it is a valid action assert self.action_space.contain...
def new_keyboard(self): return KeyboardView(self) def initLayers(self): self.layers = {} self.add_layer_names(["id","effort","pressed","pressedPerc"]) def initKb(self): for id, row in enumerate(self.analyzer.keyboard.getAllRows()): self.kbView.addRow(position=id,keys=row) ...
This code initializes a GUI application for a keyboard analysis tool, setting up a window with a label displaying keyboard layout information, configuring the window properties, creating UI components like checkboxes, a keyboard view, and an options panel. It links an "Analyze" button to a method for processing keyboar...
def __init__(self,analyzer) -> None: super().__init__() self.analyzer = analyzer ttk.Label(self,text=f"{self.analyzer.keyboard.layoutName} on {self.analyzer.keyboard.name}").pack() self.title("OpKeyMize") self.geometry('1800x1000+50+50') self.iconbitmap("assets/ok_logo.ic...
def find_calendar_tag(soup): for tag in soup.find_all(True): if tag.name == "div" and tag.has_attr('class'): if 'calendar-list-view' in tag['class']: return tag return None def remove_empty(tags): not_empty = list() for tag in tags: if tag.name is not None: ...
The main task of the code is to parse HTML content, extract calendar-related event data using BeautifulSoup, validate the presence of a calendar tag, filter out empty elements, and return structured event information. It raises an error if the calendar tag is missing, ensuring only valid event data is processed and ret...
def loadeventsfromhtml(html): soup = BeautifulSoup(html, 'html.parser') calendar = find_calendar_tag(soup) if calendar is None: raise NotImplementedError soup_events = remove_empty(calendar.children) events = parse_events(soup_events) return events
def __symbol_finder(self, pattern, start, ascii): for i in range(start, len(pattern)): curr = self.__char_to_index(pattern[i]) if curr == ascii: return i return def __char_to_index(self, char): return ord(char) def search(self, pattern, replace, flag1, fla...
The code generates all possible strings by replacing the substring between brackets in 'pattern' with each character in the ASCII range defined by the bracketed characters. It then performs a search for each generated string and returns a list of all search results.
def range_search(self, pattern, replace, bracket_idx, flag1, flag2): end_bracket_idx = self.__symbol_finder(pattern, bracket_idx, 93) first_part = pattern[:bracket_idx] second_part = pattern[end_bracket_idx+1:] words = [] matches = [] for i in range(self.__char_to_index(p...
def __symbol_finder(self, pattern, start, ascii): for i in range(start, len(pattern)): curr = self.__char_to_index(pattern[i]) if curr == ascii: return i return def range_search(self, pattern, replace, bracket_idx, flag1, flag2): end_bracket_idx = self.__s...
The function `or_search` processes a pattern by splitting it into two parts, identifies special symbols (range, set, wildcard, etc.), and executes corresponding search methods (e.g., `range_search`, `set_search`) for each segment. It aggregates results from all applicable searches, defaulting to a general search if no ...
def or_search(self, pattern, replace, flag1, flag2): bar_idx = self.__symbol_finder(pattern, 0, 124) first_pattern = pattern[:bar_idx-1] second_pattern = pattern[bar_idx+2:] Identify = Identifier.Identifier(first_pattern) Range = Identify.symbol_finder(first_pattern, 0, 45) ...
def encrypt(plaintext1, plaintext2): global ternary_digit keyed_alphabet = key_alphabet() # print(keyed_alphabet) radix_mapping = radix_map(keyed_alphabet) # print(radix_mapping) letter_mapping = letter_map(keyed_alphabet, radix_mapping) # print(letter_mapping) first_cypher = first_encry...
The code implements a cipher system for encrypting/decrypting two texts using customizable symbols and a ternary digit. It parses command-line arguments, validates inputs, processes text (filtering, padding), and applies encryption/decryption functions. In encryption mode, it combines two plaintexts into a cipher; in d...
def main(): global symbols global ternary_digit global key i_file = None o_file = None # Parse parameters ((correct_args, err_msg), settings) = parse_arguments(sys.argv) # print("-------------------- * --------------------") # print("Parameters:") # for key, value in settings.it...
def _substitute(self, str): """ Substitute words in the string, according to the specified reflections, e.g. "I'm" -> "you are" :type str: str :param str: The string to be mapped :rtype: str """ return self._regex.sub(lambda mo: self._ref...
This function replaces placeholders in a response string with dynamic data. It processes '%'-based wildcards by substituting matched groups, inserts a username from _data_arr, and replaces SQL-related placeholders with parsed statements and query results if the input is a question. Errors during SQL parsing are caught ...
def _wildcards(self, response, match, sent = ''): pos = response.find('%') while pos >= 0: num = int(response[pos+1:pos+2]) response = response[:pos] + \ self._substitute(match.group(num)) + \ response[pos+2:] pos = response.find('%') ...
def _load_data(self, filepath): data = pd.read_csv(filepath) return data def _train_public_list(self): train_list = list(self.train_label['alert_key']) public_list = list(self.predicted_alert_key['alert_key']) return train_list, public_list def _process(self, co...
The code initializes a class by loading multiple datasets from specified file paths using configuration parameters. It processes these datasets to generate training and public datasets through filtering and merging operations, preparing them for further analysis or model training.
def __init__(self, configs): self.configs = configs self.train_label = self._load_data(self.configs.filepath['train_label']) self.public_alert_date = self._load_data(self.configs.filepath['public_alert_date']) self.predicted_alert_key = self._load_data(self.configs.filepath['pr...
def check_keydown_events(event, ai_settings, screen, ship, bullets): if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings, screen,ship, bullets) elif event.key =...
This function handles user input events in a game, processing keyboard presses/releases and mouse clicks. It exits the game on quit events, triggers actions via keydown/up events, and checks mouse clicks to activate play/high score buttons, delegating specific tasks to helper functions like check_keydown_events and che...
def check_events(ai_settings, screen, stats, sb, play_button, hs_button, ship, aliens, bullets): """Respond to keypresses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(...
def check_fleet_edges(ai_settings, aliens): for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets): if stats.ships_left > 0: #Decrement ships left ...
The function updates alien movement, checks for collisions between aliens and the ship, and detects if aliens reach the screen's bottom, triggering appropriate game responses like handling ship collisions and alien bottom-bound events.
def update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets): check_fleet_edges(ai_settings, aliens) aliens.update() #Look for alien-ship collisions if pygame.sprite.spritecollideany(ship, aliens): ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets) #Look for aliens...
def char_at_pos(grid: list[str], x: int, y: int) -> str: if not is_valid_pos(grid, x, y): return "" return grid[y][x] def find_length_of_num(grid: list[str], x: int, y: int) -> int: curr_x = x + 1 l = 1 while char_at_pos(grid, curr_x, y).isdigit(): l += 1 curr_x += 1 ...
This function calculates the sum of all numbers in a grid that are adjacent to non-digit, non-dot characters. It iterates through each cell, identifies numbers, checks their neighboring positions for symbols, and accumulates the number's value if a symbol is found.
def part_1(grid: list[str]) -> int: total = 0 for y in range(len(grid)): curr_x = 0 while curr_x < len(grid[0]): if not char_at_pos(grid, curr_x, y).isdigit(): curr_x += 1 else: l = find_length_of_num(grid, curr_x, y) for p...
def char_at_pos(grid: list[str], x: int, y: int) -> str: if not is_valid_pos(grid, x, y): return "" return grid[y][x] def adjacent_positions(x: int, y: int) -> set: positions = set() for x_diff in range(-1, 2): for y_diff in range(-1, 2): if x_diff == 0 and y_diff == 0: ...
The code calculates the sum of products of pairs of distinct numbers adjacent to each asterisk (*) in a grid. For each '*', it identifies neighboring digits, groups them into unique numbers, and if exactly two numbers are found, multiplies them and adds the result to the total.
def part_2(grid: list[str]): total = 0 for x in range(len(grid[0])): for y in range(len(grid)): if char_at_pos(grid, x, y) == "*": adjacent = adjacent_positions(x, y) dig_adj = list(filter(lambda t: char_at_pos(grid, t[0], t[1]).isdigit(), adjacent)) ...
def parse_input(inp_file: str): inp = open(inp_file) grid = [] for line in inp.readlines(): grid.append(line.replace("\n", "")) return grid def part_1(grid: list[str]) -> int: total = 0 for y in range(len(grid)): curr_x = 0 while curr_x < len(grid[0]): if no...
The code reads a grid from "input.txt", computes and prints results for two parts (part_1 and part_2) of a problem involving the grid, likely solving a puzzle or computational task in two distinct steps.
def main(): grid = parse_input("input.txt") print(part_1(grid)) print(part_2(grid))
def create_blue_portal(self): if not self.blueActive: self.blueRect.x = self.rect.x self.blueRect.y = self.rect.y self.blue_portal_row_index = self.row_index self.blue_portal_column_index = self.column_index self.blueActive = True self.crea...
This code updates a game entity's position on a grid-based map, managing movement, map representation changes, portal creation, and collision checks. It adjusts the entity's coordinates, updates the map array to track movement, resets counters, triggers portal creation based on flags, and stops movement when travel dis...
def update(self): if self.moving: self.mapCounter += 1 if self.direction == "right" or self.direction == "left": self.rect.x += self.speed if self.mapCounter == 5: if self.settings.resetPacEaten is True: self.set...
def update(self): if self.moving: self.mapCounter += 1 if self.direction == "right" or self.direction == "left": self.rect.x += self.speed if self.mapCounter == 5: if self.settings.resetPacEaten is True: self.set...
The code checks if a movement in a specified direction is possible by detecting collisions with map elements (pygame.Rect). If a collision is detected, it calculates the distance to the nearest obstacle and sets an update flag for movement. If no collision is found, it triggers the corresponding movement method (e.g., ...
def check_move(self, direction): while self.mapCounter != 0: self.update() self.blit() pygame.display.flip() if direction == "left": if isinstance(self.map[self.row_index][self.column_index - 1], pygame.Rect) or \ isinstance(self.map[se...
def _singularize_verb_forms(self, sent: 'spacy.Doc') -> str: ''' Singularize verb forms. ''' verb_auxiliaries = self._find_all_verb_candidates(sent, ['they']) verb_replacements = self._find_singular_forms(verb_auxiliaries) new_toks = [] for tok in sent: ...
The code's main task is to rewrite a gender-fair sentence by replacing gendered forms with generic male and female versions using linguistic rules. It checks if the normalized sentence contains gendered terms, processes verbs, and generates male/female variants. The function returns the original and transformed sentenc...
def reverse(self, sent: str, norm_sent: str) -> str: ''' Rewrite a gender-fair sentence to use generic male and female forms using rules. ''' if not self.contains_gendered_form(norm_sent): return sent, norm_sent, norm_sent, norm_sent tagged = self.spacy_tagger(norm_s...
def load_planets(self, filename='Planet_load.txt'): print(f'Loading planets from {filename}') file = open('C:\\Users\\jtims\\PycharmProjects\\Gravity\\' + filename) input_data = file.read().split('\n') file.close() while input_data[-1] == '': del input_data[-1] ...
The code simulates planetary motion over time, updating positions and velocities iteratively. It checks for collisions at each step, tracking progress via print statements if enabled. The simulation runs until max_time or max_runs is reached, outputting collision details or completion status.
def run(self, record_history=True): if not self.planets_loaded: self.load_planets() print(f'The input parameters are: Max time = {self.max_time}\tMax runs = {self.max_runs}\tPrecision from ' + f'{self.precision_min} to {self.precision_max}') collision = False co...
def read_command_output(command, prompt_string, time_gap=4, objTab=objTab): objTab.Screen.Send(command + "\r") objTab.Screen.WaitForString(command, time_gap) command_output = objTab.Screen.ReadString(prompt_string) command_output = command_output.split("\r") return command_output def clear_known_hos...
The code attempts to connect to a network device by first pinging its IP address to check availability. If the device is reachable, it iterates through predefined SSH user credentials, clears known hosts, and tries to establish a connection. If a connection mismatch occurs, it interrupts and retries. If successful, it ...
def connect_to_host(device_ip,device_prompt_string,objTab): global returned_value ping_command = "ping " + str(device_ip) ping_command_output = read_command_output(ping_command, prompt_string_of_main_screen, time_gap=wait_for_seconds,objTab=objTab) ping_command_output = " ".join(ping_command_output) ...
def get_devices_from_csv(): the_devices = list() last_name_ip_address = "" if os.path.exists(result_file_name): with open(result_file_name,"r") as csv_result_file: reader = csv.reader(csv_result_file,delimiter="\n") last_device = [row for row in reader][-1] last_n...
The code's main task is to connect to network devices via SSH, retrieve health status and storage information (CPU/memory usage, cfcard sizes), handle parsing errors, differentiate between master/slave components, and export collected data to a CSV file, logging connection issues or errors when they occur.
def Main(): global objTab device_list = get_devices_from_csv() data = list() for device in device_list: device_name,device_ip, version, district = device.split(",") device_prompt_string = ">" try: device_district = district.split("/")[2].strip() exc...
def distributed_stmt(store, stmt): var = stmt.children[0].value if len(stmt.children) == 2: shape = () dist_stmt = stmt.children[1] else: shape = parse_shape(store, stmt.children[1]) dist_stmt = stmt.children[2] dist = dist_stmt.children[0].value args = [process_numexpr(store, arg) for arg in ...
The code parses a program using a Lark grammar, processes each statement (distributed, dataassign, assign) by updating a Store object, and returns the modified store. It initializes a parser, parses the input, iterates through parsed statements, applies corresponding handling functions, and ultimately returns the popul...
def run(program): parser = Lark.open('./grammar.lark', start='simpleppl') p = parser.parse(program) store = Store(pm.Model()) for stmt in p.children: if stmt.data == 'distributed': distributed_stmt(store, stmt) if stmt.data == 'dataassign': data_assign_stmt(store, stmt) if stmt.data == '...
def parse_input(contents: str): lines = contents.splitlines() lsd = (line.split(' ') for line in lines) ls2 = [(template, tuple([int(n) for n in ns.split(',')])) for (template, ns) in lsd] return ls2 def generate(template, ns): if len(ns) == 1: n = ns[0] b = ('.'*u + '#'*n + (len(template) - n - ...
The main task of the code is to calculate the total number of characters generated by applying the `generate` function to all expanded (template, ns) pairs derived from the input. It parses the input, expands it into multiple template-namespace pairs, generates strings for each pair, and sums their lengths to return th...
def get_answer_b(contents): inp = parse_input(contents) return sum(len(generate(template, ns)) for (template, ns) in expand(inp))
def _get_fill_number(self) -> int: result = re.match(r"^(\d)*", self._path.stem) if not result: raise ValueError(f"Could not extract fill number from path '{self._path}'.") return int(result.group()) def _get_scan_times(self) -> Tuple[datetime, datetime]: result = re.search(...
This code initializes an object to manage data processing tasks, setting attributes like file paths, detector configurations, energy parameters, and correction methods. It prepares to collect results into DataFrames, handling optional parameters and ensuring valid configurations for detectors and corrections.
def __init__(self, path: Union[Path, str], fits: List[str], detectors: Optional[List[str]] = None, corrections: Optional[List[str]] = None, name: str = "", energy: float = 0.0, energy_unit: str = "GeV", ...
def numberK2(X_train, X_test, y_train, y_test, testx, testy): xtn = X_train xts = X_test tx = testx numberK(X_train, X_test, y_train, y_test, testx, testy) X_train["1"], X_test["1"], testx["1"] = K7(xtn), K7(xts), K7(tx) numberK(X_train, X_test, y_train, y_test, testx, testy) X_train["1"], X...
The function applies various transformation functions (K1-K10) to the '2' column of training and test datasets, sequentially updating the data and invoking numberK2 for evaluation. It iterates through K1 to K10, modifying the datasets each time before re-running numberK2, likely to test different feature transformation...
def numberK3(X_train, y_train, X_test, y_test, testx, testy): xtn = X_train xts = X_test tx = testx numberK2(X_train, X_test, y_train, y_test, testx, testy) X_train["2"], X_test["2"], testx["2"] = K1(xtn), K1(xts), K1(tx) numberK2(X_train, X_test, y_train, y_test, testx, testy) X_train["2"],...
def __format_important_stats(self, fixture): stats = flatten(fixture["stats"], sep="_") return stats def __format_goals(fixture, important): home_id = fixture["home_id"] away_id = fixture["away_id"] goals = fixture["goals_json"] if goals: df = pd.DataFrame(g...
The main task of the code is to process a sports fixture data by extracting and formatting key statistics (goals, corners, cards) and important match details. It aggregates these into a structured dictionary, adds the fixture ID, and prepares the result for database updates by wrapping it in a "$set" key. The output is...
def format(self, fixture): data = dict() important = self.__format_important_stats(fixture) goals_data = self.__format_goals(fixture, important) corners_data = self.__format_corners(fixture, important) cards_data = self.__format_cards(fixture, important) result = { ...
def __condition_for_probability(self, rule): table_name = "probability" column_name = rule["code"] field = f"{table_name}.{column_name}" return [self.gen_between_condition(field, rule["values"])], [field] def __condition_for_odds(self, rule): table_name = "pre_odds" colum...
This function processes pre-match rules from a given strategy. It categorizes each rule by type (probability, odds, aggregate stats), generates corresponding conditions and fields using helper methods, and aggregates them into lists. The output consists of combined conditions and fields for further processing or analys...
def __query_for_pre_match_rules(self, strategy): pre_match_conditions = [] pre_match_fields = [] for rule in strategy["strategy_prematch_rules"]: if rule["category"] == "probability": conditions, fields = self.__condition_for_probability(rule) elif rule["c...
def __query_for_pre_match_rules(self, strategy): pre_match_conditions = [] pre_match_fields = [] for rule in strategy["strategy_prematch_rules"]: if rule["category"] == "probability": conditions, fields = self.__condition_for_probability(rule) elif rule["c...
The code constructs a MongoDB aggregation query to filter matches based on strategy rules. It combines pre-match conditions and fields, adding in-play rules, timers, and status filters if the strategy type is "in-play". The final query uses `$match` with aggregated conditions to select relevant matches, excluding previ...
def format(self, strategy): #picks = list(picks_table.find({"strategy_id": strategy["id"]}, {"fixture_id": 1})) pre_match_conditions, pre_match_fields = self.__query_for_pre_match_rules( strategy) fields = pre_match_fields league_conditions = [self.__query_for_leagues(strate...
def find_sums(n): sums = [] all_sums = [] find_sums_helper(n, n, sums, all_sums) return all_sums def createsublist(wordlist,filtertext, size = 0): filtertext = filtertext.upper() sublist = [] for word in wordlist: if contains(word,filtertext): if (size > 0) and (len(word...
The function generates valid word combinations from a list that match the length of a given text, applying constraints on minimum word size, maximum word count, and combination validity. It filters words based on length, reduces invalid combinations early, and returns possible matches using recursive checks. The approa...
def wordcombofinder(wordlist,filtertext,minlength = 3,minmax = 3, maxwords = 4): # this is very inefficient way of doing this, so I have 2 parameters to control the vast amounts of combinations # If the total wordlength is less than like 10 you should be fine for runtime, but it explodes exponentially # aft...
def sequentialTesting(populationArray, stopRule, p, batchSize, Constants, seqRepeat=1, threshold=1, sequential=True): """ A function gives the test results to a subject array and the total number of test-kit consumption and the individual testing number given the subject array, the stop rule, the batch ...
The main task of the code is to process multiple iterations of sequential testing results, compute evaluation metrics (accuracy, sensitivity, specificity, PPV, NPV) and test consumption values (total, individual, batch), then compile these into a structured pandas DataFrame for analysis. It iterates through input array...
def resultsToDataFrame(populationArrayIterations, **kwargs): """ a helper function provides convenient results for a sequential testing, returns a dataframe with accuracy, sensitivity, specificity, PPV, NPV, totalTestConsumption, individualTestConsumption, and batchTestConsumption Input: popul...
def seq_test(subject_array,stop_rule,p, batch_size, sp, sens_i, alpha, beta, repeat = 1, prob_threshold = 1, seq = True, batch_limit = 32): """ A function gives the test results to a subject array and the total number of test-kit consumption and the individual testing number given the subject array, t...
The function `test_result` evaluates a test method on input data (single or multiple datasets) by computing performance metrics (accuracy, sensitivity, specificity, PPV, NPV) and consumption statistics (test, individual, batch). It returns a structured DataFrame containing these metrics for each dataset. If input is a ...
def test_result(data, seq_test, **kwargs): """ a helper function provides convenient results for a given test method with its **kwargs Input: data (array or list of arrays) seq_test (test_method object): could be seq_test, matrix_test and other test_method objects Output: result...