dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def solve_kkt_system_block_elimination(A, c, x): grad = gradient(c, x) A_diag_inv = A @ np.diag(np.square(x)) nu = - cho_solve(cho_factor(A_diag_inv @ A.T), A_diag_inv @ grad) delta_x_nt = np.diag(np.square(x)) @ (-grad - A.T @ nu) return (delta_x_nt, nu, grad) def solve_kkt_system_naive(A, c, x): ...
The main task of the code is to verify the equivalence of two KKT system solving methods via an assertion, execute a centering step for linear programming using an interior-point method, and visualize the Newton decrement's convergence behavior on a logarithmic scale. This tests algorithm correctness and demonstrates o...
def main_centering(): assert np.allclose( np.concatenate(solve_kkt_system_block_elimination(A, c, x0)), np.concatenate(solve_kkt_system_naive(A, c, x0)) ) x, nu, progress = centering_LP(A, c, x0, alpha, beta) plt.plot(progress['lambda'], label='newton decrement') ...
def gradient_descent(x0, f, dom, gradient, tol, alpha, beta): x = [x0] while np.linalg.norm(gradient(x[-1])) > tol: delta = - gradient(x[-1]) x.append(backtracking_line_search(f, dom, gradient, x[-1], delta, alpha, beta)) return x def get_stats(x_opt, f): p_opt = list(map(f, x_opt)) ...
The code compares gradient descent and Newton's method for optimization by running both algorithms with initial guess x0, collecting iteration statistics (steps and error), and plotting their step sizes and errors over iterations on log scales. The goal is to visualize and analyze convergence behavior of both methods f...
def run_gradient_newton(): x0 = np.zeros(n) tol = 1e-5 alpha = 0.3 beta = 0.8 x_opt = gradient_descent(x0, f, dom, gradient, tol, alpha, beta) iterations_steps, steps, iterations_error, error = get_stats(x_opt, f) top_left, bottom_left = plt.subplot(2, 2, 1), plt.subplot(2, 2, 2)...
def phase_1(A, b, t_barrier, mu, alpha, beta): m, n = A.shape A_1 = np.column_stack((A, - A @ np.ones(n))) b_1 = b - A @ np.ones(n) c_1 = np.concatenate([np.zeros(n), [1]]) x0 = pinv(A) @ b t0 = 2 - min(x0) z0 = np.concatenate([x0 + np.ones(n) * (t0-1), [t0]]) z_opt, progress = feas...
The main task of the code is to solve a linear program using phase 1 and phase 2 methods, check feasibility, compare results with a convex solver (cvx), and verify solution accuracy via an assertion. It initializes with phase 1 to find an initial feasible point, then applies a barrier method for optimization, finally v...
def main_phase_1_phase_2(): feasible, x0 = phase_1(A, b, t0, mu, alpha, beta) print('Is feasible?', feasible) cvx_result, cvx_opt = cvx_solve_LP(A, b, c) cvx_feasible = cvx_result < np.inf print('cvx is feasible?', cvx_feasible) x_opt, history = feasible_start_barrier(A, c, t0, x0, mu, alpha, b...
def matches_timestamp_format(timestamp_str: str): """ Checks if a timestamp is within accepted formats. """ for format_str in formats_to_try: try: datetime.strptime(timestamp_str, format_str) return True except ValueError: continue return False def...
The main task of the code is to parse Fitbit data files (CSV/JSON) by extracting metric names, dates, and extensions from filenames using regex. It processes timestamp fields, converts them to UTC/local time, aggregates data by metric, sorts entries chronologically, and batches them monthly for further processing via `...
def parse_fitbit_data(filepaths: list): filepaths = [path for path in filepaths if path.endswith((".csv", ".json"))] # Regex pattern to match filenames and capture the metric name, dates (including those in parentheses), and extension. pattern = r'^(.*?)(?: - )?(?:(\d{4}-\d{2}(?:-\d{2})?(?:-\d{4}-\d{2}-\d...
def create_directory_if_not_exist(path): pathlib.Path(path).mkdir(parents=True, exist_ok=True) def check_if_match_completed(match_data): state = match_data.get("state") if state == "mom": return True else: return False def init_match_performance_data_wtests(match_id, team1_id, team2_id, ...
This function converts structured match data from a dictionary into a CSV file, extracting details like match IDs, team information, scores, venues, dates, captains, and series IDs. It filters completed matches, processes squad data to identify captains, and writes the results to a specified CSV file with predefined he...
def init_match_to_csv(data_dict, file_name): path_name = "api_data/" create_directory_if_not_exist(path_name) match_writer = csv.writer(open(path_name + file_name + ".csv", "w", newline="")) # Write CSV Header, If you dont need that, remove this line match_writer.writerow(["match_id", "match_type"...
def init_match_to_csv(data_dict, file_name): path_name = "api_data/" create_directory_if_not_exist(path_name) match_writer = csv.writer(open(path_name + file_name + ".csv", "w", newline="")) # Write CSV Header, If you dont need that, remove this line match_writer.writerow(["match_id", "match_type"...
The main task of the code is to initialize and convert JSON data into multiple CSV files, including matches, players, teams, player-team relationships, umpires, umpire-match assignments, and series, by calling specific functions for each data entity.
def init_all_match_data(json_data): init_match_to_csv(dict(json_data), "match") init_players_to_csv(dict(json_data), "players") init_teams_to_csv(dict(json_data), "teams") init_players_plays_for_teams_to_csv(dict(json_data), "player_plays_for_teams") init_umpires_to_csv(dict(json_data), "umpires") ...
def run_turbomole(command,outfile=None): if outfile == None: outfile=command.split()[0]+'.out' proc_cmd=['nohup']+command.split() if not command.startswith('jobex'): if outfile == None: outfile = command+'.out' proc_cmd+=['>','outfile'] with open(outfile,'w') as tm_out: tm_...
The code performs structure optimization using Turbomole's jobex, handling convergence and SCF errors by adjusting cycles, running single-point calculations, and checking optimization status. It constructs command-line options from settings, iterates until convergence, and exits on failures.
def jobex(settings): options='' if settings['use ri']: options+=' -ri' if settings['tddft']: options+=' -ex %i'%(settings['opt exc state']) options+=' -c %i'%(settings['opt cyc']) num_cycles,done=0,False while not done: run_turbomole('jobex%s'%(options)) os.system('eiger > ...
def kmeans(X, k, max_iters): centroids = X[np.random.choice(range(len(X)), k, replace=False)] # centroids = [np.random.uniform(size=len(X[0])) for i in range(k)] converged = False current_iter = 0 while (not converged) and (current_iter < max_iters): cluster_list = [[] for i in range(len(...
The code performs RBF kernel-based classification using k-means clustering. It computes centroids, generates RBF features, trains weights via pseudo-inverse, predicts test labels, and calculates accuracy by comparing predicted vs actual test labels.
def fit(self): self.centroids, self.std_list = kmeans(self.X, self.k, 1000) if not self.std_from_clusters: dMax = np.max([get_distance(c1, c2) for c1 in self.centroids for c2 in self.centroids]) self.std_list = np.repeat(dMax / np.sqrt(2 * self.k), self.k) RBF_X = self...
def testFolder(net, ctx, folder_path): for i, image_file in enumerate(os.listdir(folder_path)): image_path = os.path.join(folder_path, image_file) testImage(net, ctx, image_path) def testImage(net, ctx, image_path): image = cv.imread(image_path) _, image_name = helper.getFilename(image_path...
The code loads a pre-trained SSD object detection model (either MobileNet or ResNet50 variant) and configures it for inference on specified input data. It sets up a GPU/CPU context, loads model parameters, and executes testing based on command-line arguments: processing a dataset folder, an image, or a video. The main ...
def main(args): BASE_MODEL = 'ssd_512_mobilenet1.0_custom' TRAINED_MODEL = 'ssd_512_mobilenet1.0_gym.params' BASE_MODEL = 'ssd_512_resnet50_v1_custom' TRAINED_MODEL = 'ssd_512_resnet50_v1_cow.params' net = gcv.model_zoo.get_model(BASE_MODEL, classes=cfg.CLASSES, ...
def is_train_and_test_file_exist(self)->bool: try: train_data_test = False test_data_test = False train_data_test = os.path.exists(self.data_ingestion_artifact.train_data_path) test_data_test = os.path.exists(self.data_ingestion_artifact.test_data_path) ...
The main task of the code is to perform data validation by checking the existence of train/test files, detecting data drift, and generating a DataValidationArtifact containing schema/report paths, validation status, and a success message. It logs the artifact and returns it, raising an exception on errors.
def initiate_data_validation(self)->DataValidationArtifact : try: self.is_train_and_test_file_exist() self.is_data_drift_found() data_validation_artifact = DataValidationArtifact( schema_file_path=self.data_validation_config.schema_file_path, r...
def image_to_text(path): read_image = open(path, "rb") read_response = computervision_client.read_in_stream(read_image, raw=True) read_operation_location = read_response.headers["Operation-Location"] operation_id = read_operation_location.split("/")[-1] while True: read_result = computervis...
The code extracts text from an image using `image_to_text`, then calculates and returns an array of four features: spelling accuracy, grammatical accuracy, percentage of corrections, and phonetic accuracy of the extracted text. The function processes an image path to generate a feature vector for text quality analysis.
def get_feature_array(path: str): feature_array = [] extracted_text = image_to_text(path) feature_array.append(spelling_accuracy(extracted_text)) feature_array.append(gramatical_accuracy(extracted_text)) feature_array.append(percentage_of_corrections(extracted_text)) feature_array.append(percent...
def check_account(account): if(account.isdigit()): if(len(account) == 16): mycursor.execute("select account from user") for i in mycursor: if i == (account,): return (True,) return (Fa...
The main task of the code is to delete a user account from a database after verifying its existence and balance. If the account balance is zero, it directly deletes the account. If there's a non-zero balance, it transfers the amount (as cash) using a `trans` function before deletion. The function returns confirmation m...
def close_account( account): if(check_account(account)): if(check_balance(account) == '0'): mycursor.execute("delete from user where account = %s", (account,)) mydb.commit() return "Account deleted Successfully" k = check_balance(account) trans(k, 3, accou...
def _parse_arguments(args=None): """ Parse arguments directly passed from CLI """ parser = argparse.ArgumentParser( description='Pure python ssh tunnel utils\n' 'Version {0}'.format(__version__), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argu...
The main task of the code is to process command-line arguments for establishing an SSH tunnel, handling mandatory parameters like `ssh_address` and `-R` (remote bind addresses), along with optional settings for authentication, logging, compression, and tunnel configuration. It parses inputs, removes `None` values, sets...
def _cli_main(args=None): """ Pass input arguments to open_tunnel Mandatory: ssh_address, -R (remote bind address list) Optional: -U (username) we may gather it from SSH_CONFIG_FILE or current username -p (server_port), defaults to 22 -P (password) -L (local_bind_ad...
def MRV(self, idSpeaker): orderedValues = PriorityQueue() Xi = self.FindSpeaker(idSpeaker) for aux in Xi.Neighbors: neighbor = self.FindSpeaker(aux) orderedValues.put([len(neighbor.SpeakTime),neighbor.Name]) resp = orderedValues.get() pr...
The main task of the code is to implement a backtracking algorithm with constraint satisfaction heuristics. It selects variables using the Minimum Remaining Values (MRV) heuristic, assigns values via the Least Constrained Value (LCV) strategy, and applies forward checking to propagate constraints. The function aims to ...
def Backtrack(self, sp, day, hour, w, csp): # if assignment.state == 'Complete': # return assignment var = self.MRV() self.LeastConstrainedValue(var) self.ForwardChecking(var,day,hour)
def findPossibleCharsInPlate(imgGrayscale, imgThresh): ''' This fucntion extracts all the contours from the number plate image and groups the relevant contours into a list and returns the list @input: Grayscale and thresholded image of the numberplate @output: List of relevant contours ''' l...
The function `detectCharsInPlates` processes a list of potential license plates to extract and recognize characters. It preprocesses images (grayscale, thresholding), detects possible characters via contours, groups them into matching clusters, removes overlapping characters, and identifies the longest valid character ...
def detectCharsInPlates(listOfPossiblePlates,save_intermediate,output_folder,showSteps): ''' This function processes the list of number plates and returns a lsit of processed number plates with their text. @input: List of images of number plates @output:A list of number plates with all the informati...
def reducible(self, word): return self.reduce(word) != word def _reduce(self, word): word0 = word for _ in range(self.max_rewrites + 1): old = word for left, right in self.rules: word = word.replace(left, right) if word == old: ...
This code initializes a rewriting system by validating input alphabet and rules, ensuring convergence through critical pair checks, and precomputing data structures for efficient reduction and classification of words. It enforces rule normalization, checks for irreducibility of single letters, and builds caches and suc...
def __init__(self, alphabet, rules, max_rewrites=1000): self.alphabet = ''.join(alphabet) self.rules = rules self.max_rewrites = max_rewrites # Assert we're provided correct arguments if not isinstance(rules, list): raise ValueError("Rules must be a list of pairs of ...
def draw_boxplot_for_scene_type(data, attribute): # check attribute is valid if not hasattr(data[0], attribute): raise AttributeError("Attribute " + attribute + " does not exist in data") # check is attribute is numeric if not np.issubdtype(type(getattr(data[0], attribute)), np.number): ...
This function generates visualizations and tables analyzing a specified attribute across different scene types. It creates boxplots, mean/std tables, bar charts for scene-type statistics, bar charts highlighting top actors by attribute mean, and a time series plot of the attribute over time.
def draw_all_graphs_and_tables(attribute): # Load data data = load_full_data() draw_boxplot_for_scene_type(data, attribute) table_of_mean_and_std_by_scene_type(data, attribute) bar_chart_of_mean_and_std_by_scene_type(data, attribute) bar_chart_of_most_extreme_actors_by_mean(data, attribute, top=...
def load_anchor_annotations(anchor_paths): labels, labels_list = load_labels(anchor_paths) for annotation in labels.values(): annotation['key'] = path_to_key(annotation['key']) good_anchors, other_anchors = filter_labels( labels, labels_list, must_have=['good'], mus...
This code initializes an object by processing anchor and PMK annotations. It separates anchors into valid and invalid categories, filters PMK annotations based on bad anchors, and organizes valid/invalid PMK keys by anchor keys using dictionaries. The goal is to structure annotation data for later validation or process...
def __init__(self, anchor_annotations, pmk_annotations): # Split anchors into good and bad labels. anchors_good, anchors_bad, anchor_label_list = load_anchor_annotations( anchor_annotations) # Collect final anchor labels. self.anchor_valid_annotations = anchors_good ...
def _disease(self, evidence_item): """Get an evidence item's disease data. :param Evidence evidence_item: A CIViC Evidence record :return: A dictionary containing disease data """ disease = self._get_dict(evidence_item['disease']) if not disease: return None ...
This function extracts and structures data from a CIViC Evidence record into a dictionary, including fields like ID, name, description, associated drugs, and metadata. It conditionally adds assertion-related attributes if specified. The output organizes evidence item details for downstream processing or API responses.
def _evidence_item(self, evidence_item, is_evidence=False, is_assertion=False): """Get evidence item data. :param Evidence evidence_item: A CIViC Evidence record :param bool is_evidence: Whether or not the evidence item is being harvested ...
def _get_all_evidence(self): """Return all evidence item records. :return: All civicpy evidence item records """ return civicpy.get_all_evidence() def _evidence_item(self, evidence_item, is_evidence=False, is_assertion=False): """Get evidence item data. ...
The main task of the code is to harvest all CIViC evidence item records by retrieving them via `_get_all_evidence()`, converting each into structured records using `_evidence_item()`, and returning them as a list. The function processes each evidence item, ensures they are marked as evidence, and aggregates them into a...
def _harvest_evidence(self): """Harvest all CIViC evidence item records. :return: A list of all CIViC evidence item records. """ evidence_items = self._get_all_evidence() evidence = list() for ev in evidence_items: ev_record = \ self._evidenc...
def _variant(self, variant): """Get basic variant data. :param Variant variant: A CIViC Variant record :return: A dictionary containing variant data """ return { 'id': variant['id'], 'entrez_name': variant['entrez_name'], 'entrez_id': variant[...
The main task of the code is to extract and structure data from a CIViC variant object into a dictionary, including nested attributes like evidence items, variant groups, assertions, and clinical annotations, while returning a consolidated dictionary of variant data for further processing or storage.
def _harvest_variant(self, variant): """Harvest an individual CIViC variant record. :param Gene variant: A CIViC variant object :return: A dictionary containing CIViC variant data """ v = self._variant(variant) # Add more attributes to variant data v_extra = { ...
def _assertion(self, assertion): """Get assertion data. :param Assertion assertion: A CIViC Assertion record :return: A dictionary containing assertion data """ disease = self._get_dict(assertion['disease']) return { 'id': assertion['id'], 'type':...
The main task of the code is to extract and compile key attributes from a CIViC assertion object into a structured dictionary. It processes the input assertion, enriches it with additional metadata like NCCN guidelines, AMP levels, ACMG codes, evidence items, and phenotypes, then returns the aggregated data as a dictio...
def _harvest_assertion(self, assertion): """Harvest an individual CIViC assertion record. :param Gene assertion: A CIViC variant object :return: A dictionary containing CIViC assertion data """ a = self._assertion(assertion) # Add more attributes to assertion data ...
def _get_all_variants(self): """Return all variant records. :return: All civicpy variant records """ return civicpy.get_all_variants() def _harvest_variant(self, variant): """Harvest an individual CIViC variant record. :param Gene variant: A CIViC variant object ...
The main task of the code is to retrieve and process all CIViC variant records by iterating through each variant, converting it to a dictionary, harvesting its data via `_harvest_variant`, and compiling results into a list for return.
def _harvest_variants(self): """Harvest all CIViC variant records. :return: A list of all CIViC variant records. """ variants = self._get_all_variants() variants_list = list() for variant in variants: v = self._harvest_variant(self._get_dict(variant)) ...
def _get_all_assertions(self): """Return all assertion records. :return: All civicpy assertion records """ return civicpy.get_all_assertions() def _harvest_assertion(self, assertion): """Harvest an individual CIViC assertion record. :param Gene assertion: A CIViC varian...
This function retrieves all CIViC assertion records by iterating through assertions obtained via _get_all_assertions(), processes each assertion using _harvest_assertion() after converting it to a dictionary, and compiles them into a list for return. Its main task is to aggregate and transform CIViC assertion data into...
def _harvest_assertions(self): """Harvest all CIViC assertion records. :return: A list of all CIViC assertion records. """ assertions = self._get_all_assertions() assertions_list = list() for assertion in assertions: a = self._harvest_assertion(self._get_dic...
def _harvest_evidence(self): """Harvest all CIViC evidence item records. :return: A list of all CIViC evidence item records. """ evidence_items = self._get_all_evidence() evidence = list() for ev in evidence_items: ev_record = \ self._evidenc...
The code retrieves and stores evidence, genes, variants, and assertions from CIViC into composite and individual JSON files. It uses private methods to gather data, compiles them into a JSON structure, and saves them with the provided filename. The function returns `True` on success or `False` on failure, logging error...
def harvest(self, filename: Optional[str] = None): """Retrieve and store evidence, gene, variant, and assertion records from CIViC in composite and individual JSON files. :param Optional[str] filename: File name for composite json :return: `True` if operation was successful, `False` oth...
def getPGridFromID(id, rot): pGrid = rotVars[id][rot] return pGrid def executeHardDrop(pGrid, board, x): global lockQueued executeSoftDrop(pGrid, board, x) lockQueued = True def executeSoftDrop(pGrid, board, x): # Find lowest valid position y = piecePos[1] # Starts from the current piece po...
This function simulates a Tetris-like game loop by processing piece movements, handling hard/soft drops, locking pieces into the grid, and managing hold/queue mechanics. It updates the game state by applying deltas, executing drop actions, locking pieces, and swapping held pieces with the current piece or dequeuing new...
def runSim(): global nextDelta, hardDropQueued, softDropQueued, lockQueued, grid, hold, currentPiece, pieceRot, piecePos, holdQueued, colors pGrid = getPGridFromID(currentPiece, pieceRot) if hardDropQueued: executeHardDrop(pGrid, grid, piecePos[0]) hardDropQueued = False if so...
def hardDrop(): if source == SCREEN_CAPTURE: ping('Space') elif source == INTERNAL_SIM: tetrisSim.hardDrop() tetrisSim.runSim() wait(hardDropLatency) return def holdPiece(): if source == SCREEN_CAPTURE: ping('c') elif source == INTERNAL_SIM: ...
The code automates Tetris gameplay by analyzing the game grid and piece queue to determine optimal moves. It uses screen capture or simulation to detect the board state, calculates ridges and holes, and generates a moveset for positioning and rotating pieces. The script handles holding pieces, sliding, and dropping to ...
def calculate(): if keyboard.is_pressed('esc'): return global started if keyboard.is_pressed('`'): started = True # Press A to go forwards global stepPermit if lockstep: if keyboard.is_pressed('a'): stepPermit = True if not stepPermit: ...
def initSim(): global currentPiece, queue, piecePos currentPiece = drawPiece() piecePos = genPieceSpawn(currentPiece) regenerateQueue() # Flip pieces and initiallize piece rotations for i in range(len(baseRot)): bp = baseRot[i] bp = np.flip(bp, axis=1) baseRot[i] = bp ...
This code initializes a Tetris game by setting up input handling, rendering the game grid, queue, and hold piece using Pygame. It initializes core components, starts a keyboard listener, and enters a loop to update the screen, draw game elements, and manage game state with optional callbacks for initialization and loop...
def init(cbI=None, cbL=None): print("Initializing!") tetrisCore.init() initSim() if cbI is not None: cbI() # Hook input listener = keyboard.Listener(on_press=onPress) listener.start() pygame.init() screen = pygame.display.set_mode((600, 800)) running = True w...
def reset_game(screen, bottom_pipes, top_pipes, pipe_collision_list, pipe_collision_list_180): screen.fill((255,255,255)) bottom_pipes.clear() top_pipes.clear() pipe_collision_list.clear() pipe_collision_list_180.clear() pygame.time.wait(2000) def create_bottom_pipe(bottom_pipes, screen_width, m...
The code implements a Flappy Bird-style game called "Flappy Turd" using Pygame. It handles player input for jumping, pipe collision detection, score tracking, and game reset. The game features scrolling backgrounds, animated pipes, and sound effects for collisions and scoring. The main loop manages game states, renderi...
def main(): screen_width = 800 screen_height = 450 min_distance = 400 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Flappy Turd") CLOCK = pygame.time.Clock() pipe_collision_list = [] pipe_collision_list_180 = [] fart_sound = pygame.mixer...
def filter_corpus(): """ Gets the filters from the listboxes and filters the corpus :return: a Corpus object with a subset of the letters """ print('Filtering corpus') if by_writer.get(): selected_writers = writer_filter.curselection() if len(selected_writers) == 0: r...
The code's main task is to search a filtered corpus using user-defined parameters (term, sensitivity, output format) and display or save results as concordances, frequency counts, or category-based statistics, handling errors and formatting outputs accordingly.
def search(): """ Searches the corpus and outputs the results according to the user's specifications :return: None """ try: corp = filter_corpus() print('Finished filtering') term = search_term.get() is_sensitive = sensitive.get() write_to_file = to_file.get()...
def check_probability(x, name="probability"): """Check that a probability is between 0 and 1.""" if not (0 <= x <= 1): msg = "Invalid %s '%s', it must be in [0, 1]." % (name, str(x)) raise ValueError(msg) def convert_index_to_state(index): """Convert transition probability matrix index to st...
The function `get_transition_and_reward_arrays` generates transition probability matrices (P) and reward vectors (R) for a Markov Decision Process (MDP) in fire management. Given a probability `s` of population staying in its abundance class, it computes P (A×S×S) and R (length S) by iterating over states and actions. ...
def get_transition_and_reward_arrays(s): """Generate the fire management transition and reward matrices. The output arrays from this function are valid input to the mdptoolbox.mdp classes. Let ``S`` = number of states, and ``A`` = number of actions. Parameters ---------- s : float ...
def stop(self): self.running = False self.logger.info("Server stopped") def remove_old_clients(self): # Identify clients that haven't sent a heartbeat for a while now = time.time() remove = set() for c, hb_ts in self.clients.items(): if now - hb_ts > 20: ...
This code sets up a UDP server to listen on a specified port, handling incoming messages via a receive loop. It manages client connections, sends queued messages, and processes data using select() for non-blocking I/O. The server runs until stopped, logging errors and closing the socket upon termination.
def server(self): try: self.sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP self.sock.setblocking(False) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.interface...
def ComputeConvLayer(in_data, layer_name): print("-- compute " + layer_name) weight = LoadConvWeight(layer_name) param = LoadConvParam(layer_name) # ci, co, kernel, stride, pad hi = in_data.shape[0] wi = in_data.shape[1] ci = param[0] co = param[1] kernel = param[2] stride = param[3] pad = param[4...
The function `ComputeBottleNeck` implements a residual bottleneck block for neural networks. It processes input data through three convolutional layers with batch normalization and ReLU activations. If `down_sample` is True, it adds a shortcut connection via a downsampling convolution; otherwise, it uses the input dire...
def ComputeBottleNeck(in_data, bottleneck_layer_name, down_sample = False): print("compute " + bottleneck_layer_name) out = ComputeConvLayer(in_data, bottleneck_layer_name + "_conv1") out = ComputeBatchNormLayer(out, bottleneck_layer_name + "_bn1") out = ComputeReluLayer(out) out = ComputeConvLayer(out, bottl...
def compute_conv_layer(in_data, layer_name): print("-- compute " + layer_name) weight = load_conv_weight(layer_name) param = load_conv_param(layer_name) # ci, co, kernel, stride, pad hi = in_data.shape[0] wi = in_data.shape[1] ci = param[0] co = param[1] kernel = param[2] stride = param[3] pad = p...
The function computes a bottleneck block in a neural network, processing input data through three convolutional layers with batch normalization and ReLU activations. It implements a residual connection by adding either the original input (if no downsampling) or a downsampling shortcut path (if enabled) to the final bat...
def compute_bottleneck(in_data, bottleneck_layer_name, down_sample = False): print("compute " + bottleneck_layer_name) out = compute_conv_layer(in_data, bottleneck_layer_name + "_conv1") out = compute_bn_layer(out, bottleneck_layer_name + "_bn1") out = compute_relu_layer(out) out = compute_conv_layer(out, bot...
def compute_conv_layer(in_data, layer_name): print("-- compute " + layer_name) weight = load_conv_weight(layer_name) param = load_conv_param(layer_name) # ci, co, kernel, stride, pad hi = in_data.shape[0] wi = in_data.shape[1] ci = param[0] co = param[1] kernel = param[2] stride = param[3] pad = p...
This function computes a bottleneck block in a neural network, processing input data through three convolutional layers with batch normalization and ReLU activations. If downsampling is enabled, it adds a shortcut connection using a separate convolutional layer; otherwise, it adds the original input. The output is the ...
def compute_bottleneck(in_data, bottleneck_layer_name, down_sample = False): print("compute " + bottleneck_layer_name) out = compute_conv_layer(in_data, bottleneck_layer_name + "_conv1") out = compute_bn_layer(out, bottleneck_layer_name + "_bn1") out = compute_relu_layer(out) out = compute_conv_layer(out, bot...
def ComputeConvLayer(in_data, layer_name): print("-- compute " + layer_name) weight = LoadConvWeight(layer_name) param = LoadConvParam(layer_name) # ci, co, kernel, stride, pad hi = in_data.shape[0] wi = in_data.shape[1] ci = param[0] co = param[1] kernel = param[2] stride = param[3] pad = param[4...
This code processes an input image through a deep neural network architecture, applying convolutional layers, batch normalization, ReLU activation, max pooling, and multiple residual bottleneck blocks with varying downsampling. It progressively transforms the image data through layered feature extraction, culminating i...
def run(self, img): out = ComputeConvLayer(img, "conv1") out = ComputeBatchNormLayer(out, "bn1") out = ComputeReluLayer(out) out = ComputeMaxPoolLayer(out) # layer1 out = ComputeBottleNeck(out, "layer1_bottleneck0", down_sample = True) out = ComputeBottleNeck(out, "layer1_bottleneck1", dow...
def load_config(): # Make the global variables writable from local scope. global config, ROT_CIPHER_SHIFT, PATH_VAULT, PATH_LOG # Instantiate a ConfigParser instance and store it in config. config = configparser.ConfigParser() # Check if the config already exists, if not create it with def...
The main task of the code is to run a menu-driven application that loads configuration and password vault data, processes user input via a loop, executes selected menu functions, handles errors, and logs activities. It clears the screen, displays options, and exits gracefully when requested, ensuring secure data handli...
def main(): try: # Load the config.ini settings load_config() # Load the user password vault load_vault() except Exception as ex: print_error(ex) # Loop the menu until exit has been requested. while not exit_requested: # Clear the screen to r...
def _fetch_baseline(self, version: str) -> None: """ Fetch Baseline from GitHub. Use local copy if available. """ logging.info(f"Fetching Baseline: {version}...") search_paths = [ DOWNLOAD_CACHE.name + "/Baseline.zip", "Baseline.zip" ] ...
This method constructs a baseline package by loading configuration data, fetching required components (SwiftDialog/Installomator), parsing settings, setting permissions, validating configurations, generating fake icons if needed, and creating a .pkg file. It handles mobileconfig file path adjustments and raises excepti...
def build(self) -> None: """ Build Baseline Raises: Exception: Unable to generate pkg. """ self.configuration = plistlib.load(open(self.configuration_file, "rb")) self._fetch_baseline(version=self._baseline_version) if self._build_cache_swift_dialog ...
def get_pawn_moves(self, row, col): """ :param row: int :param col: int :return: list of pawn moves """ moves = [] piece = self.board_logic_array[row, col] # Check if the Pawn is white or black if piece.isupper(): direction = -1 # Whi...
This function generates all possible moves for a specified chess piece based on its type and position on the board. It delegates to specialized methods for each piece (pawn, knight, bishop, rook, queen, king) to calculate valid moves, returning a list of coordinate tuples. The function handles both uppercase (white) an...
def single_piece_move(self, piece, row, col): """ Get all possible moves, even if it reveals king :param piece: str :param row: int :param col: int :return: list of tuples (moves) """ if piece == 'P' or piece == 'p': moves = self.get_pawn_moves...
def get_train_data(): mfccfeatures, plpfeatures = None, None trainlabels = [] for label in labels: mfccs, plps = extract_features("Train_dataset/" + label+".wav", 5) numexamples = mfccs.shape[0] if mfccfeatures is None: mfccfeatures = mfccs else: mfccf...
The main task of the code is to provide a menu-driven interface for training and testing classifiers. It repeatedly prompts the user to choose between retraining models (option 1), evaluating them (option 2), or exiting (option 3). Input validation ensures valid choices, and the code executes corresponding actions: tra...
def main(): # Train classifiers message = """ Choose an operation: 1- Train 2- Test 3- Exit Enter 1, 2 or 3 """ while True: # choice = input("Enter 'train' to retrain the classifiers, 'test' to evaluate, or 'exit' to quit: ") choice = int(input(message)) whil...
def isLegalMove(self, column, state): """ Boolean function to check if a move (column) is a legal move """ for i in range(6): if state[i][column] == ' ': # once we find the first empty, we know it's a legal move return True # if we get here, ...
This function performs a minimax search with alpha-beta pruning to evaluate optimal moves in a game. It recursively explores legal moves up to a specified depth, alternating players, and returns the maximum alpha value representing the best possible score for the current player assuming optimal opponent play.
def search(self, depth, state, curr_player): """ Searches the tree at depth 'depth' By default, the state is the board, and curr_player is whomever called this search Returns the alpha value """ # loop w/ conditional statement for legal moves legal_m...
def isLegalMove(self, column, state): """ Boolean function to check if a move (column) is a legal move """ for i in range(6): if state[i][column] == ' ': # once we find the first empty, we know it's a legal move return True # if we get here, ...
The alphaBeta function implements the minimax algorithm with alpha-beta pruning to determine the optimal move for the current player in a game state. It evaluates all legal moves by recursively calling the search function, negating the opponent's scores, and selects the move with the highest alpha value. The function r...
def alphaBeta(self, depth, state, curr_player): """ Returns the best move (as a column number) and the associated alpha Calls search() """ # determine opponent's piece if curr_player == self.pieces[0]: opp_player = self.pieces[1] else: opp_pla...
def exec_open_file_dialog(self): """Executes open file dialog.""" dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) if dlg.exec_(): file_path = dlg.selectedFiles()[0] self.file_name = file_path[file_path.rfind('/')+1 :] self.wave_params, self.d...
The code initializes a GUI application with VAD functionality, setting up the UI, connecting menu actions to methods for file operations, VAD processing, and result visualization. It links menu items to functions like opening files, applying VAD, displaying input/output, saving results, and showing an about window, usi...
def __init__(self): super().__init__() self.setupUi(self) # initializing design self.about = None self.input_file = vad.SimpleVAD() self.menuOpenNew.triggered.connect( lambda: self.exec_open_file_dialog()) self.menuExit.triggered.connect( lambda: ...
def initialize_weights(input_size, hidden_size): W1 = np.random.rand(input_size, hidden_size) b1 = np.random.rand(hidden_size) W2 = np.random.rand(hidden_size, 1) b2 = np.random.rand() return W1, b1, W2, b2 def feedforward(X, W1, b1, W2, b2): A1 = sigmoid(np.dot(X, W1) + b1) H2 = sigmoid(np.dot(A1, W2) + ...
The code trains a simple neural network with two layers using gradient descent. It initializes weights and biases, iteratively performs forward and backward propagation to adjust parameters, and stops early if the prediction error falls below a threshold. The main task is to optimize the network's parameters to minimiz...
def train(X, y, learning_rate, epochs): W1, b1, W2, b2 = initialize_weights(2, 1) for epoch in range(epochs): A1, H2 = feedforward(X, W1, b1, W2, b2) dW1, db1, dW2, db2 = backpropagation(X, y, A1, H2, W1, W2, b1, b2, learning_rate) W1 -= dW1 b1 -= db1 W2 -= dW2 b2 -= db2 if np.mean(...
def timedelta_to_minutes(t: timedelta): return t.days * 1440 + t.seconds // 60 def get_position_information(self, entry_date: dt, exit_date: dt, signal_type): ''' Get Position Entry , MaxDrawdown , Close ''' minutes_diff = self.timedelta_to_minutes((exit_date - entry_date)) ...
The code processes a sequence of trading signals to evaluate a strategy's performance. It calculates time intervals between signals, computes position details and alpha scores (profit metrics) for each valid signal, accumulates these values, and finally determines an overall effective profit rate score using numpy arra...
def test(self, signals: Iterable): ''' Test All Signal Paramas : Signals as tuple (Date:dt , Signal_type:int ) ''' alpha_array = [] t2c_array = [] for index in range(len(signals) - 1): date, sig = signals[index] next_date, _ = signals[in...
def get_key(idx: int) -> str: """ Get scancode or name of key from its index. If key shadows a function key and function modifier key is down, return function key. """ if should_use_function_key(idx): return KEYS[idx]["shadow_function_key"] if "scancode" in KEYS[idx]: return KEY...
The function `press_key` simulates or actually presses a keyboard key based on its index and a `dry_run` flag. If `dry_run` is True, it logs the action instead of executing it. It checks if the key exists, handles function modifier keys by updating their state, and uses `keyboard.press_and_release` or `keyboard.press` ...
def press_key(idx: int, dry_run: bool) -> None: """ Press key with given index, or just pretend to. @param[in] idx Index of key. @param[in] dry_run Print a message to stdout instead of actually pressing key if True """ if idx not in KEYS: return key = get_key(idx) if is_functi...
def get_key(idx: int) -> str: """ Get scancode or name of key from its index. If key shadows a function key and function modifier key is down, return function key. """ if should_use_function_key(idx): return KEYS[idx]["shadow_function_key"] if "scancode" in KEYS[idx]: return KEY...
This function releases a keyboard key corresponding to the given index, either performing the action or simulating it via a printed message if dry_run is True. It handles function modifier keys by updating their state and uses conditional logic to determine whether to press/release or just release the key based on its ...
def release_key(idx: int, dry_run: bool) -> None: """ Release key with given index, or just pretend to. @param[in] idx Index of key. @param[in] dry_run Print a message to stdout instead of actually pressing key if True """ if idx not in KEYS: return key = get_key(idx) if is_fu...
def load_key_calibration(cal_fd: TextIO) -> None: """ Load key calibration from file. @param[in] cal_fd File descriptor of open calibration file. """ for field, cfg in json.load(cal_fd).items(): idx = int(field) KEYS[idx] = cfg if is_function_key_modifier(idx): F...
The main task of the code is to process command-line arguments for hardware interaction, loading calibration data, adjusting process priority, and executing actions like raw keyscan output, key detection, voltage plotting, or message reading from a device, based on specified flags.
def main(args: argparse.Namespace) -> int: with open(args.calibration, "r") as cal_fd: load_key_calibration(cal_fd) set_niceness(niceness=args.niceness) if args.raw: for scan in read_keyscans(device=args.device, baudrate=args.baudrate): print_raw_scan(scan) elif args.dete...
def TotalBinomial(self, FirstValue, SecondValue): Minor = min(FirstValue, SecondValue) Mayor = max(FirstValue, SecondValue) return self.Factorial(Mayor)/(self.Factorial(Mayor - Minor)*self.Factorial(Minor)) def PositionsCombinations(self, Total, Subgroup): PositionsList = [] Addi...
This recursive function generates all combinations of 'Subgroup' elements from 'Objects' by recursively building each combination. It uses positional indices to select elements, appends valid combinations to 'ObjectPositions', and iterates through all possible binomial coefficients, returning the complete list of combi...
def RecursiveCombinational(self, Objects, Subgroup, ObjectPositions, Positions, Index, SubIndex): if Index == self.TotalBinomial(len(Objects), Subgroup): return ObjectPositions if SubIndex < Subgroup: ListOfPositions = self.PositionsCombinations(len(Objects), Subgroup) ...
def SumOfLists(self, Answer, FirstList, SecondList, Swivel): if Swivel < len(FirstList): ObjectList = [] Answer.append(self.SetEqual(ObjectList, FirstList, Swivel, 0)) return self.SumOfLists(Answer, FirstList, SecondList, Swivel + 1) elif len(FirstList) <= Swivel < le...
The main task of the code is to recursively generate and sum all binomial combinations of the input list `Objects`. It uses recursion to build combinations incrementally, starting from `Index` and combining results with `SumOfLists`, until reaching the base case where `Index` equals the list length, returning the final...
def AllBinomial(self, Objects, Index): if Index < len(Objects): SumArrays = [] return self.SumOfLists(SumArrays, self.Combinational(Objects, Index), self.AllBinomial(Objects, Index + 1), 0) else: return self.Combinational(Objects, len(Objects))
def createFolders(): if os.path.exists('Dummy'): shutil.rmtree('Dummy') os.mkdir('Dummy') os.mkdir('Dummy/input') os.mkdir('Dummy/output') os.mkdir('Dummy/output2') os.mkdir('Dummy/output2/A') def processInput(): input_folder = 'Dummy/input' output_folder = 'Dummy/output' out...
The main task of the code is to process audio files by splitting them, analyzing their language using a prediction model, and generating output files. It creates directories, processes input files, saves results, cleans temporary data, reads processed outputs, predicts language labels, and formats final outputs with ta...
def mainn(): createFolders() splitFiles, audio_length, actual_language = processInput() save(splitFiles) shutil.rmtree('Dummy') # os.remove('AudioFiles/audiofile.mp3') X = read_output_file() final_lang_array, tab_str1, tab_str2 = predict(X, audio_length) output(final_lang_array, tab_str1...
def find_commit_info(list_of_commits, commit_hash): list_of_commits = [ extract_info_from_log_entry(log_entry) for log_entry in list_of_commits] for commit_info in list_of_commits: if commit_info['hash'] == commit_hash: return commit_info return None def extract_info_from_log_en...
The function reverts a Git repository to a specified commit using a hash or user-selected commit. It retrieves commit history, validates the target commit, saves current changes, performs reverts, and consolidates multiple reverts into a single commit if needed. The task involves handling user input, commit lookup, and...
def goBack(ctx, commit_hash): """ Returns version to a specific commit via hash or selected commit To display a list with all the commits run: $ gt goback If you know the hash of the commit you want to go back to, then run $ gt goback --hash <commitHash> """ repo = ctx.obj[...
def position(x, dx): r = [ ] t = int(((x*2)/dx)+1) for i in range(t): r.append(-x+dx*i) return r def wavefunction(r): phi = [m.cos(i) for i in r] #phi = [i*i for i in r] #phi = [1/(m.pi** (1/4)) * m.exp(- (i**2)/2) for i in r] return phi def kinetic(phi,r,dx): k = [] ...
The main task of the code is to compute the energy of a quantum system using a Monte Carlo method. It calculates particle positions, wavefunction values, kinetic energy, initial energy, and iteratively refines the energy estimate through Monte Carlo sampling, integrating quantum mechanical properties and stochastic sim...
def main(): r = position(x,dx) phi = wavefunction(r) k = kinetic(phi,r,dx) E0 = Energyinitial(k, phi, r, dx) E = Monte_carlo(phi, k,E0,r, dx)
def compute_d1(S,K,r,delta,sigma,TTM): numerator = np.log(S/K)+(r-delta+((sigma**2)/2)*TTM) denominator = sigma*np.sqrt(TTM) return numerator/denominator def compute_d2(d1,sigma,TTM): return d1-sigma*np.sqrt(TTM) def approximateNormCDF(value): # This method is what is used to help alleviate when a ...
This function calculates the price of a European call option using the Black-Scholes model and an approximation method. It computes the exact call price via the cumulative normal distribution function (norm.cdf) and an approximate version using approximateNormCDF. Both methods use d1 and d2 derived from input parameter...
def compute_call(strike, underlying, TTM, imp_vol, div_yield, rate): #Computes D1/D2 and uses them for both call value approaches d1 = compute_d1(underlying, strike, rate, div_yield, imp_vol, TTM) d2 = compute_d2(d1,imp_vol, TTM) call_price = (underlying * np.exp(-1*div_yield*TTM)*norm.cdf(d1)) cal...
def compute_d1(S,K,r,delta,sigma,TTM): numerator = np.log(S/K)+(r-delta+((sigma**2)/2)*TTM) denominator = sigma*np.sqrt(TTM) return numerator/denominator def compute_d2(d1,sigma,TTM): return d1-sigma*np.sqrt(TTM) def approximateNormCDF(value): # This method is what is used to help alleviate when a ...
The code computes the exact and approximate prices of a European put option using the Black-Scholes model. It calculates D1 and D2, then applies the Black-Scholes formula with both the standard normal CDF (for exact pricing) and an approximate CDF (for estimation). The function returns both computed put prices, incorpo...
def compute_put(strike, underlying, TTM, imp_vol, div_yield, rate): # Computes D1/D2 and uses them for both put value approaches d1 = compute_d1(underlying, strike, rate, div_yield, imp_vol, TTM) d2 = compute_d2(d1,imp_vol, TTM) put_price = -1*(underlying * np.exp(-1*div_yield*TTM)*norm.cdf(-1*d1)) ...
def calculate_powers(bus_lst): for bus1 in bus_lst: bus1.P = 0 bus1.Q = 0 total_y = 1j * bus1.comp for bus2 in bus1.connected_lines: total_y += bus1.connected_lines[bus2].y bus1.P -= bus1.V * bus2.V * Pc(bus1, bus2, bus1.connected_lines[bus2].y) bu...
The function performs Newton-Raphson iterations for power flow analysis on a power system, updating bus voltages and angles. It runs 4 iterations, recalculating the Jacobian matrix and adjusting variables each time. If set_print is True, it prints iteration progress and system states. The primary task is to solve power...
def newton_raphson(bus_lst, set_print=True): calculate_powers(bus_lst) if set_print and False: #this if does not run print('---------------------------------------------------------------------------') print('initial conditions') printsys(bus_lst) # print('Initial Jacobian') ...
def has_password(): if os.path.isfile(password_file): return True else: return False def login(): possible_tries = 3 while possible_tries > 0: password = input("Enter password: ") if (validate_password(password)): if (app_state["filename"]): sh...
The main task of the code is to display a welcome message, handle command-line input for a filename, and determine whether to prompt for login or signup based on password existence. It initializes application state with a provided filename if specified, then executes login or signup workflows depending on password vali...
def main(): print(strings["welcome"]) if len(sys.argv) == 2: app_state["filename"] = sys.argv[1] print(f"Login to see the file: {app_state['filename']}") if (has_password()): login() else: signup()
def general(ax, glsize, ys): xf = gen_xf(glsize) # vertical lines ax.vlines(xf, ys[0], ys[1], colors="#000000") # horizontal lines for cnt, (x0, x1) in enumerate(zip(xf[:-1], xf[1:])): ls = "--" if 3 == cnt or 7 == cnt else "-" ax.hlines(ys, x0, x1, colors="#000000", linestyles=ls) ...
The main task of the code is to generate and save a customized plot based on the input filename. It creates a figure with a specified size, disables axis display, and applies a general setup. Depending on the filename, it calls one of four grid functions (grid1-grid4) to draw specific layouts. Finally, it saves the gen...
def main(fname): glsize = 11 ys = [0., 1.] fig = pyplot.figure(figsize=(glsize+2, np.max(ys)-np.min(ys)+2.)) ax = pyplot.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) general(ax, glsize, ys) if "grid1" == fname: grid1(ax, glsize, ys) elif "grid2" == fname: ...
def generate_encode_template(self, batch_size): boxes_batch = [] for boxes in self.boxes_list: boxes = np.expand_dims(boxes, axis=0) boxes = np.tile(boxes, (batch_size, 1, 1, 1, 1)) boxes = np.reshape(boxes, (batch_size, -1, 4)) boxes_batch.a...
This code decodes predicted bounding box coordinates from a model's output, applying confidence thresholding, non-maximum suppression (NMS), and coordinate normalization. It converts encoded predictions to actual box coordinates, filters low-confidence boxes, suppresses overlapping boxes using greedy NMS, and returns t...
def decode_y(self, y_pred, confidence_thresh = 0.1, iou_threshold = 0.45, top_k = 200, normalize_coords = False, img_height = None, img_width = None): y_encode_template = self.generate_encode_template(batch_size = len(y_pred)) y_pred_decoded = np.copy(y_pred) y_pred_decoded[:,:,-2] = ...
def get_pp(startyear=None,startmonth=None,member=None): """ Return the postprocess path for the ensemble or control. """ prod=sysconfig['prod'] return '/'.join([sysconfig['rootdir'],get_configid(startyear,startmonth,member),prod,'pp']) def get_ppname(variable, frequency, pp=None, constraint=None): ...
The function `get_pathDict` generates a dictionary containing key-value pairs required for GFDL simulations, using inputs like variable, frequency, and optional ensemble parameters (startyear, startmonth, member). If ensemble details are omitted, it defaults to the control simulation. The dictionary includes keys such ...
def get_pathDict(variable,frequency,constraint=None,startyear=None,startmonth=None,member=None,time='*',out='ts'): """ Return a pathDict dictionary for the given variable and frequency, and for the ensemble characteristics given. The pathDict dictionary contains all of the relevant key-value pairs to b...
def create_config_menu(self, menu_bar): #Creates the Configuration menu edit_menu = menu_bar.addMenu('Config') set_path_action = QAction('Set Warcraft3 path', self) set_path_action.triggered.connect(self.change_path) edit_menu.addAction(set_path_action) close_action = QA...
The main task of the code is to create and configure a menu bar in a GUI application. It initializes the menubar using `self.menuBar()`, then adds three distinct menus—configuration, guides, and help—by calling corresponding methods. Each method likely populates the menubar with specific options or actions related to t...
def setup_menu_bar(self): menubar = self.menuBar() self.create_config_menu(menubar) self.create_guides_menu(menubar) self.create_help_menu(menubar)
def get_profiles(self): path = os.path.normpath(os.path.join(self.custom_path, "CustomMapData", "Twilight's Eve Evo")) wc3_names_directories = [] try: for wc3_names_directory in os.listdir(path): full_path = os.path.join(path, wc3_names_directory) if o...
The main task of the code is to load profiles, set an active profile if none exists, retrieve class names, and update the GUI if class data is available. It ensures configuration initialization by selecting the first profile when no active one is set and triggers a GUI update based on retrieved class information.
def main(self): profiles = self.get_profiles() if profiles: if self.active_profile == "": self.active_profile = profiles[0] self.update_config_file() class_name_list = self.get_class_names() if self.class_list: s...
def get_class_names(self): class_names = [] profile_path = os.path.join(self.custom_path, "CustomMapData", "Twilight's Eve Evo", self.active_profile) if os.path.exists(profile_path): class_list = {} for evo_class_name in os.listdir(profile_path): class...
This code initializes a GUI application for reading and managing Warcraft III (WC3) files, setting up window properties, loading configuration data, and preparing structures to handle class lists, recipes, and user profiles. It initializes variables for file paths, user settings, and UI components, then calls methods t...
def __init__(self): super().__init__() self.original_width = 400 self.original_height = 400 self.dir_contents = {} self.selected_classes = [] self.setWindowTitle("Evo File Reader") self.setGeometry(100, 100, 400, 400) self.VERSION = "v1.2" self.ICO...
def cell_profile(image, cell): ax = np.array([np.cos(cell.angle), np.sin(cell.angle)]) p0 = cell.pos - ax*(cell.length*0.5 + cell.radius) p1 = cell.pos + ax*(cell.length*0.5 + cell.radius) profile = profile_line(image, (p0[1], p0[0]),(p1[1],p1[0]), order=2) return profile def plot_solution(mincells,...
The code processes each cell by analyzing its intensity profile to identify potential split points. It checks if a minimum in the profile meets depth, position, and length criteria. If valid, the cell is split into two new cells with adjusted positions and lengths. Invalid cells remain unchanged. The function updates t...
def split_cells(im, cells, minlen): #print('--- Split cells ---') newcells = [] plt.subplot(1,3,3) plt.cla() for cell in cells: profile = cell_profile(im, cell) plt.plot(profile, '.-') # Find minima of profile minima = argrelmin(profile)[0] #print('Minima ',m...
def decideAction(): sensorVal = getSensorReadings() # map sensorVal to BOT_MOVEMENT if (sensorVal[S2] == 0 and sensorVal[S3] == 1) or (sensorVal[S1] == 0 and sensorVal[S2] == 0 and sensorVal[S3] == 0 and sensorVal[S4] == 1): return "adjust_right" elif (sensorVal[S2] == 1 and sensorVal[S3] == 0) ...
This function executes navigation actions based on a decision variable, handling movement commands (straight, turn, adjust), dead-end logic (backtracking via explorer_list), exploration termination ("stay"), and decision logging. It maps decisions to specific robotic motions, tracks exploration paths, and terminates wh...
def act(): decision = decideAction() if decision != "straight" and decision != "adjust_left" and decision != "adjust_right": print(decision) if decision == "straight": straight() elif decision == "adjust_left": adjust_left() elif decision == "adjust_right": adjust_ri...
def load(self, pull_gcs: bool = True): """Load the protocol data from a local pickle file.""" if self.use_gcs_protocol_sync: if pull_gcs: self.accessed_gcs = self.gcs_pull() else: self.accessed_gcs = False else: self.accessed_gc...
The function marks an experiment as completed by updating its status and metadata in a database, including stop time, duration, and report status. If GCS storage is enabled, it uploads the experiment's results as a ZIP file to a cloud bucket. The update includes setting "job_status" to "completed" and logging the compl...
def complete( self, experiment_id: Union[int, str], report: bool = False, save: bool = True, ): """Set status of an experiment to completed - change status in db.""" self.load() experiment_data = self.get(experiment_id) # Store experiment directory in ...
def send_image(): global teleported global saved_picture completed_image = [] circuitList = [] error_rate = [] if saved_picture: columnCount = 0 if variable.get() == "80x80": columnCount = 80 if variable.get() == "160x160": columnCount = 160 ...
The code creates a graphical user interface (GUI) for a quantum computing or simulation tool, featuring input/output display areas, adjustable error parameters (gate and measurement), pixel density settings, and buttons to teleport images/messages. It initializes canvas elements, labels, scales, and buttons for user in...
def createFrontend(): global meas_scale, gate_scale, pixel_density global input_display , output_display canvas.place(x = 0, y = 0) canvas.create_rectangle( 40, 300, 360, 375, fill="grey", outline="black") # in canvas.create_rectangle( 790, 300, 1110, 375, fill="grey", outline="black") # out ...
def gen_users_route(user_id=None, extra=False): user_route = EXTRA_CREDIT_USER_ROUTE if extra else USER_ROUTE return ( f"{user_route}s/" if user_id is None else f"{user_route}/{str(user_id)}/" ) def gen_users_path(user_id=None, extra=False): return f"{LOCAL_URL}{gen_users_route(u...
This test verifies that a GET request to the users endpoint returns a 200 OK status and ensures the "users" field in the JSON response is a list. It checks the response structure, validates the status code, and confirms the data type of the "users" field, raising an error if the type mismatch occurs.
def test_get_initial_users(self): req_type = "GET" route = gen_users_route() res = requests.get(gen_users_path()) self.jsonable_test(res, req_type, route, 200) users = res.json().get("users") self.assertEqual( type(users), list, wrong_...
def gen_users_route(user_id=None, extra=False): user_route = EXTRA_CREDIT_USER_ROUTE if extra else USER_ROUTE return ( f"{user_route}s/" if user_id is None else f"{user_route}/{str(user_id)}/" ) def gen_users_path(user_id=None, extra=False): return f"{LOCAL_URL}{gen_users_route(u...
This test method verifies the correct creation of a user by sending a POST request with sample data, checking the response status code (201), and asserting that the returned JSON matches the expected sample user data, including a zero balance.
def test_create_user(self): req_type = "POST" route = gen_users_route() res = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER)) self.jsonable_test(res, req_type, route, 201, SAMPLE_USER) user = res.json() for key in SAMPLE_USER.keys(): self.assertE...
def gen_users_route(user_id=None, extra=False): user_route = EXTRA_CREDIT_USER_ROUTE if extra else USER_ROUTE return ( f"{user_route}s/" if user_id is None else f"{user_route}/{str(user_id)}/" ) def gen_users_path(user_id=None, extra=False): return f"{LOCAL_URL}{gen_users_route(u...
The code tests creating and retrieving a user via POST/GET requests. It verifies the POST response returns valid JSON with an 'id' field, then uses that ID to fetch the user via GET. It checks the GET response's JSON validity, confirms the 'id' exists, and validates all fields match the sample input, including ensuring...
def test_get_user(self): req_type = "POST" route = gen_users_route() res = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER)) jsonable, error = is_jsonable(res, req_type, route, SAMPLE_USER) self.assertTrue( jsonable, error_str( ...
def gen_users_route(user_id=None, extra=False): user_route = EXTRA_CREDIT_USER_ROUTE if extra else USER_ROUTE return ( f"{user_route}s/" if user_id is None else f"{user_route}/{str(user_id)}/" ) def gen_users_path(user_id=None, extra=False): return f"{LOCAL_URL}{gen_users_route(u...
The code tests the deletion of a user via API by creating a user, deleting it, and verifying the deletion's success through response checks. It confirms the user's data matches the sample post-deletion and ensures a 404 error occurs when retrieving the deleted user, validating proper API behavior.
def test_delete_user(self): req_type = "POST" route = gen_users_route() res = requests.post(gen_users_path(), data=json.dumps(SAMPLE_USER)) jsonable, error = is_jsonable(res, req_type, route, SAMPLE_USER) self.assertTrue( jsonable, error_str( ...
def gen_users_route(user_id=None, extra=False): user_route = EXTRA_CREDIT_USER_ROUTE if extra else USER_ROUTE return ( f"{user_route}s/" if user_id is None else f"{user_route}/{str(user_id)}/" ) def gen_users_path(user_id=None, extra=False): return f"{LOCAL_URL}{gen_users_route(u...
This function creates a user with a specified balance, sends a POST request to register the user, verifies the HTTP 201 response, and asserts that the returned user data matches the input, including the balance. It returns the JSON response for further testing.
def _create_user_and_assert_balance(self, balance, extra=False): dummy_user = EXTRA_SAMPLE_USER if extra else SAMPLE_USER user_with_balance = {**dummy_user, "balance": balance} req_type = "POST" route = gen_users_route(extra=extra) res = requests.post( gen_users_path(...
def gen_users_path(user_id=None, extra=False): return f"{LOCAL_URL}{gen_users_route(user_id, extra)}" def jsonable_test(self, res, req_type, route, status_code, body=None): jsonable, error = is_jsonable(res, req_type, route, body) self.assertTrue(jsonable, error) self.assertEqual( ...
The main task of this code is to retrieve user data via GET or POST requests, validate the response's JSON structure and status code, and assert that the returned user fields (including balance) match expected values from a sample user dictionary. It handles both standard and "extra" user scenarios, verifying all key-v...
def _get_user_and_assert_balance(self, user_id, balance, extra=False): dummy_user = EXTRA_SAMPLE_USER if extra else SAMPLE_USER req_type = "POST" if extra else "GET" route = gen_users_path(user_id, extra=extra) print(dummy_user.get("password")) res = (requests.post(gen_users_pat...
def gen_send_path(extra=False): return f"{LOCAL_URL}{gen_send_route(extra)}" def jsonable_test(self, res, req_type, route, status_code, body=None): jsonable, error = is_jsonable(res, req_type, route, body) self.assertTrue(jsonable, error) self.assertEqual( res.status_code, ...
This function sends a POST request to transfer money between users, validates the response status, and checks if the returned transaction data matches the sent parameters, including handling optional password authentication.
def _send_money(self, user_id1, user_id2, amount, status_code, password=None, extra=False): req_type = "POST" route = gen_send_path(extra=extra) send_body = { "sender_id": user_id1, "receiver_id": user_id2, "amount": amount, } if extra: ...
def _create_user_and_assert_balance(self, balance, extra=False): dummy_user = EXTRA_SAMPLE_USER if extra else SAMPLE_USER user_with_balance = {**dummy_user, "balance": balance} req_type = "POST" route = gen_users_route(extra=extra) res = requests.post( gen_users_path(...
This test checks if an unauthorized request to an extra user endpoint returns a 401 status. It creates a user, sends a POST with incorrect credentials, and verifies the response using jsonable_test, conditional on EXTRA_CREDIT being true.
def test_extra_get_user_unauthorized(self): if not EXTRA_CREDIT: print("test unauthorized?") return user = self._create_user_and_assert_balance(5, extra=True) req_type = "POST" route = gen_users_route(user["id"], extra=True) res = requests.post(gen_users_...
def _create_user_and_assert_balance(self, balance, extra=False): dummy_user = EXTRA_SAMPLE_USER if extra else SAMPLE_USER user_with_balance = {**dummy_user, "balance": balance} req_type = "POST" route = gen_users_route(extra=extra) res = requests.post( gen_users_path(...
This test verifies that the send_money function correctly transfers funds between users when the sender has sufficient balance, and fails to execute when the sender's balance is insufficient, ensuring balances remain unchanged in such cases. It checks successful transfers and handles overdraft scenarios by validating u...
def test_send_money(self): user_id1 = self._create_user_and_assert_balance(10).get("id") user_id2 = self._create_user_and_assert_balance(10).get("id") self._send_money(user_id1, user_id2, 6, 200) self._get_user_and_assert_balance(user_id1, 4) self._get_user_and_assert_balance(use...
def _create_user_and_assert_balance(self, balance, extra=False): dummy_user = EXTRA_SAMPLE_USER if extra else SAMPLE_USER user_with_balance = {**dummy_user, "balance": balance} req_type = "POST" route = gen_users_route(extra=extra) res = requests.post( gen_users_path(...
This test verifies the send money functionality with extra credit, ensuring that users cannot overdraw their balances. It creates two users, transfers funds between them, checks balance updates after a valid transaction, and confirms balances remain unchanged after an invalid overdraft attempt. The test validates corre...
def test_extra_send_money(self): if not EXTRA_CREDIT: return user1 = self._create_user_and_assert_balance(10, extra=True) user_id1 = user1.get("id") user_id2 = self._create_user_and_assert_balance(10, extra=True).get("id") self._send_money(user_id1, user_id2, 6, 200, ...
def create_file_table( folder_path: str, destination_path: str = None, save: bool = False ) -> pd.DataFrame: """ Creates a DataFrame containing the file paths of all the Markdown files (.md) found in the specified folder path. Args: folder_path (str): The path to the folder containing the M...
The main task of the code is to generate a master dataset by creating a CSV file listing text file paths, enriching it with the actual text content, and converting it into a Hugging Face Arrow dataset for efficient processing. It uses input parameters to define paths and controls file creation, data updating, and datas...
def generate_master(de_params: Dict[str, Any]) -> None: """ Generate the master dataset by performing a series of steps: 1. Load parameters from the dictionary. 2. Create a CSV file that lists paths to individual text files. 3. Update the CSV file with the actual text content of the files. 4. Co...
def clearScreen(): """Clears the terminal.""" os.system('cls' if os.name == 'nt' else 'clear') def load_data(): global cars with open(MY_DATA, 'r') as filehandle: cars = json.load(filehandle) def menu(): """Prints the menu, returns user selection.""" ic('V -> View all cars.') ic('A -...
The main task of the code is to run a program that continuously displays a menu, processes user selections, and executes corresponding actions. It initializes by clearing the screen and loading data, then loops to show the menu, capture user input, clear the screen again, and invoke the appropriate function based on th...
def main(): clearScreen() load_data() while True: userSelection = menu() clearScreen() menuAction(userSelection)
def clearScreen(): """Clears the terminal.""" os.system('cls' if os.name == 'nt' else 'clear') def load_data(): global animals with open(MY_DATA, 'r') as filehandle: animals = json.load(filehandle) def menu(): """Prints the menu, returns user selection.""" print('V -> View all animals.')...
The code's main task is to run a program that clears the screen, loads data, displays a menu, processes user selections, and executes corresponding actions in a loop until exited.
def main(): clearScreen() load_data() while True: userSelection = menu() clearScreen() menuAction(userSelection)
def _make_rest_call(self, action_result, endpoint, data=None, params={}, headers={}, method="get", auth=None, **kwargs): """ Returns 2 values, use RetVal """ url = self._base_url + endpoint try: request_func = getattr(requests, method) except AttributeError: # S...
This helper function handles REST API calls, retrying with a new OAuth token if an unauthorized error occurs. It attempts to fetch fresh credentials, and if successful, retries the request. If credential retrieval fails, it returns an error.
def _make_rest_call_helper(self, action_result, endpoint, data=None, params={}, headers={}, method="get", auth=None, **kwargs): try: return self._make_rest_call(action_result, endpoint, data=data, params=params, headers=headers, method=method, auth=auth, **kwargs) ...
def generate_drug_data(mol_graph, atom_symbols, smiles_rdkit_list,id): edge_list = torch.LongTensor( [(b.GetBeginAtomIdx(), b.GetEndAtomIdx(), *edge_features(b)) for b in mol_graph.GetBonds()]) edge_list, edge_feats = (edge_list[:, :2], edge_list[:, 2:].float()) if len(edge_list) else ( torch.LongT...
The code loads drug molecular data from a CSV file, converts SMILES strings to RDKit molecules, extracts unique atomic symbols, generates graph representations (PyTorch Geometric and DGL formats) for each drug molecule, and saves them as pickle files for graph-based model training.
def load_drug_mol_data(args): data = pd.read_csv(args.dataset_filename, delimiter=args.delimiter) drug_id_mol_tup = [] symbols = list() drug_smile_dict = {} smiles_rdkit_list = [] for id1, id2, smiles1, smiles2, relation in zip(data[args.c_id1], data[args.c_id2], data[args.c_s1], ...
def PeoplePerSection(seats, section): ticketsSold = GetValidInput(seats, section) if ticketsSold == SENTINEL: exit() return(ticketsSold) def TotalCost(tickets, price): cost = 0 cost = tickets * price return(cost) def PrintValues(seats, section, ticketPrice, totalPrice): print(f...
This code processes ticket sales for three sections (A, B, C) by repeatedly prompting users to input the number of tickets they want to purchase. It calculates the total cost for each transaction, updates seat availability, and maintains running totals (per transaction and overall). The loop continues until the user ch...
def main(): #declared variables SEATS = [300, 500, 200] SECTIONS = ['A', 'B', 'C'] PRICE = [20, 15, 10] keepGoing = 'y' grandTotal = 0 while keepGoing == 'y': #delcared variables ticketsSold = [0,0,0] totalPrice = [0,0,0] total = 0 i = 0 ...
def ft_mean(args): """Return the mean of the numbers given as arguments.""" length = len(args) if length == 0: raise AssertionError("ERROR") args_sum = 0 for n in args: args_sum += n return args_sum / length def ft_median(args): """Return the mean of the numbers given as argu...
The function `ft_statistics` calculates and prints statistical values (mean, median, quartile, standard deviation, variance) based on the keyword arguments provided. It iterates through each keyword value, invokes the corresponding helper function with the input arguments, and outputs the result. If an `AssertionError`...
def ft_statistics(*args, **kwargs): """Calculate statistics on the args given as arguments.""" for v in kwargs.values(): try: if v == "mean": print(f"mean: {ft_mean(args)}") elif v == "median": print(f"median: {ft_median(args)}") elif v...
def init_network(input_size, layers: list): weights = [np.zeros((layers[0], input_size))] biases = [np.zeros((layers[0], 1))] for i in range(1, len(layers)): weights.append(np.zeros((layers[i], layers[i - 1]))) biases.append(np.zeros((layers[i], 1))) return {'W': weights, 'b': biases} de...
The code initializes a neural network with 2 input neurons and layers [3, 2, 2], trains it using back-propagation on training data (trainX, trainY), prints the learned weights and biases for each layer, and evaluates the network's output for each training input via forward propagation, displaying results. The main task...
def main(): network = init_network(2, [3, 2, 2]) back_prop(network, trainX, trainY) print('________________________\n') for i in range(len(network['W'])): weight, bias = network['W'][i], network['b'][i] print(f'Weights {i}:\n{weight}\n\nBiases {i}:\n{bias}\n') print('_______________...
def restore_weights(self): try: checkpoint = torch.load(self._saving_filepath) self._model.load_state_dict(checkpoint['model_state_dict']) self._model.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) print(f"Model correctly Restored") self...
The code trains a graph-based model using sampled batches from training data, applying node dropout for regularization. It iterates over epochs, shuffles edges, processes batches with a sampler, computes loss via the model's train_step, and evaluates performance after each epoch. The main task is to optimize the model'...
def train(self): if self._restore: return self.restore_weights() row, col = self._data.sp_i_train.nonzero() ratings = self._data.sp_i_train_ratings.data edge_index = np.array([row, col, ratings]).transpose() for it in self.iterate(self._epochs): loss = 0...
def resolve_kg_id(self, uri): exclude = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#type": "type", "https://www.wikidata.org/wiki/Q853614": "identifier", "http://purl.obolibrary.org/obo/DUO_0000001": "Data use permission", "http://www.w3.org/2000/01/rdf-schema#t...
The code transforms input result values by resolving URIs into structured metadata. It extracts each URI, resolves it to a knowledge graph identifier, retrieves associated type and summary data, then compiles the results into a list of dictionaries containing resolved URI details, including name, prefix, value, type, a...
def transform_results(self, result_values): self.results = [] for result_value in result_values: uri_unres = result_value['pred']['value'] uri_dict = self.resolve_kg_id(uri_unres) if not uri_dict: continue aType = self.get_type(uri_dic...
def captioning_machine(images): captions = [] for image in images: # for each image in a listing caption = prediction_pipeline(image) captions.append(caption) return airbnb_prediction(captions) def disambiguate(description, caption): # do something to the data to "disambiguate it" #...
The code processes a listing by downloading and analyzing images, generating captions, resolving ambiguities in the listing's description using these captions, and then compiling the final text with details like URL, price, and reviews for output.
def process_listing(listing): raw_images = listing.get("photos") images = [] for image in raw_images: im = Image.open(requests.get(image, stream=True).raw) images.append(im) description = listing.get( "description" ) captions = captioning_machine(images) disambiguate...
def read_data(): with open('documents.json', 'r') as f: documents = json.load(f) return documents def process_listing(listing): raw_images = listing.get("photos") images = [] for image in raw_images: im = Image.open(requests.get(image, stream=True).raw) images.append(im) ...
The main task is to read data, process each listing by transforming it into a structured format, and write the processed data to a file in JSON format. The `main()` function orchestrates reading input, applying transformations via `process_listing()`, and persisting results using `write_to_file()`.
def main(): listings = read_data() for listing in listings: p_listing = process_listing(listing) write_to_file(p_listing.json())
def download_calendar(url, as_table): # Download the calendar from the URL r = requests.get(url) # Parse the calendar into an ics.Calendar object calendar = Calendar(r.text) # Convert the calendar into an array events = [event for event in calendar.events] event_info = parse_to_table(events)...
The code downloads calendar events from a specified URL, converts them into a CSV file named 'assignments.csv', and prints the event data in a tabular format using the `organize_data` function.
def test(): event_info = download_calendar('https://learn.dcollege.net/webapps/calendar/calendarFeed/c2d84bf6673c402cb557f2a84ddabd87/learn.ics',True) write_as_csv('assignments.csv',event_info) # print the event_info in tabular format print(organize_data(event_info))
def get_environment(self): return self._get_env("ENVIRONMENT") def get_storage_account(self): return self._get_env("STORAGEACCOUNT") def get_dataLake_storage_type(self): return self._get_env("STORAGE") def get_automation_scope(self): return self._get_env("AUTOMATIONSCOPE") def get_re...
This method returns or prints configuration details in HTML or text format, displaying key-value pairs of environment-related parameters like storage account, Azure AD ID, and credentials. It redacts sensitive data like service credentials when printing text, and formats them in a table if HTML is requested.
def help(self, as_html=False): if as_html: return f""" <p>Configuration:</p> <table> <tr><th align='left'>Function </th><th align='left'> Value </td></tr> <tr><td>get_environment() </td><td> {self.get_environment()} </...
def get_dataLake_storage_type(self): return self._get_env("STORAGE") def get_service_principal_id(self): return self._get_dbutils_secret("DATAPLATFORMAPPID") def get_service_credential(self): return self._get_dbutils_secret("DATAPLATFORMSECRET") def get_oauth_refresh_url(self): retur...
The main task of the code is to configure Apache Spark to connect to Azure Data Lake Storage (ADLS) by setting appropriate authentication parameters based on the specified storage type (Gen1 or Gen2). It uses service principal credentials for OAuth authentication, sets refresh URLs, and validates the storage type. If t...
def connect_storage(self): _gen1 = "dfs.adls.oauth2" _gen2 = "fs.azure.account" _storageType = self.get_dataLake_storage_type() if _storageType == "AzureDataLakeGen1": self.spark.conf.set( f"{_gen1}.access.token.provider.type", "ClientCredential" ...
def generateTransmitterOutputSignal(data): channelSignal , gain = deployWirelessGain(convertToQPSK(data)) return channelSignal , gain def generateReceiverInputSignal(channelSignal , SNR): return addAWGN(channelSignal , SNR) def removeGainFromReceiverInputSignal(receivedSignal , gain): return receivedSignal / gain d...
The code simulates a QPSK communication system, transmitting data through a noisy channel with given SNR, then decoding the received signal. If showPlots is True, it visualizes transmitted vs. received signals; otherwise, it calculates and returns the bit error rate as a percentage.
def QPSK(data , SNR , showPlots=True): # Transmitter Side channelSignal , gain = generateTransmitterOutputSignal(data) # Receiver Side receivedSignal = generateReceiverInputSignal(channelSignal , SNR) receivedSignalNoGain = removeGainFromReceiverInputSignal(receivedSignal , gain) decodedSignal = generateDecodedS...
def encodeHamming(data): codeGeneratorMatrix = ["1101", "1011", "1000", "0111", "0100", "0010" , "0001"] encodedSignal = [] for i in range(0 , len(data) // 4): encoded_7bit = [] data_4bitSelected = data[i * 4 : (i + 1) * 4] for matCode in codeGeneratorMatrix: row = list(map(int , matCode)) encoded_7bit....
The main task of the code is to simulate a Hamming(7,4) error-correcting communication system. It encodes input data, transmits it through a noisy channel with specified SNR, decodes the received signal, and either visualizes transmitted/received signal points or calculates the bit error rate compared to the original d...
def Hamming7_4(data , SNR , showPlots=True): encodedSignal = encodeHamming(data) # Transmitter Side channelSignal , gain = generateTransmitterOutputSignal(encodedSignal) # Receiver Side receivedSignal = generateReceiverInputSignal(channelSignal , SNR) receivedSignalNoGain = removeGainFromReceiverInputSignal(rece...
def generateTransmitterOutputSignal(data): channelSignal , gain = deployWirelessGain(convertTo16QAM(data)) return channelSignal , gain def generateReceiverInputSignal(channelSignal , SNR): return addAWGN(channelSignal , SNR) def removeGainFromReceiverInputSignal(receivedSignal , gain): return receivedSignal / gain ...
This function simulates a 16QAM communication system, generating transmitted/received signals with given SNR. It either visualizes the I/Q constellation points (transmitted vs received) or calculates bit error rate when plotting is disabled. The core task is evaluating 16QAM performance under different SNR conditions t...
def _16QAM(data , SNR , showPlots=True): # Transmitter Side channelSignal , gain = generateTransmitterOutputSignal(data) # Receiver Side receivedSignal = generateReceiverInputSignal(channelSignal , SNR) receivedSignalNoGain = removeGainFromReceiverInputSignal(receivedSignal , gain) decodedSignal = generateDecode...
def get_instrument(instrument_name): instrument_type = 'melodic' program_number = INSTRUMENTS.get(instrument_name.lower()) if not program_number: program_number = PERCUSSION.get(instrument_name.lower()) instrument_type = 'percussion' if not program_number: raise Attribute...
This function converts musical note data to align with a specified key by transposing and scaling notes, while preserving instrument metadata. It processes non-percussion notes by mapping them to the closest MIDI values within the key's range, adjusts for octaves, and retains the original instrument header if present.
def convert_to_key(data, key, number_of_octaves=4): instrument, instrument_type = None, None if type(data[0]) != tuple: instrument = data.pop(0) _, instrument_type = get_instrument(instrument) x, y = zip(*data) if instrument_type == 'percussion': new_y = y else: # F...
def gen_neighborhood_nc(adata: anndata.AnnData, n: int, test_spots: np.array, test_spots_bool: np.array, all_spot_coords: np.array, spot_scalefactor: float) -> np.array: ''' Returns list of [x...
The function calculates and stores spatial neighborhoods for specified cell types in an `AnnData` object, considering previous computations. It filters spots by a given category and cell type, computes neighborhoods for `n` layers (noncumulative or cumulative), and adds results to `.uns['neighborhood']`. If `return_ada...
def clc_ngh(adata: anndata.AnnData, cat: str, celltype: str, n: int, noncumulative: bool=True, return_adata: bool=False, ) -> Union[anndata.AnnData,None]: ''' Calculate neighborhood of specified group of spots. Parameters: ----...
def piece_placed(self, coordinates): # print(f"{self.piece_held}\n\n\n{self.pieces_in_hand}\n\n\n{coordinates}") target_coordinates = self.make_move(self.piece_held, coordinates) if target_coordinates: self.update_coordinates(target_coordinates) show_new_piece(self.player...
This code creates a graphical user interface (GUI) for a game using tkinter. It sets up a main game board with a grid of clickable buttons, handles mouse hover events, and initializes player-specific grids to display pieces in hand. The GUI includes a titled window with a customizable layout, highlighting game areas an...
def create_gui(self): self.toplevel = tkinter.Toplevel() self.toplevel.title("game") self.toplevel.geometry('1200x1000') self.toplevel.config(bg="#3f525a") self.game_frame = tkinter.Frame(self.toplevel, highlightthickness=10, highlightbackground="#1f292d") self....
def reduce_embs_dim(x, **kwargs): x = reduce_dim(np.stack(x, -1), **kwargs)[0] x = x.transpose(2, 0, 1) return x def cluster( embs, n_clusters, method='mbkm', location_weight=None, sort=True): x, mask = prepare_for_clustering(embs, location_weight) print(f'Clustering pixels using {...
The code performs hierarchical clustering on major data, optionally reducing dimensions via PCA. It clusters major data, relabels small clusters, identifies connected components, and optionally clusters minor data sub-structures. Labels are combined hierarchically into a stacked array for multi-level clustering results...
def cluster_hierarchical( x_major, method, n_clusters, x_minor=None, min_cluster_size=None, reduce_dimension=False, location_weight=None): if reduce_dimension: x_major = reduce_embs_dim(x_major, method='pca', n_components=0.99) if x_minor is not None: x_minor = re...
def reduce_embs_dim(x, **kwargs): x = reduce_dim(np.stack(x, -1), **kwargs)[0] x = x.transpose(2, 0, 1) return x def smooth(x, filter_size): x = x.transpose(1, 2, 0) x = smoothen(x, filter_size) x = x.transpose(2, 0, 1) return x def cluster_and_save( x, method, n_clusters, min_cluste...
This function preprocesses embeddings by reducing dimensionality (via PCA if specified) and smoothing (if specified), then clusters the data using multiple cluster counts (default: 10-70) with the given method (e.g., k-means). It returns a list of cluster labels for each configuration.
def preprocess_and_cluster( x, prefix=None, n_components=None, filter_size=None, n_clusters=None, min_cluster_size=None, method='km'): if n_components is not None: x = reduce_embs_dim(x, method='pca', n_components=n_components) if filter_size is not None: t0 = t...