dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def conv(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0): with tf.variable_scope(name): l2_regularizer = lambda t: l2_loss(t, weight=weight_decay) kernel = tf.get_variable("weights", [kH, kW, nIn, nOut], initi...
This code defines an Inception-ResNet V1 model for face recognition, processing input images through convolutional, pooling, and inception modules with batch normalization. It returns facial feature embeddings and intermediate network outputs for tasks like identity verification or classification.
def inference(images, keep_probability, phase_train=True, weight_decay=0.0, bottleneck_layer_size=128,reuse=False): """ Define an inference network for face recognition based on inception modules using batch normalization Args: images: The images to run inference on, dimensions batch_size...
def conv(inpOp, nIn, nOut, kH, kW, dH, dW, padType, name, phase_train=True, use_batch_norm=True, weight_decay=0.0): with tf.variable_scope(name): l2_regularizer = lambda t: l2_loss(t, weight=weight_decay) kernel = tf.get_variable("weights", [kH, kW, nIn, nOut], initi...
The code defines a face recognition inference network using Inception-ResNet architecture with batch normalization. It processes real and synthetic images separately through convolutional and pooling layers, then merges them. The network employs inception modules for feature extraction, culminating in a bottleneck laye...
def inference2(images, images_syn, keep_probability, phase_train=True, weight_decay=0.0, bottleneck_layer_size=128, reuse=False): """ Define an inference network for face recognition based on inception modules using batch normalization Args: images: The images to run inference on...
def plotVisual(allImgData, output, foldername): # Determines number of plots / frames. Creates multiple static plots if # animation disabled, or 1 plot with many frames if animation enabled. numPlots = len(allImgData) if output["plotAnimate"]: numPlots, numFrames = 1, numPlots for i i...
The main task of the code is to conditionally execute plotting and data analysis functions based on flags in the `output` dictionary. It triggers `plotVisual`, `plotDistribution`, `plotButterfly`, and `printDataTable`/`exportCSV` functions if their corresponding boolean values in `output` are `True`, using `allImgData`...
def main(allImgData, output, foldername): if output["plotVisual"]: plotVisual(allImgData, output, foldername) if output["plotAreaDistribution"]: plotDistribution(allImgData, foldername, distType="area") if output["plotLatDistribution"]: plotDistribution(allImgData,...
def _open_genome_file(refGen): global fusion_genes global genome_open fusion_genes = [] # Ask the user to manually select a reference file #file = filedialog.askopenfilename(filetypes=(("gtf files", "*.gtf"), ("All files", "*.*"))) file = "Genomes/Homo_sapiens.GRCh38.100.gtf" if file: ...
The code creates a GUI application for genomic data analysis, enabling users to load BAM files, select reference genomes, and customize themes. It provides interactive views for chromosomes, gene fusions, and summaries, with features like gene/position search, chromosome selection, and drag-and-drop sequence navigation...
def main(): # Allow the window variables to be accessible outside of the main function (for theme changes, text population, etc.) global win global frame1 global frame2 global frame3 global frameChr global frmChrGen global frameRef global fusion_area global chrom_area global ...
def _connect_db(self): """ Establish read-only database connection """ assert self.db is None, 'A connection has already been opened.' self.db = lmdb.open( self.processed_path, map_size=10*(1024*1024*1024), # 10GB create=False, ...
The main task of the code is to retrieve protein-ligand data from a database using an index, ensure the data contains affinity information, and return it as a structured `ProteinLigandData` object with validation.
def get_ori_data(self, idx): if self.db is None: self._connect_db() key = self.keys[idx] data = pickle.loads(self.db.begin().get(key)) if 'affinity' not in data: self._load_affinity_info() self._inject_affinity(key, data['ligand_filename']) ...
def build_sharetypo_edge(self): def share_typos(c1, c2): for e_c1 in c1: for e_c2 in c2: if dist(e_c1.word, e_c2.word) <= self.k: return True return False for outer_index, out_cluster in enumerate(self.nodes_list): ...
The code initializes a clustering model by constructing nodes from word frequencies, building shared-typo edges between nodes, calculating fidelity and stability scores, and performing clustering using a weighted objective function. It balances cluster quality via gamma, with clustering executed if gamma ≠ 1. The main ...
def __init__(self, word_frequency_map, gamma, k): self.nodes_list = [] self.word_frequency_map = word_frequency_map self.sum_freq = 0 self.gamma = gamma self.ignore_indices = [] self.k = k print("K = ", self.k) # Cost N for x in word_frequency_map...
def initialize(self): self.billingObj=database.connectData() self.totalItems=0 self.totalPrice=0.0 self.customerCount=0 self.CartItemsDic={} self.parserControl=ConfigParser() self.parserControl.read("settings.ini") def billingInput(self): self.get...
This code initializes a GUI component by creating a frame, applying styles, setting up UI elements, handling billing input and display, and configuring keyboard bindings for a billing management application.
def __init__(self,main): self.master=Frame(main) self.master.grid(row=0,column=0,sticky=NSEW) stylesheet().getTreeview() self.initialize() self.billingInput() self.billingList() self.keyBindings()
def file_lines_to_list(filename): with open(filename) as file: return [line.rstrip() for line in file] def get_list_include_keywords(list, *keywords): result = [] for line in list: for keyword in keywords: if keyword in line: result.append(line.strip()) return...
The code generates airgap resources by executing a script for each job and architecture, collecting file/image URLs based on keywords, combining results, deduplicating lists, and generating airgap packages. It processes parameters, runs shell commands, filters outputs, and handles full-mode requirements for additional ...
def batch_gen_airgap_resources(jobs_params): other_required_list = {key: [] for key in ['file_list', 'image_list']} list_data = {key: [] for key in ['file_list', 'image_list']} is_executed = False for arch in jobs_params.get('arch', []): for job in jobs_params.get('jobs',[]): extra_v...
def getCollections(profileName): collectionsData = { 'collections': {} } # Web frontend is expecting the above to be structured as: # 'collections': { # 'collection_id': { # 'icon': 'string', # 'items': [{},{},{}] # } # } data = deserialize(g...
The function `getAll` aggregates user profile data by compiling information from multiple sub-functions into a unified dictionary. It retrieves profile details like picture, name, location, icons, collections, recent activity, last addition, and friends, then returns them as a structured `allData` dictionary for a give...
def getAll(profileName): allData = { 'picture': '', 'fullName': '', 'location': '', 'icons': [], 'collections': getCollections(profileName)['collections'], 'recentActivity': getRecent(profileName), 'lastAddition': getLastAdded(profileName)['lastAddition'], ...
def getAll(profileName): allData = { 'picture': '', 'fullName': '', 'location': '', 'icons': [], 'collections': getCollections(profileName)['collections'], 'recentActivity': getRecent(profileName), 'lastAddition': getLastAdded(profileName)['lastAddition'], ...
This code handles API requests by extracting user profile data based on query parameters. It retrieves specified data (e.g., profile info, collections) using functions mapped to request types, then returns the result in JSON format with CORS headers.
def handler(event, context): print("event") print(event) profileName = event['queryStringParameters']['uid'] request = event['queryStringParameters']['request'] calls = { 'all': getAll(profileName), 'profile': getProfile(profileName), 'collections': getCollections(profil...
def parse_dirs(self): self.bydirs = self.__get_parser_dirs(self.basedir,[self.basedir]) def printdebug(self,string): try: if os.environ['DEBUG']: print("[DEBUG]"+string) except: return def parse_groups(self): """Parses groups and filters the ones t...
The code initializes an object by parsing directories and groups, mapping directories to groups and vice versa, then checking permissions. It logs intermediate states of directory-group mappings for debugging.
def __init__(self): self.parse_dirs() self.printdebug('self.bydirs at the beggining '+self.bydirs.__str__()) self.parse_groups() self.printdebug('self.bygroups at the beggining '+self.bygroups.__str__()) self.dirtogroup() self.printdebug('self.bygroups after dirtogroup() ...
def get_state_dependency(self,state): if type(state) in (range,list): state=list(state) state = ",".join([str(x) for x in state ]) return pd.read_sql_query(""" select distinct (a.state_id-(select max(state_id)+1 from state s))*-1 as state,substr(c.command,33) com...
This function generates and aggregates unique recipes for a specified column by analyzing state dependencies, constructing a parallel workflow, and extracting operations from database records. It processes dependencies, builds a graph, identifies relevant states, and compiles distinct recipe operations for return.
def reuse_recipe(self,col_id): state_dep = self.get_state_dependency(self.get_column_dependency(col_id).state.tolist()) #print(",".join([str(x) for x in state_dep.dep_state.unique()])) parallel_workflow = self.parallel_workflow() _,parallel_graph,_ = self.gv_template(parallel_wor...
def get_col_logic_to_idx(self,state,col): col_logic = self.get_col_at_state_order(state) #print(col_logic) return col_logic.iloc[col].col_id def get_row_logic_to_idx(self,state,row): row_logic = self.get_row_at_state_order(state) return row_logic.iloc[row].row_id def get_column_d...
The code generates a visual lineage of data transformations by tracing dependencies between states for specified columns and rows. It processes historical cell data, constructs a workflow visualization with states and data flows, and returns a WorkflowViz object representing the lineage of changes across states.
def lineage_viz(self,row,col,step=-1): if step>-1: #col = self.get_col_logic_to_idx(self.get_step_to_state(step),col) #row = self.get_row_logic_to_idx(self.get_step_to_state(step),row) col = self.get_col_logic_to_idx(step,col) row = self.get_row_logic_to_idx(step,...
def get_col_logic_to_idx(self,state,col): col_logic = self.get_col_at_state_order(state) #print(col_logic) return col_logic.iloc[col].col_id def get_row_logic_to_idx(self,state,row): row_logic = self.get_row_at_state_order(state) return row_logic.iloc[row].row_id def get_column_d...
The function `get_cell_lineage` traces the lineage of a cell's data across different states by analyzing dependencies between columns and rows. It processes historical cell data, filters relevant dependencies, and constructs a visual graph using Graphviz to represent transitions between states. The output includes a tr...
def get_cell_lineage(self,row,col,step=-1): if step>-1: #col = self.get_col_logic_to_idx(self.get_step_to_state(step),col) #row = self.get_row_logic_to_idx(self.get_step_to_state(step),row) col = self.get_col_logic_to_idx(step,col) row = self.get_row_logic_to_idx(...
def _drawCircle(self, **params): """ Draws a circle according to params :param params: style and other parameters from the circle tag :return: None """ cx = self._convertToPixels(params['cx']) cy = self._convertToPixels(params['cy']) r = self._convertToPix...
The code renders SVG elements into a PNG image by processing each element's attributes and styles, calling corresponding drawing methods for shapes like circles, lines, and paths, then saving the final image with the specified filename.
def render(self, name): """ Renders the png file :param name: name of the exported png :return: None """ if self.height is None or self.width is None or self.units is None: return None for element in self.elements: elementName = element.tag...
def loadvideo_decord(self, sample, sample_rate_scale=1): """ load images by cv2 if mode == 'test', we return a whole list, it will be selected by chunk_nb, split_nb in __getitem__; otherwise, we select 'num_segment' list segment, other images in list will be discarded """ ...
This code implements a custom dataset loader for video data, handling training, validation, and testing modes. It loads video clips, applies transformations (resizing, cropping, flipping, normalization), and returns processed tensors with labels. Training includes random augmentations, validation uses center cropping, ...
def __getitem__(self, index): if self.mode == 'train': scale_t = 1 sample = self.dataset_samples[index] buffer = self.loadvideo_decord(sample, sample_rate_scale=scale_t) if not buffer.any(): while not buffer.any(): warnings.war...
def generate_images_for_pipeline(generator, number_of_runthroughs_param): """ This method generates number_of_runthroughs images and saves them in the output folder :param generator: generator that has to be used :param number_of_runthroughs_param: number of images to generate :return: list of image...
The code defines a pipeline function that generates images using a specified generator, processes them with multiple processors (split by '/'), and evaluates each processing step using an evaluator. It runs the generator for a given number of iterations, applies each processor sequentially to the generated content, and...
def pipeline(generator: str, processor: str, evaluator: str, number_of_runthroughs: Optional[int] = typer.Argument(default=1)): content = generate_images_for_pipeline(generator, number_of_runthroughs) processors = processor.split("/") for current_processor in processors: process_for_pi...
def updateErrors(self): removedConflicts = self.previousConflictNumbers - self.conflicts()[0] for removeError in removedConflicts: self.ui.IDs["SudokuTextBox" + str(removeError) + "_"].textcol = (0, 0, 0) self.ui.IDs["SudokuTextBox" + str(removeError) + "_"].refresh() sel...
This code handles error checking logic based on user selection from a dropdown. It updates/clears errors, manages UI elements like the "ShowErrors" button, and toggles conflict highlighting. The function enables/disables error checks, clears previous conflicts, and adjusts visual feedback depending on the selected mode...
def errorCheckingLogic(self): errorChecking = self.ui.IDs['SettingsDropdown'].active if errorChecking == "Check Button": self.updateErrors() self.clearConflictNotes() if not(self.renderingErrorCheckButton): self.ui.IDs["ShowErrors"].enabled = True ...
def displayHint(self): hint, solvable = self.hint() if solvable: self.ui.IDs["SudokuTextBox" + str(hint) + "_"].col = (0,255,0) self.ui.IDs["SudokuTextBox" + str(hint) + "_"].refresh() self.currentHint = hint else: notSolvable = self.ui.maketext(0,...
This method creates three UI buttons for a Sudoku game: "Hint" to display hints, "Solve" to solve the puzzle, and "Errors" to highlight conflicts. The "Errors" button is initially disabled. Each button is positioned, sized, and linked to specific functions via lambda callbacks.
def makeAdditionalButtons(self): self.ui.makebutton(10, 60, width=130, ID="ShowHint", text="Hint", menu="SudokuGame", command=lambda: self.displayHint()) self.ui.makebutton(10, 110, width = 130, ID="SolveBoard", text="Solve", menu="SudokuGame", command=lambda: self.displaySolve()) self.ui.makebu...
def makeTable(self): def datavalidation(textID, Tile:SudokuTile): # Stops the hint tile being green if self.currentHint != None: self.ui.IDs["SudokuTextBox" + str(self.currentHint) + "_"].col = pyui.Style.defaults['col'] self.ui.IDs["SudokuTextBox" + str(...
This code initializes a puzzle game (likely Sudoku) by setting up the game board, UI components, menus, buttons, and level data. It configures parameters like board dimensions, valid characters, time tracking, and loads predefined levels. The main task is to prepare the game environment, including rendering elements, c...
def __init__(self, ui: pyui.UI, levelNumber:int, boxWidth=3, boxHeight=3, boxesX=3, boxesY=3, validChars=[str(x) for x in range(1,10)]): self.levelNumber = levelNumber self.board = [] self.prevTime = time.time() self.boxWidth = boxWidth self.boxHeight = boxHeight self.box...
def run(graph: nx.Graph) -> None: global _progress memo = {} draw_and_save_graph(graph) _progress['start_time'] = time.perf_counter() # Using the CanonicalEdges directly with the graph object now. canonical_edge_list = CanonicalEdges(graph).calc() net_score = _net_score(graph=graph, dep...
The code parses command-line arguments to generate specific graph types (e.g., complete, wheel, friendship) using NetworkX or custom functions. It validates required parameters, constructs the graph, and executes a `run` function on it. The task involves creating predefined or user-specified graphs and solving a game-r...
def main(): sys.setrecursionlimit(10000) parser = argparse.ArgumentParser(description='Solve a game.') parser.add_argument( '--type', default='file', type=str, help='Edge source type name (defaults to "file").' ) parser.add_argument( '--nodes', type=in...
def parse_data(file_name): """ Parses data file and stores people and there preferences """ people = [] file = open(file_name) for line in file: # Strips '\n' from each line line = line[:-1] name = line.split("|")[0] preferences = line.split("|")[1].split(", ") ...
The main task of the code is to generate an optimal shift schedule by assigning people to tasks using a max flow algorithm. It reads input data, creates a graph for each shift, applies Ford-Fulkerson for maximum flow, resolves flow issues, and assigns tasks while tracking preference conflicts. Finally, it prints each p...
def create_schedule(): input_file_name = "input.txt" # TODO Add person data for every shift people = parse_data(input_file_name) tasks = [{"bar1" : 3, "bar2" : 1, "keuken" : 0, "gardarobe" : 3, "bekers" : 2, "deur" : 1}, {"bar1" : 3, "bar2" : 1, "keuken" : 1, "gardarobe" : 2, "bekers" : 2,...
def user_id_to_user(**kwargs): """ db_session user """ db_session = kwargs["db_session"] user = kwargs.get("user") if isinstance(user, User): return user if isinstance(user, int): assert_id(user) return get_user_by_id( db_session=db_session, ...
The function updates a user's password by retrieving the user and password from arguments, validating the password, sending a password change email (ignoring delivery errors), generating a new salt, encrypting the password with the salt, and committing the changes to the database.
def update_user_password(**kwargs): """ db_session user password """ db_session = kwargs["db_session"] user = user_id_to_user( db_session=db_session, user=kwargs.get("user") ) password = kwargs.get("password") assert_password(password) try: send_email...
def generate_real_sample(dataset, n_sample): X, labels = dataset idx = np.random.randint(0, len(X), n_sample) X, labels = X[idx], labels[idx] X.reshape(-1,X.shape[1], 1) y = np.ones((n_sample, 1)) return [X, labels.astype(np.float16)], y.astype(np.float16) def generate_fake_sample(generator, l...
The code trains a GAN (Generator-Discriminator-Classifier) model using a dataset, alternating between updating the discriminator with real/fake samples and training the generator via the GAN model. It iterates over batches for multiple epochs, logging losses and periodically evaluating performance. The classifier is tr...
def train(g_model, d_model, c_model, gan_model, dataset, latent_size, n_epochs=20, n_batch=100): # X_sup, y_sup = select_supervised_sample(dataset) X_sup, y_sup = dataset print(X_sup.shape, y_sup.shape) bat_per_epo = len(dataset[0])//n_batch n_step = int(bat_per_epo * n_epochs) half_batch = int(...
def load_and_process_data_local() -> pd.DataFrame: """Load data from local storage page per page and compute transaction statistics per country from them""" input_datasets = sorted(os.listdir(os.path.join(os.curdir, "Data"))) for page, input_file in enumerate(input_datasets): response = retrieve_da...
The main task of the code is to process transaction data from either a local source or a REST API, aggregate it by country, and save the results based on the specified output type. It loads data using the appropriate method, performs aggregation, and stores the final country-wise transaction summary.
def main(args: argparse.Namespace) -> None: input_type = args.input_type output_type = args.output_type if input_type == "local": transactions_per_country = load_and_process_data_local() elif input_type == "rest-api": transactions_per_country = load_and_process_data_rest_ap...
def id2subtype(id): subtype_re = re.search("\/([cC][aA][sS][\w\-]+)$" , id) if subtype_re is not None: subtype = subtype_re.groups()[0] return subtype else: return None def get_clade_ids(clades_list): clade_seqs = {} seq2clade = {} with open(clades_list) as ifh: f...
The function `learn_phylogenetic_tree` processes input sequences to analyze and compare phylogenetic clades. It extracts subtypes from FASTA headers, constructs clade alignments, generates HHSuite profiles, and evaluates clade scores against outgroups. Results are compiled into JSON, highlighting alignment scores for e...
def learn_phylogenetic_tree(work_directory, input_fasta, clades_file): eu.BasicUtils.make_path(work_directory) ## first pass to select subtypes subtypes = () with open(input_fasta, "r") as ofh: subtypes = {id2subtype(record.id) for record in SeqIO.parse(input_fasta, "fasta")} ## Get seque...
def check_nuclease_essential_parts(protein_seq, db_name): hmm_res = hu.run_single_sequence(protein_seq, db_name) [nuclease_score, ruvc_score, hnh_score] = analyze_scores_of_nuclease(hmm_res) has_correct_start = test_if_cas9_has_correct_start(hmm_res) return [has_correct_start, nuclease_score, ruvc_score...
This function analyzes a protein sequence to determine if it's a nuclease (e.g., Cas9) by evaluating scores from a database. It checks for essential nuclease domains (RUVC, HNH), corrects sequence issues if detected, re-analyzes scores after fixes, and returns a dictionary with nuclease scores, classification, sequence...
def get_nuclease_composition_info(protein_seq, db, fasta_file, start_pos, end_pos, strand): [has_correct_start, nuclease_score, ruvc_score, hnh_score] = check_nuclease_essential_parts(protein_seq, db) is_nuclease = ruvc_score > ruvc_min_score and hnh_score > hnh_min_score was_fixed = False if is_nuclea...
def get_profiles_list(hmm_folder): profiles_list = glob.glob('{}/*.HMM'.format(hmm_folder)) + glob.glob('{}/*.hmm'.format(hmm_folder)) return profiles_list def run_single_hmm_profile(proteins_fasta, hmm_profile, hmm_output_file, log_file): with open(log_file, 'a') as hmmer_log: hmm_cmd = ['hmmsearch...
The function runs multiple HMM profiles against a protein FASTA file, generating individual HMMER results for each profile in a specified directory. It aggregates these results into a single TSV file and returns the aggregated output. Key steps include creating result directories, executing each HMM profile, logging ou...
def run_all_profiles_in_directory(hmm_folder, proteins_fasta, work_dir): profiles_list = get_profiles_list(hmm_folder) hmm_results_folder = '{}/hmmer'.format(work_dir) os.mkdir(hmm_results_folder) log_file = "{}/hmmer.log".format(work_dir) for hmm_profile in profiles_list: hmm_out = hmm_prof...
def is_train_test_file_exists(self) -> bool: try: logging.info(f"Checking if train and test dataset file are available") is_train_file_exist = False is_test_file_exist = False train_file_path = self.data_ingestion_artifact.train_file_path test_file_pa...
The main task of the code is to perform data validation by checking the existence of train/test files, validating the dataset schema, and detecting data drift. If successful, it creates and returns a `DataValidationArtifact` with file paths and validation status. If any step fails, it raises an exception.
def initiate_data_validation(self) -> DataValidationArtifact: try: self.is_train_test_file_exists() self.validate_dataset_schema() self.is_data_drift_found() data_validation_artifact = DataValidationArtifact( schema_file_path = self.data_validatio...
def heuristic(piece_at_grid): user_pieces = [] cpu_pieces = [] user_king = None cpu_king = None winner = None for raw in piece_at_grid: for p in raw: if type(p) == King and p.team == "user": user_king = p elif type(p) == King and p.team == "cpu": ...
This function implements a minimax algorithm with alpha-beta pruning for a game, evaluating the best move for the current player (CPU or user) up to a specified depth. It recursively explores legal moves, applies heuristic evaluation at depth 3, and tracks the optimal move while pruning suboptimal branches to improve e...
def N_ply_look_ahead(depth, piece_at_grid, turn, alpha, beta): if depth >= 3: return heuristic(piece_at_grid), [] best_move = [] winner = None brune = False if turn == "cpu": max_eval = -1000 for raw in piece_at_grid: if brune : break for piece in raw: ...
def transform_dis(df): df_dis_fil = filter_columns(df) df_dis_fil = filter_title(df_dis_fil, nat_dis_categories) df_dis_fil = filter_coord( df_dis_fil, lat_aus_min, lat_aus_max, lon_aus_min, lon_aus_max ) df_dis_col = rename_columns(df_dis_fil) df_dis_col = create_date_column(df_dis_col)...
The main task of the code is to perform an ETL (Extract, Transform, Load) process: loading raw data from an S3 bronze bucket using Spark, transforming it via dedicated functions, and writing the processed datasets into Delta Lake format in an S3 silver bucket. The process includes saving a bookmark for reprocessing, en...
def main(): # Load the raw data from S3 bronze bucket logger.info("Loading raw data from S3 bronze bucket...") df_dis_bronze = spark.read.format("delta").load(f"{s3_input_path}df_dis_bronze") df_glo_bronze = spark.read.format("delta").load(f"{s3_input_path}df_glo_bronze") df_ano_bronze = spark.read....
def check_collision(bullets, settings, aliens): if pygame.sprite.groupcollide(bullets, aliens, True, True): settings.score +=1 def limit_bullets(bullets): for bullet in bullets: if bullet.rect.bottom < 0: bullets.remove(bullet) def player_death(settings, screen, aliens, ship): if...
This function updates the game screen by drawing the background, managing game states (active/inactive), rendering game elements (ship, aliens, bullets), handling collisions, limiting bullets, updating positions, displaying scores, enforcing boundaries, and checking for new waves or game over conditions. It ensures rea...
def update_screen(settings, screen, ship, bullets, alien, aliens, play_button): # draws background screen.fill(settings.bg_color) # updates button if not settings.game_active: play_button.draw_button() elif settings.game_active: # draw fleet of aliens aliens.draw(screen) ...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateZip(self, name="zip1", *files): if not files: files = [("zp1", "content1"), ("zp2", "content2")] ...
The test verifies that an incremental update correctly updates only the changed file (ip2) while leaving unchanged files (ip1) intact, despite differing content but matching checksums, ensuring the installer handles selective updates accurately.
def testUploadWithOneChangedFile(self): # Existing manifest from a previous install. self._CreateRemoteManifest( "zip1 zp1 ip1 0", "zip1 zp2 ip2 1") # Existing files from a previous install. self._PutDeviceFile("dex/ip1", "old content1") self._PutDeviceFile("dex/ip2", "old content2...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateZip(self, name="zip1", *files): if not files: files = [("zp1", "content1"), ("zp2", "content2")] ...
This test verifies that a full upload correctly updates files on a device even when their checksums match but contents differ. It sets up remote and local manifests with version differences, simulates device files with old content, creates a zip, and triggers a non-incremental install. Finally, it checks that both file...
def testFullUploadWithOneChangedFile(self): # Existing manifest from a previous install. self._CreateRemoteManifest( "zip1 zp1 ip1 0", "zip1 zp2 ip2 1") self._PutDeviceFile("dex/ip1", "old content1") self._PutDeviceFile("dex/ip2", "old content2") self._PutDeviceFile("install_timest...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateLocalManifest(self, *lines): content = "\n".join(lines) with open(self._DEXMANIFEST, "w") as f: ...
This test verifies an incremental upload process by creating remote/local manifests, uploading files, generating a zip, and checking if incremental installation correctly updates device files with expected content ("content1" for existing and "content2" for new files).
def testUploadWithNewFile(self): self._CreateRemoteManifest("zip1 zp1 ip1 0") self._PutDeviceFile("dex/ip1", "content1") self._PutDeviceFile("install_timestamp", "0") self._mock_adb.package_timestamp = "0" self._CreateLocalManifest( "zip1 zp1 ip1 0", "zip1 zp2 ip2 1") self._Cr...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateZip(self, name="zip1", *files): if not files: files = [("zp1", "content1"), ("zp2", "content2")] ...
This test verifies that an incremental update correctly deletes the old version's dex file from the device. It sets up a test environment with two versions of an app, performs an incremental install, and checks if the outdated "dex/ip2" file is removed from the mocked ADB file system, ensuring proper cleanup during upd...
def testDeletesFile(self): self._CreateRemoteManifest( "zip1 zp1 ip1 0", "zip1 zip2 ip2 1") self._PutDeviceFile("dex/ip1", "content1") self._PutDeviceFile("dex/ip2", "content2") self._PutDeviceFile("install_timestamp", "0") self._mock_adb.package_timestamp = "0" self._CreateZip...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateZip(self, name="zip1", *files): if not files: files = [("zp1", "content1"), ("zp2", "content2")] ...
This test verifies that an incremental install does not update any files when the local and remote manifests are identical, ensuring existing device files remain unchanged. It sets up device files, creates matching manifests, performs an incremental install, and checks that all original file contents persist, confirmin...
def testNothingToUpdate(self): self._CreateRemoteManifest( "zip1 zp1 ip1 0", "zip1 zip2 ip2 1", "dex1 - ip3 0") self._PutDeviceFile("dex/ip1", "content1") self._PutDeviceFile("dex/ip2", "content2") self._PutDeviceFile("dex/ip3", "content3") self._PutDeviceFile("install_timest...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateZip(self, name="zip1", *files): if not files: files = [("zp1", "content1"), ("zp2", "content2")] ...
This test verifies that the resources file is not updated during an incremental install when the local and device checksums match. It sets up device files with specific checksums and timestamps, performs an incremental install, and checks that the resources.ap_ file remains unchanged, confirming no unnecessary updates ...
def testNoResourcesToUpdate(self): self._CreateRemoteManifest("zip1 zp1 ip1 0") self._PutDeviceFile("dex/ip1", "content1") # The local file is actually "resource apk", but the checksum on the device # for the resources file is set to be the same as the checksum for the # local file so that we can co...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateZip(self, name="zip1", *files): if not files: files = [("zp1", "content1"), ("zp2", "content2")] ...
This test verifies that incremental installation correctly updates resources by setting up a mock environment with specific files, creating a zip archive, and checking if the expected 'resources.ap_' file is properly installed and matches the expected content after the process.
def testUpdateResources(self): self._CreateRemoteManifest("zip1 zp1 ip1 0") self._PutDeviceFile("dex/ip1", "content1") self._PutDeviceFile("resources.ap_", "resources") self._PutDeviceFile("resources_checksum", "checksum") self._PutDeviceFile("install_timestamp", "0") self._mock_adb.package_time...
def _CreateRemoteManifest(self, *lines): self._PutDeviceFile("dex/manifest", "\n".join(lines)) def _PutDeviceFile(self, f, content): self._mock_adb.files[self._GetDeviceAppPath(f)] = content def _CreateZip(self, name="zip1", *files): if not files: files = [("zp1", "content1"), ("zp2", "content2")] ...
This test verifies that the incremental install process correctly exits with an error when encountering a mismatched install timestamp. It sets up a scenario with predefined manifests, device files, and a mock timestamp, then triggers an incremental install expecting a SystemExit exception to ensure proper validation o...
def testIncrementalInstallWithWrongInstallTimestamp(self): self._CreateRemoteManifest( "zip1 zp1 ip1 0", "zip1 zip2 ip2 1", "dex1 - ip3 0") self._PutDeviceFile("dex/ip1", "content1") self._PutDeviceFile("dex/ip2", "content2") self._PutDeviceFile("dex/ip3", "content3") self._m...
def allBooks(): cursor = connection.cursor() book_list = getbooks() allBooks_dict = {} for book in book_list: cursor.execute("SELECT * FROM books_book WHERE name=%s",[book]) book_data = dictfetchall(cursor) for item in book_data: name=item['name'] allBooks...
This function handles adding new book data by processing POST requests, validating author and genre forms, checking for existing entries, and inserting new records into the database while avoiding duplicates. It uses Django forms and raw SQL queries to manage authors, genres, and books, ensuring data integrity and redi...
def addData(request): cursor = connection.cursor() book_names = allBooks() allAuthors = getauthors() allTypes = getgenre() count = len(book_names) if request.method == "POST": af = AuthorForm(request.POST) if af.is_valid(): auth_name = af.cleaned_data['aname'] ...
def isTrendDown(self, testData = []): res = np.all(np.diff(self.moving_average(np.array(testData), n=len(testData)-1))<0) resTwo = np.all(np.diff(self.moving_average(np.array(testData[60:]), n=len(testData[60:])-1))<0) return res and resTwo def initiateTrading(self, trade_type, tradePair, dat...
This function processes an Excel file for a specific trading pair, analyzes historical price trends, and initiates trades. It reads adjusted close prices, tracks movements in 120-period windows, detects upward/downward trends, and triggers 'call', 'put', or 'med' trades via initiateTrading() based on trend consistency....
def read_work_book(self, pair): print("Doing a custom strategy for %s"%(pair)) pair = pair.replace('/','_').replace("=X", "") self.from_main.write_log(pair, "Doing a custom strategy for %s"%(pair)) if pair not in self.from_main.keysToList(self.from_main.tradingHistory): ...
def readInput(file): # Take in n of grid. n = int(file.readline()) # Create grid of n width and fill it from input file. grid = [] for i in range(n): a = [] for j in range(n): x = int(file.read(1)) if x == CLUELESS_WALL: cell = Cell(i, j, x, 0...
The code reads a maze configuration from a file, checks its solvability, and uses a stack-based algorithm to solve it visually via Pygame. It initializes the grid, draws the maze, and either completes the puzzle or reports unsolvability, with a loop handling window events for closure.
def main(): path = "tests/" + input("file name: ") file = open(path, "r") setup = readInput(file) n = setup[0] grid = setup[1] width = BLOCK_SIZE*n stack = [] clock = pygame.time.Clock() drawInitial(width, grid) if checkAllWalls(grid, n) == False: print("Puzzle not s...
def init_sub_pub(): """ Initlialises all ROS publishers and subscribers used for the project. """ # Initialise node with any node name rospy.init_node('robot_controller') global pub global desired_pose_pub global gripper_pub # Create publisher pub = rospy.Publisher( 'des...
This code controls a robotic arm to detect, pick up, identify colored cubes, and drop them at designated points using a state machine. It initializes variables, monitors cube movement, selects valid cubes, checks colors, and executes precise movements for pickup and drop-off. The system transitions between states (pred...
def main(): # initialise nodes and gripper init_sub_pub() init_global_vars() # global variables used in main global current_joint_angles # array of current angles in radians global desired_joint_angles # array of desired angles in radians global cubes # dictionary...
def _authenticate(self): self._authenticate_token() def to_json_response(self, response): body = json.dumps(response.data) return self.respond(status=200, body=body, mimetype="application/json") def respond(self, status, body, mimetype="text/html"): return Response(status=status, respons...
This code handles HTTP requests by authenticating, routing the request to the appropriate method, processing it, and returning JSON responses. It catches exceptions to return specific HTTP error codes: 400 for invalid input, 403 for unauthorized access, 404 for missing endpoints, and 500 for internal errors.
def dispatch_request(self, **kwargs): try: self._authenticate() endpoint = getattr(self, request.method.lower()) response = endpoint(request, **kwargs) response = self.to_json_response(response) except (TypeError, ValueError): response = self.r...
def DOG_filters(sigma, kernel_size, no_of_orient, sobel_vertical): dog_filters = [] orientations = np.linspace(0,360,no_of_orient) #define orientations for x in sigma: gauss_kernel = GaussianFilter2d(x, kernel_size) sobel_convolve = convolve2d(gauss_kernel, sobel_vertical) for i in range(0...
The main task of the code is to generate multiple filter banks (DoG, LM, Gabor, and half-disk masks), apply them to images to produce texton, brightness, and color maps, compute gradients using Chi-square, and compare edge detection methods (Canny, Sobel, PbLite). It processes 10 images, saving filter banks, maps, grad...
def main(): """ Generate Difference of Gaussian Filter Bank: (DoG) Display all the filters in this filter bank and save image as DoG.png, use command "cv2.imwrite(...)" """ sobel_vertical = np.array([[-1, 0, 1], [-4, 0, 4], [-1, 0, 1]]) sigma1 = [3,5] kernel_size = 49 orientations1 = 16 dog_f...
def reset_deque(self, state): # Reset deque filled with the initial state and action 'NOOP'. state_deque = deque(maxlen=self.num_sequences) action_deque = deque(maxlen=self.num_sequences-1) for _ in range(self.num_sequences-1): state_deque.append( np.zeros(se...
The code trains a reinforcement learning agent in an environment by collecting experiences (actions, rewards, states) in a memory buffer. It alternates between exploration (random actions initially, then guided exploration) and learning phases, updating the agent's policy and latent network. The episode tracks cumulati...
def train_episode(self): self.episodes += 1 episode_return = 0. episode_steps = 0 done = False state = self.env.reset() self.memory.reset_episode(state) state_deque, action_deque = self.reset_deque(state) while (not done) and episode_steps <= self.max_ep...
def add_env_variables(env_variable): # Get token and channel ID from env variables. if os.environ.get(env_variable) is not None: return os.environ[env_variable] else: raise Exception(f"Environment variable {env_variable} not defined.") def on_activate_print_wo(bot, special_hotkeys, timing): ...
The main task of the code is to run a Discord bot that listens for keyboard hotkeys to capture and send screenshots (with/without UI) to a specified channel. It loads configuration data from a pickle file, retrieves environment variables for authentication, initializes the bot, sets up hotkey handlers, and starts the b...
def run_defiasmessengerbot(): with open(get_data_path(), "rb") as f: data = pickle.load(f) # Get env variables: token = add_env_variables('DEFIASMESSENGERBOT_TOKEN') channel_id = int(add_env_variables('DEFIASMESSENGERBOT_CHANNELID')) # Get configs from pickle file path = data["path"] ...
def loss_curlB(self, domain_data): p, q, r = tf.split(self.curlB(*domain_data), 3, axis=-1) mod_curl2 = p**2 + q**2 + r**2 mod_curl = tf.sqrt(mod_curl2) return (self.rho**2 / 2.0) * tf.reduce_mean(mod_curl2) + tf.reduce_mean(mod_curl * self.lam(*domain_data)) def total_loss_b(self, bo...
This function performs a training step for a neural network by computing gradients of a combined loss function, which includes energy, boundary, and curl losses. It uses TensorFlow's GradientTape to track operations, calculates gradients of the total loss (weighted sum of individual losses) with respect to model parame...
def train_step_main(self, optimizer, domain_data, boundary_data): with tf.GradientTape() as tape: curl_loss = self.loss_curlB(domain_data) bdry_loss = self.total_loss_b(boundary_data) engy_loss = self.loss_energy(domain_data) loss = engy_loss + 100.*bdry_loss + cu...
def plot_solution(self, resolution, save_dir, index): #self.A.load_weights('{}/{}'.format(save_dir, self.A.name)).expect_partial() fig = plt.figure(figsize=(16, 16)) ax_B = fig.add_subplot(111, projection='3d') x, y, z = self.domain.grid_sample(resolution) grid = (resoluti...
The code trains a physics-informed neural network (PINN) to solve partial differential equations (PDEs) by minimizing multiple loss components: divergence, curl, boundary conditions, energy, and a multiplier term. It iteratively updates model weights using specified optimizers, logs training metrics (losses and runtime...
def learn(self, optimizers, epochs, n_sample, save_dir): if not os.path.exists(save_dir): os.makedirs(save_dir) domain_data = self.domain.sample(n_sample) boundary_data = self.domain.boundary_sample(n_sample) heading = "{:>6}{:>12}{:>12}{:>18}".format('epoch', 'loss_main', 'l...
def trading_time(self) -> bool: """ Check if it is within the allowed trading time. Returns: bool: True if it is within the allowed trading time, False otherwise. """ if int(self.start_time_hour) < datetime.now().hour < int(self.finishing_time_hour): retu...
The main task of the code is to open a trading position (Buy/Sell) based on given conditions, increment a deal counter, apply stop-loss/take-profit settings, and close all positions at the end of the trading day. It checks for existing positions, trading time validity, and executes trades accordingly while maintaining ...
def open_position(self, buy: bool, sell: bool, comment: str = "") -> None: """ Open a position based on buy and sell conditions. Args: buy (bool): True if a Buy position should be opened, False otherwise. sell (bool): True if a Sell position should be opened, False other...
def tm_from_seq(self, seq_list): # concatenate seqs with stop symbol in between # seq = np.concatenate([seq + [99] for seq in seq_list]) tm_out = np.zeros([self.nb_states, self.nb_states], dtype=int) # inventory of transitions for seq in seq_list: for tr in zip(seq[:-...
The function calculates bootstrapped confidence intervals for transition matrix (TM) values derived from data. It first computes the actual TM from given labels, then samples valid indices, performs bootstrap iterations by training HMMs and predicting sequences, aggregates TM values, and computes mean, standard deviati...
def get_data_tm(self, trace_dict, out_labels, nb_bootstrap_iters): """ Calculate bootstrapped confidence intervals on data-derived transition matrix values :return: """ # actual value actual_tm = self.tm_from_seq(out_labels) # CIs tm_array = [] in...
def gcd(a: int, b: int) -> int: """Run the euclidean algorithm to compute g = gcd(a,b). Args: a, b: ints Returns: g = gcd(a,b) Examples: >>> gcd(2024, 748) 44 """ if b == 0: return a return gcd(b, a%b) def exp_encrypt(plaintext: list[int], key: int, p: int)...
The code decrypts a ciphertext using modular exponentiation with the multiplicative inverse of the key. It ensures the key is invertible by checking $\gcd(\text{key}, p-1) = 1$. The decryption computes $x = \text{ciphertext}^{\text{inverse\_key}} \mod p$, where $\text{inverse\_key}$ is the modular inverse of the key mo...
def exp_decrypt(ciphertext: list[int], key: int, p: int) -> list[int]: """Performs the inverse of exp_encrypt. Args: ciphertext: encrypted integers key: k to invert f(x) = x^k mod p p: size of the modulus, needs to be a prime bigger than 256^block_size Returns: plaintext: a...
def accuracy(y_true, y_pred): """ Accuracy Args: y_true: array array of true labels y_pred: array array of predicted labels """ acc = (y_true == y_pred).mean() return acc def f1_average(y_true, y_pred, n_classes): """ F1 average over all classes ...
This code initializes a class to track and compute classification metrics (accuracy, F1, precision, recall) using exponential moving average (EMA). It sets up data structures to store true/predicted labels, metric calculation functions, and EMA/total accumulators for each metric. The EMA factor (0.99) and number of cla...
def __init__(self, factor_ema=0.99, n_classes=8): self.factor_ema = 0.99 self.n_classes = n_classes self.labels_true = [] self.labels_pred = [] self.metrics = {'accuracy', 'f1', 'precision', 'recall'} self.getter = {} self.getter['accuracy'] = lambda x, y: accu...
def get_subtype_mapping(self, mappings, subtype): """To Retrieve subtype mappings (mappings for subtypes of \ alerts/events) case insensitively. Args: mappings: Mapping JSON from which subtypes are to be retrieved subtype: Subtype (e.g. DLP for alerts) for which the ...
The main task of the code is to transform raw Netskope JSON data into target platform-supported formats (e.g., CEF) using predefined mappings. It checks transformation configuration, retrieves syslog/CEF mappings, processes each data entry, and constructs structured events. Errors during mapping or transformation are l...
def transform(self, raw_data, data_type, subtype) -> List: """To Transform the raw netskope JSON data into target platform \ supported data formats.""" if not self.configuration.get("transformData", True): if data_type not in ["alerts", "events"]: return raw_data...
def ensure_build_file(package: str): if os.path.isabs(package): die(f"$BUILD_CONFIG must be a relative path.") if not os.path.exists(os.path.join(package, "BUILD.bazel")) and not os.path.exists( os.path.join(package, "BUILD")): build_file = os.path.join(package, "BUILD.bazel") ...
This function generates a buildozer command to create or update a target in a build file. It checks if the target exists, writes commands to define it if missing, or updates its type if conflicting. It handles package paths, loads rules from a specified file, adds targets to distribution lists, and optionally inserts c...
def _new(self, kind: str, name: str, package=None, load_from="//build/kernel/kleaf:kernel.bzl", add_to_dist=True) -> str: """Writes a buildozer command that creates a target. Returns: the new target """ if package is None: package = self.package ...
def _new(self, kind: str, name: str, package=None, load_from="//build/kernel/kleaf:kernel.bzl", add_to_dist=True) -> str: """Writes a buildozer command that creates a target. Returns: the new target """ if package is None: package = self.package ...
This function processes build configuration variables to generate Buildozer commands for kernel builds. It creates Bazel targets like `kernel_build`, handles module packaging, image generation, and ABI settings, while adding FIXME comments for unsupported configurations or manual adjustments needed. It translates envir...
def _create_buildozer_commands(self) -> None: """Fills in self.out_file.""" common = self.args.common_kernel_tree self.dist_targets = set() target = self._new("kernel_build", self.target_name) dist = self._new("copy_to_dist_dir", self.dist_name, load_fr...
def _create_buildozer_commands(self) -> None: """Fills in self.out_file.""" common = self.args.common_kernel_tree self.dist_targets = set() target = self._new("kernel_build", self.target_name) dist = self._new("copy_to_dist_dir", self.dist_name, load_fr...
The code's main task is to generate and apply changes to BUILD files using buildozer. It first performs a dry run to identify attributes/targets for modification, retrieves existing BUILD file data, then creates and executes buildozer commands to implement the changes, ensuring updates are applied accurately.
def run(self): # Dry run to see what attributes / targets will be added self.existing = dict() with self: # This modifies self.existing self._create_buildozer_commands() # The buildozer command file is deleted. # self.existing.keys() = things we would...
def RGB_to_LUV(rgb): # Convert RGB values to the range [0, 1] rgb = rgb / 255.0 # Convert RGB to XYZ matrix = np.array([[0.412453, 0.357580, 0.180423], [0.212671, 0.715160, 0.072169], [0.019334, 0.119193, 0.950227]]) xyz = np.dot(rgb, matrix.T) ...
The function performs agglomerative clustering-based image segmentation. It reads an RGB image, converts it to LUV color space if specified, segments the image into clusters using a defined number of clusters, and visualizes the segmentation results by drawing cluster points and a dindogram on the original image.
def agglomerative(number_of_clusters=15,color_space="RGB"): Image_Before = read_rgb(gray=False, normalize=False) if color_space == "LUV": Image_Before = RGB_to_LUV(Image_Before) image = np.array(Image_Before) points,dindogram = segment(image,number_of_clusters) return draw(points,dindo...
def read_rgb(gray=False,normalize = True): img = cv2.imread('./static/img/input/current.png') #0 is to read the as gray scale if gray: img =cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # img=rgb2gray(img) # normalize the value of each pixel to be between 0 &1 if normalize: img=img/225 ...
The code processes an image to detect edges using Sobel filter and Gaussian blur, then applies a greedy algorithm to adjust an initial circular contour based on parameters alpha, beta, gamma. If area is 0, it visualizes the original and adjusted contours, saves the image, and returns the path; else, it calculates the a...
def start(radius,centerx,centery,area, alpha=1, beta=1,gamma=1): img = read_rgb(gray=True,normalize = False) s = np.linspace(0, 2*np.pi, 100) y_coordinates = centery + radius*np.sin(s) x_coordinates = centerx + radius*np.cos(s) init = np.array([y_coordinates, x_coordinates]).T new_img = img....
def find_key_by_value(cache_object, price_value): for key, value in cache_object.items(): if value['price'] == price_value: return key return None def update_db_from_cache(cache_dictionary, station_cache_id): fuel_station_id = get_fuel_station_id_from_cache_key(station_cache_id) upda...
The code processes a vote request by incrementing a vote count in a cache object. If the vote count reaches 4, it updates a database using the cache data. Otherwise, it refreshes the cache with a 1.5-hour timeout. If the requested price value isn't found in the cache, it triggers an alternative function to handle the r...
def process_vote_request(price_value, cache_object, station_cache_key, data): cache_key = find_key_by_value(cache_object, price_value) if cache_key is not None: cache_object[cache_key]['votes'] += 1 #todo fire a function here if cache_object[cache_key]['votes'] >= 4: update_...
def return_fuel_station_cache_key(id): try: station = Fueling_station.objects.only('name').get(id=id) # Generate a cache-safe key by removing invalid characters safe_name = "".join(c for c in station.name if c.isalnum()) return f"{safe_name}_ID_{id}_cache_key" except Fueling_st...
The function checks a cache key for a fuel station ID, retrieves cached data if available, extracts a price value from input data, and processes a vote request if the price exists. If no cache is found, it executes an alternative function with the cache key and data.
def check_cache_key_for_fuel_station_id_and_process_request(data, fuel_station_id): station_cache_key = return_fuel_station_cache_key(fuel_station_id) cache_object = cache.get(station_cache_key) if cache_object is not None: # Access price value from data dictionary price_value = data.get('p...
def validators(self, mask_name: str) -> list[str]: return self.mask_file_data(mask_name)["users"] def validated_mask(self, mask_name: str) -> np.ndarray: return self.mask_file_data(mask_name)["validated"] def current_mask(self, mask_name: str) -> np.ndarray: return self.mask_file_data(mask_name)...
The code checks if validators exist for a given mask name and verifies if the validated mask matches the current mask. It returns `True` if validators exist and the masks are equal, otherwise `False`.
def is_validated(self, mask_name: str) -> bool: result = len(self.validators(mask_name)) > 0 if result: assert np.array_equal(self.validated_mask(mask_name), self.current_mask(mask_name)) return result
def update(self, time, frametime): self.update_uniforms(frametime) self.buffer_agent.bind_to_storage_buffer(0) self.texture.bind_to_image(0, read=True, write=True) self.CS_agent.run( group_x=AgentConfig.N // 512 + 1, group_y=1, group_z=1 ) self.CS_texture.run( group_x=TextureConfig.size[0] // ...
This code renders a 2D scene by updating the scene if not paused, clearing the screen with a gray color, setting an orthographic projection matrix for 2D rendering, binding a texture to a shader, rendering a quad with the texture, and rendering ImGui UI elements.
def render(self, time, frametime): if not self.pause: self.update(time, frametime) self.ctx.clear(0.5, 0.5, 0.5) modelview = glm.ortho(0, TextureConfig.size[0], 0, TextureConfig.size[1], -1, 1) self.shader_texture['modelview'].write(modelview) self.texture.use(location=0) self.quad_2d.render(self.shad...
def isEven(n): return not isOdd(n) def searchEven(n): # Check for direct answer if power_of_2(n): return (1, n.bit_length()-1) # Not power of 2, so half until odd count = 0 while isEven(n): n = n>>1 count +=1 return (n, count) def searchOdd(n): # Due to log...
The code calculates the total number of steps required to reduce an integer `n` to 1 by repeatedly applying operations specific to even and odd numbers, accumulating step counts from both processes.
def search(n): count = 0 while n>1: if isEven(n): # This will always return an odd value for n (n, c) = searchEven(n) count += c # Guaranteed odd, so search it (n, c) = searchOdd(n) count += c # Return the result return count
def get_players_df(): df_players = _raw_load_df(PLAYERS_DATASET_TAG) df_players = df_players.astype({ PLAYER_DATABASE_NAME_COLUMN: str, PLAYER_DATABASE_NICKNAMES_COLUMN: str, PLAYER_DATABASE_RATING_COLUMN: pandas.Int64Dtype(), }) df_players.loc[:, PLAYER_DATABASE_NICKNAMES_COLUMN...
This function adds new player records to an existing DataFrame, assigning initial ratings based on existing data or a default value. It updates the database with new players and their ratings if specified, returning the updated DataFrame and new player data.
def add_players(player_records: List[dict], df_players=None, persist_into_database=True): if df_players is None: df_players = get_players_df() ratings = df_players[PLAYER_DATABASE_RATING_COLUMN] if len(ratings) == 0: initial_rating = DEFAULT_INITIAL_PLAYER_RATING else: initial_r...
def get_players_df(): df_players = _raw_load_df(PLAYERS_DATASET_TAG) df_players = df_players.astype({ PLAYER_DATABASE_NAME_COLUMN: str, PLAYER_DATABASE_NICKNAMES_COLUMN: str, PLAYER_DATABASE_RATING_COLUMN: pandas.Int64Dtype(), }) df_players.loc[:, PLAYER_DATABASE_NICKNAMES_COLUMN...
This function adjusts player ratings based on match outcomes by calculating rating changes using team average ratings and goal differences, applying these adjustments to individual players, and updating the player database if specified. It retrieves player data, computes adjustments, updates ratings, and optionally per...
def adjust_player_ratings(match_record, df_players=None, persist_into_database=True): if df_players is None: df_players = get_players_df() df_home_players, df_away_players = [ df_players.loc[match_record[column_name]] for column_name in [MATCHES_DATABASE_HOME_TEAM_COLUMN, MATCHES_DATABA...
def get_matches_df(): df_matches = _raw_load_df(MATCHES_DATASET_TAG) df_matches = df_matches.astype({ MATCHES_DATABASE_DATETIME_COLUMN: str, MATCHES_DATABASE_HOME_TEAM_COLUMN: str, MATCHES_DATABASE_AWAY_TEAM_COLUMN: str, MATCHES_DATABASE_HOME_GOALS_COLUMN: pandas.Int64Dtype(), ...
This function removes specified match IDs from a DataFrame, handling special cases like non-essential matches. It validates IDs, warns about essential matches, confirms deletion, and updates the database. It returns the modified DataFrame and removed data.
def remove_matches_command(match_ids, is_ignore_warnings=False, df_matches=None): if df_matches is None: df_matches = get_matches_df() ids_to_remove_set = set() indices_not_parsed = [] for id in match_ids: if id == REMOVE_NONESSENTIAL_MATCHES_STRING: is_essential = find_esse...
def get_players_df(): df_players = _raw_load_df(PLAYERS_DATASET_TAG) df_players = df_players.astype({ PLAYER_DATABASE_NAME_COLUMN: str, PLAYER_DATABASE_NICKNAMES_COLUMN: str, PLAYER_DATABASE_RATING_COLUMN: pandas.Int64Dtype(), }) df_players.loc[:, PLAYER_DATABASE_NICKNAMES_COLUMN...
The main task of the code is to identify and remove players from a DataFrame based on input identifiers. It categorizes identifiers into invalid indices, unrecognized entries, or ambiguous matches, then removes corresponding players from the DataFrame if valid. It returns the removed players and lists of problematic id...
def remove_players(identifiers, df_players=None): if df_players is None: df_players = get_players_df() identification_dict = identify_players(identifiers, df_players) ids_to_remove, invalid_index_identifiers, unrecognized_identifiers, undecided_identifiers = [[] for _ in range(4)] for identifie...
def round_rating(rating): if isinstance(rating, pandas.Series): return rating.round() else: return round(rating) def add_players(player_records: List[dict], df_players=None, persist_into_database=True): if df_players is None: df_players = get_players_df() ratings = df_players[PL...
The function adds a new player to a database with their name, lowercased nicknames, and an optional rounded rating if provided. It updates the database and displays the added player's information to the user.
def add_player_command(rating, name, nicknames): player_record = { PLAYER_DATABASE_NAME_COLUMN: name, PLAYER_DATABASE_NICKNAMES_COLUMN: [nick.lower() for nick in nicknames], } if rating > 0: player_record[PLAYER_DATABASE_RATING_COLUMN] = round_rating(rating) df, df_new = add_play...
def get_matches_df(): df_matches = _raw_load_df(MATCHES_DATASET_TAG) df_matches = df_matches.astype({ MATCHES_DATABASE_DATETIME_COLUMN: str, MATCHES_DATABASE_HOME_TEAM_COLUMN: str, MATCHES_DATABASE_AWAY_TEAM_COLUMN: str, MATCHES_DATABASE_HOME_GOALS_COLUMN: pandas.Int64Dtype(), ...
The function `add_matches` processes a list of match records by validating team IDs, handling goal and datetime fields, adjusting player ratings, and appending records to a DataFrame. It ensures data consistency, fills missing fields with defaults, and optionally persists updates to a database.
def add_matches(match_records: List[dict], df_matches=None, df_players=None, persist_into_databse=True): if df_matches is None: df_matches = get_matches_df() for match_record in match_records: home_team_ids = match_record[MATCHES_DATABASE_HOME_TEAM_COLUMN] away_team_ids = match_record[M...
def get_matches_df(): df_matches = _raw_load_df(MATCHES_DATASET_TAG) df_matches = df_matches.astype({ MATCHES_DATABASE_DATETIME_COLUMN: str, MATCHES_DATABASE_HOME_TEAM_COLUMN: str, MATCHES_DATABASE_AWAY_TEAM_COLUMN: str, MATCHES_DATABASE_HOME_GOALS_COLUMN: pandas.Int64Dtype(), ...
The main task of the code is to update a match's score in a database, adjust player ratings based on the new scores, and optionally persist changes. It updates home/away goals, timestamps, and triggers player rating adjustments. If allowed, it rescores matches; otherwise, it ensures the match isn't essential. The funct...
def score_match(match_id, home_goals, away_goals, df_matches=None, df_players=None, allow_rescoring_of_matches=False, persist_into_database=True): if df_matches is None: df_matches = get_matches_df() if not allow_rescoring_of_matches: assert not find_essential_matches_mask(df_matches).loc[match...
def remove_players(identifiers, df_players=None): if df_players is None: df_players = get_players_df() identification_dict = identify_players(identifiers, df_players) ids_to_remove, invalid_index_identifiers, unrecognized_identifiers, undecided_identifiers = [[] for _ in range(4)] for identifie...
This function processes a list of player identifiers to remove corresponding entries from a DataFrame. It identifies removed players, invalid IDs, unmatched identifiers, and ambiguous matches, then provides user feedback on each case. If players are removed, it displays their details. It alerts users about invalid IDs,...
def remove_players_command(identifiers, df_players=None): removed_players, invalid_index_identifiers, unrecognized_identifiers, undecided_identifiers = remove_players(identifiers, df_players) nr_removed = len(removed_players.index) if nr_removed > 0: display_string_to_user(f"Removed {nr_removed} pl...
def display_string_to_user(string: str): RICH_CONSOLE.print(string) def get_players_df(): df_players = _raw_load_df(PLAYERS_DATASET_TAG) df_players = df_players.astype({ PLAYER_DATABASE_NAME_COLUMN: str, PLAYER_DATABASE_NICKNAMES_COLUMN: str, PLAYER_DATABASE_RATING_COLUMN: pandas.Int...
The main task of the code is to add a match record to a database by validating team compositions and player identifiers. It separates home/away teams using a specified delimiter, checks for duplicate or ambiguous player matches, ensures teams have equal unique players, and inserts the validated match data into the data...
def add_match_command(datetime, args): teams_spearator_index = None teams_spearator_string = None for index in range(len(args)): if args[index] in TEAM_SEPARTION_STRINGS: if teams_spearator_index is not None: display_string_to_user(f"Multiple teams separators. Found {team...
def get_players_df(): df_players = _raw_load_df(PLAYERS_DATASET_TAG) df_players = df_players.astype({ PLAYER_DATABASE_NAME_COLUMN: str, PLAYER_DATABASE_NICKNAMES_COLUMN: str, PLAYER_DATABASE_RATING_COLUMN: pandas.Int64Dtype(), }) df_players.loc[:, PLAYER_DATABASE_NICKNAMES_COLUMN...
The code drafts a command to split specified players into two balanced teams based on their ratings, ensuring an even number of players. It calculates the rating imbalance and selection probability, then suggests or stores the match depending on the discard flag, displaying team ratings and match details.
def draft_command(player_identifiers, is_discard_match): if len(player_identifiers) == 0: click.echo("Please specify available players in arguments. These players will be separated into two teams of approximatly equal rating.") exit(-9184) if len(player_identifiers) % 2 == 1: click.echo(...
def get_players_df(): df_players = _raw_load_df(PLAYERS_DATASET_TAG) df_players = df_players.astype({ PLAYER_DATABASE_NAME_COLUMN: str, PLAYER_DATABASE_NICKNAMES_COLUMN: str, PLAYER_DATABASE_RATING_COLUMN: pandas.Int64Dtype(), }) df_players.loc[:, PLAYER_DATABASE_NICKNAMES_COLUMN...
This function recomputes player ratings using match data, backing up original datasets, initializing standard players with default ratings, and updating ratings for non-standard players through match scoring. It processes each match, adjusts player ratings, and persists changes, ensuring accurate rating recalculations ...
def recompute_ratings(df_players=None, df_matches=None, df_rating_changes=None): if df_players is None: df_players = get_players_df() if df_matches is None: df_matches = get_matches_df() if df_rating_changes is None: df_rating_changes = get_rating_changes_df() for dataset_path i...
def display_string_to_user(string: str): RICH_CONSOLE.print(string) def get_matches_df(): df_matches = _raw_load_df(MATCHES_DATASET_TAG) df_matches = df_matches.astype({ MATCHES_DATABASE_DATETIME_COLUMN: str, MATCHES_DATABASE_HOME_TEAM_COLUMN: str, MATCHES_DATABASE_AWAY_TEAM_COLUMN: ...
This function updates a match's score in a database, validating inputs (non-negative goals, existing match ID), ensuring the match hasn't been scored before, then applying score changes and displaying updated results and rating adjustments.
def score_match_command(match_id, home_goals, away_goals, df_matches=None, df_players=None): if home_goals < 0 or away_goals < 0: display_string_to_user("Home and away scores need to be non negative integers") if df_matches is None: df_matches = get_matches_df() if match_id not in df_matche...
def Q_1(conn, execution_time): new_conn = load_database(conn) cursor = new_conn.cursor() #========================================================================== # Enter QUERY within the quotes: query = """ SELECT p.player_name, AVG(s.statsbomb_xg) AS avg_xgScore FROM players ...
The code executes ten sequential queries (Q_1 to Q_10) on a database connection, tracking each query's execution time in a list. It updates the connection object after each query and prints the recorded times. The main task is to run multiple queries, measure their execution durations, and output the results.
def run_queries(conn): execution_time = [0,0,0,0,0,0,0,0,0,0] conn = Q_1(conn, execution_time) conn = Q_2(conn, execution_time) conn = Q_3(conn, execution_time) conn = Q_4(conn, execution_time) conn = Q_5(conn, execution_time) conn = Q_6(conn, execution_time) conn = Q_7(conn, execution...
def initialize_joystick(): global buttons global js_name pygame.init() pygame.joystick.init() try: js = pygame.joystick.Joystick(0) js.init() js_name = js.get_name() if js_name in ('Wireless Controller', 'Sony Computer Entertainment Wireless Controller'): ...
The main task of the code is to initialize a joystick and a drone system, then execute the `run()` function, which likely controls the drone's operation using joystick inputs.
def main(): initialize_joystick() initialize_drone() run()
def resetTimer(self): self.time_start = None self.total_time_sum = 0 self.detected_num = 0 return def startTimer(self): self.time_start = time.time() return def createMeshes(self, mesh_file_path): faces, feats, Fs = self.loadMesh(mesh_file_path, ...
The code tests a 3D mesh detection model by processing .obj files in a specified folder. It runs detection tasks, measures performance (time/FPS), and prints statistics. If run_episode <0, it runs indefinitely; otherwise, it executes a set number of episodes. It skips initial timer updates and tracks detected objects, ...
def test(self, mesh_folder_path, run_episode=-1, timer_skip_num=5): if not self.model_ready: print("Model not ready yet, Please loadModel or check your model path first!") return if run_episode == 0: print("No detect run with run_episode=0!") return ...
def delete_file(file): if os.path.isfile(file): os.remove(file) def plot_mem_amd(folder,card): file=folder+'/'+card+'/amd_mem.csv' output = exec_cmd("head -100 {} |grep -n 'Profile Time:'".format(file)) line_number=int(output.split(':')[0])-7 data = pd.read_csv(file, header=[line_number,line...
The main task of the code is to generate performance metrics plots for a specified hardware card, handling different data sources (AMD, PMT, etc.), checking file existence to determine plotting methods, and executing relevant visualization functions for memory, CPU, disk, and AI performance, while managing temporary fi...
def plot_metrics(path,card): global START,STOP #plot_pcie(path,card) #plot_mem(path,card) sum_file="{}/{}/summary.log".format(path,card) delete_file(sum_file) if os.path.isfile(path+'/'+card+'/amd_mem.csv'): plot_mem_amd(path,card) elif os.path.isfile(path+'/'+card+'/mem.csv'): ...
def create_folder_remote(user, host, work_dir): cmd="ssh {}@{} mkdir -p {}".format(user,host,work_dir) out=exec_cmd(cmd) def start_perf(host,work_dir,case_name,local_dir): #result_folder= "/home/test" #work_folder=work_dir+'/'+sub_folder perf_file="start_perf.sh" send_file_remote('root', host, l...
The function `test_and_monitor` executes performance testing and monitoring on a remote host. It creates directories, initiates performance metrics collection, launches dockers, waits for processes, stops monitoring, downloads logs, generates visualizations, writes summaries, and archives results into a compressed file...
def test_and_monitor(host,name,case): path1="/home/test/dataset/" #remote folder = 'script/' # local full="{}.{}".format(name,case) create_folder_remote('root', host, path1) start_perf(host,path1,full,folder) start_dockers(host,name,path1,folder,case) time.sleep(5) #wait_for_pid_finish...
def non_rectangular_convolution_edge(list1: List[int], list2: List[int], geometry: List[Tuple[float, float]], ntt_prime: int) -> Tuple[List[int], int]: """Non-Rectangular Convolution -- Base Case 1: Single edges. Args: list1 ...
The function performs non-rectangular convolution of two integer lists over an arbitrary triangle geometry using a number-theoretic transform (NTT). It handles degenerate triangles, axis-aligned cases, and general triangles by decomposing them into rectangles, edges, and axis-aligned sub-triangles. The convolution resu...
def non_rectangular_convolution_triangle( list1: List[int], list2: List[int], geometry: List[Tuple[float, float]], ntt_prime: int) -> Tuple[List[int], int]: """Non-Rectangular Convolution -- Base Case 4: arbitrary Triangles. All ed...
def non_rectangular_convolution_edge(list1: List[int], list2: List[int], geometry: List[Tuple[float, float]], ntt_prime: int) -> Tuple[List[int], int]: """Non-Rectangular Convolution -- Base Case 1: Single edges. Args: list1 ...
The function computes the non-rectangular convolution of two integer lists over an arbitrary convex polygon geometry using number-theoretic transforms (NTT). It handles polygons with 2, 3, or more vertices by decomposing them into edges and triangles, recursively calculating their convolutions, and combining results vi...
def non_rectangular_convolution_convex_polygon( list1: List[int], list2: List[int], geometry: List[Tuple[float, float]], ntt_prime: int) -> Tuple[List[int], int]: """Non-Rectangular Convolution -- Base Case 5: Arbitrary convex polygons...
def get_version_abbrev(vsn): abbrev = '' versions = get_versions() for a in versions: if vsn in a[1]: abbrev = a[2] return abbrev images['cover'].append(pic.path_thumb_l) def book_id(book_name): bk_code = booklist.index(book_name) bk_code +=1 # since array starts from 0 ...
The main task of the code is to process search requests by determining the type of search (keyword, ID, or verse range), constructing search parameters, executing the appropriate search function, and rendering results in a template. It handles input validation, search logic, and result formatting, while also leaving no...
def results(): print("Results page...") # TODO: can reduce the vars searchtext = '' searchresult = [] id_input = '' id_result = '' kw_len = '' bcv = '' # TODO: if can abstract some of it in func or put vars in dict # results object vars print("REQUEST ARGS: ",request.args) ...
def getShoulderAngleYZ(self): # Get angle between shoulder and elbow in YZ plane return self.calculateAngle3d(self.right_elbow, self.right_shoulder, self.right_hip) * 1.25 def linearShoulderAngleX(self): diff_shoulder_elbow_x = abs(self.right_elbow.x - self.right_shoulder.x)*100 # if (se...
The code updates the robot's shoulder and elbow angles by calculating the shoulder angle in the YZ plane using `getShoulderAngleYZ()`, determining the shoulder angle in the XY plane via a linear method `linearShoulderAngleX()`, and retrieving the elbow angle with `getElbowAngle()`. It replaces a previously commented co...
def updateAngles(self): # Update angles self.shoulder_angle_YZ = self.getShoulderAngleYZ() # if self.shoulder_angle_YZ > 90: # self.shoulder_angle_XY = abs(180-self.getShoulderAngleXY()) # else: # self.shoulder_angle_XY = self.getShoulderAngleXY() self.sho...
def compile(self): file_name = self.get_file_name() name = self.get_obj_file_name() if os.path.isfile(name): os.remove(name) if os.path.isfile(MEDIA_ROOT + '/' + file_name): cmd = ['g++', '-std=c++14', '-o', name, file_name] r = subprocess.Popen(cmd,...
This code tests a submission against multiple test cases by compiling the code, executing each test input, checking outputs, and returning the maximum error value (toe) along with a status code indicating success, failure, or partial failure. It handles file cleanup and uses a checker to validate outputs, terminating e...
def test(self, submission): self.compile() name = self.get_obj_file_name() toe = 0.00 print("Compilation successful") for test in self.test_set.all(): with open(test.inp.path, 'r') as f: inp = f.read().replace('\n', '') r = submission.run(i...
def __process_eq_str(eq_ls): # split lhs and rhs __lhs_ls, __rhs_ls = __hs_ls(eq_ls) # parse lhs to get/replace derivative variable dep_dict, indep_dict = __lhs_parse(eq_ls, __lhs_ls) # replace derivative at rhs __rhs_replace(eq_ls, dep_dict, indep_dict, __rhs_ls) # post-process equation...
The function `func_from_string` generates a Python function from given equations and optional constants. It processes equations into strings and dependency/independent variable mappings. If constants are provided, it integrates them into the function definition. The generated function, when called with variables `_x_`,...
def func_from_string(equations, constants=None): eqs_str, dep_dict, indep_dict = __process_eq_str(equations) if constants: cons_str = __process_const_str(constants) print(f"def func(_x_, _y_, _f_): {cons_str} {eqs_str}") return __func_from_string(f"def func(_x_, _y_, _f_): {cons_str} {e...
def weaponSelect(charFile): global Weapons, weaponList Weapons = readCharFile(charFile, p1) p1.Weapons = [] weaponNames = [] ##weaponShop() for i in range(len(weaponList)): weaponNames.append(weaponList[i].name) for i in range(len(Weapons)): try: weaponNames.inde...
The function `getCharFile` retrieves a filename from a UI input, updates weapon, armor, and spell selections using the file, sets UI values, and closes the window, leveraging global variables for data storage and modification.
def getCharFile(): global weaponList, Armors, Weapons, Spells charFile = dpg.get_value("filename") weaponSelect(charFile) armorSelect() spellSelect() setValues() close()
def getYesNo(text): print(text) while(True): key = input() if (key == "Y" or key == "y" or key == "yes" or key == "YES"): return "Y" elif(key == "N" or key == "n" or key == "no" or key == "NO"): return "N" else: print("Error: invalid input. Ent...
The function processes all CSV files in a specified directory, analyzing each and logging results into designated output files. It checks if the output files exist, prompts for overwriting if needed, then iterates through valid CSV files, incrementing an age parameter, and compiles analysis results.
def analyzeAndLogAllCSVInPath(quota, outfile, of1, of2, of3, of4, startAge, fathersSong, path): if(os.path.exists(path)): os.chdir(path) if (os.path.isfile(outfile)): yn = getYesNo("This outfile already exists. Do you want to overwrite? (Y/N)") if (yn == "N"): ...
def getSegments(self): """ Extracts all segments based on the templates; these are the locations, directions and lengths of all sequences of cells where a clue will go. Returns segments: list(tuple(row:int, column:int, length:int, direction:Direction)) ...
This code generates a puzzle by iteratively placing words into grid segments, using backtracking to resolve dead-ends. It shuffles vocabulary, tests words against segment patterns, and adds valid words. If no match is found, it backtracks by removing recent additions, adjusting indices, and reshuffling. The process rep...
def _run(self): """Runs the creation of the puzzle.""" segments = list(self.getSegments()) segmentsAdded = [] # Tracks all added clues; reverts = [0 for s in segments] # Tracks the number of times running was reverted for a clue, used to backtrack; i = ...
def read_data(dataset_path): global header data = list() f = open(dataset_path, 'r') file = reader(f) for line in file: data.append(line) header = data.pop(0) for i in range(len(data)): data[i] = list(map(float, data[i])) if data[i][-1] == 0: data[i][-1] =...
The code evaluates and visualizes the error rates of a classification model across different threshold values using either ERM (Empirical Risk Minimization) or K-fold cross-validation. It reads dataset, computes errors for each threshold, plots the error trend against thresholds, and displays the graph. The main task i...
def adaboost(dataset_path, mode): data = read_data(dataset_path) threshold = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 25, 30, 40, 50, 60, 120, 180, 240] errors = [] if (mode == 'erm'): for t in threshold: errors.append(classify_erm(data, t)) else: for t in thre...
def read_data(dataset_path): data = list() f = open(dataset_path, 'r') file = reader(f) for line in file: data.append(line) data.pop(0) return data def classify_erm(data): errors, weight_matrix = predict_model(data, data) return errors, weight_matrix def classify_kfolds(data): ...
The code classifies a dataset using either ERM (Empirical Risk Minimization) or k-folds cross-validation, based on the specified mode. It reads input data, computes classification errors and a weight matrix, prints these values, and returns the mean error. A global threshold is set to 400, influencing the classificatio...
def classifier(dataset_path, mode): global threshold data = read_data(dataset_path) threshold = 400 errors = None weight_matrix = None if(mode=='erm'): errors, weight_matrix = classify_erm(data) else: errors, weight_matrix = classify_kfolds(data) print("Errors is/are: ", ...
def read_data(dataset_path): data = list() f = open(dataset_path, 'r') file = reader(f) for line in file: data.append(line) data.pop(0) return data def normalize(data): temp = np.array(data) mean_list = np.mean(temp, axis=0) std_list = np.std(temp, axis=0) for j in range(...
The code performs K-means clustering on a dataset by reading, normalizing, initializing random centroids, assigning data points to clusters based on a specified distance metric, and evaluating cluster quality.
def kmeans(dataset_path, k, distance): data = read_data(dataset_path) data = [[float(float(j)) for j in i] for i in data] normalize(data) centroids = random.sample(range(0, len(data)), k) centroids = [data[i] for i in centroids] clusters = get_clusters(data, centroids, distance) evaluate_clu...
def clean_expr(s): s = s.strip() if s == "" or s[0] != '(' or s[-1] != ')': return s depth = 1 for i in range(1, len(s) - 1): if s[i] == '(': depth += 1 elif s[i] == ')': depth -= 1 if depth == 0: return s return clean_expr(...
The code parses mathematical expressions into a symbolic representation, handling variables, constants, and operations (+, -, *, /, ^). It recursively processes expressions, applying modular arithmetic and managing equations/variables globally. Special cases include boolean expressions, negation, and secret values, ret...
def parse_expression(s): global cache global eqs global varset s = clean_expr(s) if s == "": raise Exception("Empty expression") sp = split_expr_binary(s, ["^"]) if sp: (left, op, right) = sp l = parse_expression(left) r = parse_expression(right) ret =...
def split_expr_binary(s, ops): i = 1 depth = 0 for i in range(len(s), 1, -1): if s[i - 1] == ')': depth += 1 elif s[i - 1] == '(': depth -= 1 elif depth == 0: for op in ops: if i - len(op) >= 1 and s[i-len(op):i] == op: ...
The function `parse_expressions` parses a string `s` containing comma-separated expressions. It splits the string on commas using `split_expr_binary`, recursively processes the left part, and appends the parsed right part. If no split occurs, it parses the entire string as a single expression. The task is to decompose ...
def parse_expressions(s): sp = split_expr_binary(s, [","]) if sp: (left, op, right) = sp return parse_expressions(left) + [parse_expression(right)] return [parse_expression(s)]
def parse_expression(s): global cache global eqs global varset s = clean_expr(s) if s == "": raise Exception("Empty expression") sp = split_expr_binary(s, ["^"]) if sp: (left, op, right) = sp l = parse_expression(left) r = parse_expression(right) ret =...
The code parses assignment statements with operators like `:=`, `=:` and `=`, handling bit-level assignments, variable declarations, and equality checks. It processes expressions, validates variable names, creates constants or temporary variables, and records equations (`eqs`) for constraints. Debug statements are prin...
def parse_statement(s): global varset global eqs s = s.strip() if len(s) > 6 and s[0:6] == "debug ": expr = parse_expression(s[6:]) print("DEBUG %s: %s [0x%x]\n" % (s[6:], expr, expr.get_real())) return sp = split_expr_binary(s, [":=", "=:", "==", "="]) if sp: (le...
def __set_up(self): """Instantiate database read/write interfaces""" self.db_reader = DbReader() self.db_writer = DbWriter() def __parse_csv(self, csv_reader): """Request, parse, and persist property information for each row in the input csv file""" for index, row in enumerate(...
The main task of the code is to process STL city parcel data by loading a CSV file, fetching additional property details from the STL City Gov Address Search website, normalizing the data, and persisting it into a remote database for further analysis and processing.
def run(self): """ This is the main entry point for StlCityParcelProcessor package. Loads input data csv file and fetches additional property information from the STL City Gov Address Search website. After fetching additional property information, normalize and persist data in...
def run_speed(self) -> bool: if not self._stepInterval: return False time = perf_counter_ns() // 1000 # time in us if (time - self._lastStepTime) >= self._stepInterval: if self._direction == DIRECTION_CW: self._currentPos += 1 else: ...
The code's main task is to determine if an object is still moving or has remaining distance to travel. It checks if `run_speed()` is true, updates the speed if so, and returns `True` if the object's speed is non-zero or it still has distance to go, indicating active movement or pending motion.
def run(self) -> bool: if self.run_speed(): self.compute_new_speed() return self.speed != 0.0 or self.distance_to_go() != 0
def process_xml_dir(path): """Processed xml directory into array of points, separated by lines""" try: _, _, file_names = next(os.walk(path)) except StopIteration: return [] lines = [] for file_name in file_names: xml_path = os.path.join(path, file_name) lines.append(process_...
The main task of the code is to traverse directories, process XML and ASCII files to extract line points and translations, filter eligible pairs, and return them as two separate lists.
def main(): lines = [] translations = [] for cur_dir, sub_dirs, files in os.walk(lines_path): if not files: continue line_points = process_xml_dir(cur_dir) dir_id = get_dir_id(cur_dir) translation_lines = process_ascii_dir(dir_id) if is_eligible(line_points, transla...