dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def longest_ORF_noncoding(dna, num_trials): """ Computes the maximum length of the longest ORF over num_trials shuffles of the specfied DNA sequence dna: a DNA sequence num_trials: the number of random shuffles returns: the maximum length longest ORF To test, I entered a sho...
The main task of the code is to identify and return amino acid sequences encoded by open reading frames (ORFs) in both strands of the given DNA sequence. It filters ORFs longer than a threshold derived from the longest non-coding ORF of a specified length, translates valid ORFs into amino acids using a coding strand co...
def gene_finder(dna): """ Returns the amino acid sequences that are likely coded by the specified dna dna: a DNA sequence returns: a list of all amino acid sequences coded by the sequence dna. """ # TODO: implement this threshold = longest_ORF_noncoding(dna, 1500) all_orf_both = fin...
def choose_random_amino_acid(protein): """Returns a random amino acid in a given protein.""" random_aa = random.choice(protein.all_residues) return random_aa def choose_random_move(self, new_protein, residue, search_space="VSHD-pull", pull_probability=0.5): """...
The main task of the code is to perform a Monte Carlo simulation for protein structure optimization by iteratively selecting random amino acids, attempting valid movements within a defined search space, and evaluating the energy of successful moves. The algorithm ensures each iteration finds a valid move through repeat...
def apply_monte_carlo(self, search_space="VSHD-pull", pull_probability=0.5): """Applies the search whereby each iteration includes choosing an amino acid, a random movement, testing if the amino acid can undergo the movement, if not choosing another amino acid until a successful move tha...
def get_dbf_table_files(): files_list = os.listdir(DBFolder) for f in files_list: if str(f).endswith('DBF'): DB_files.append(f) return DB_files def get_table_records(path,db_file_name,*args,**kwargs): p = path fn = db_file_name while kwargs: current_tb_path = kwargs['...
The code lists DBF table files, selects a specific table (hardcoded index 41), retrieves its records, builds connection strings from the data, and prints the count of these strings. The main task is to process DBF tables, extract connection information, and output the number of generated connection strings.
def main(): tabels_list = get_dbf_table_files() for fl in tabels_list: num = tabels_list.index(fl) print('tabels #: ',num,fl) #tbn = int(input(print('choose table number'))) tbn = 41 # todo: build button option to choose from tb_rec = get_table_records(DBFolder, tabels_list[tbn]) # ...
def unpack_h(s): return unpack_signed('>h', s, H_COMPLEMENT) def unpack_b(s): return bool(unpack_signed('>b', s, B_COMPLEMENT)) def unpack_i(s): return unpack_signed('>i', s, I_COMPLEMENT) def to_date(s): ordinal = unpack_i(s) if ordinal is None: return try: return date.fromordin...
This function decodes data based on the type code 't' by applying corresponding unpacking or conversion methods to the value 'v', using the specified input encoding. It handles different data types like strings, dates, times, and binary data, returning appropriately processed values.
def decode_data(t, v, input_encoding): if t == 'A': return v.strip('\x00').decode(input_encoding) if t == 'S': return unpack_h(v) if t == 'L': return unpack_b(v) if t == 'I': return unpack_i(v) if t == 'D': return to_date(v) if t == 'T': return to_...
def get_config(config_path): cfg = LazyConfig.load(config_path) cfg.train.batch_size = 1 return cfg def get_dataloader(cfg, dataset_to_visualize): if dataset_to_visualize == "train": # Remove GroundTruthBoxesToAnchors transform cfg.data_train.dataset.transform.transforms = cfg.data_train...
The main task of the code is to load a configuration file, retrieve a dataset (train/val), and analyze it using the specified configuration parameters, including printing the label map and processing data through a dataloader for further analysis or model training.
def main(): config_path = "configs/tdt4265_updated.py" cfg = get_config(config_path) dataset_to_analyze = "train" # "train/val" print("Label map is:", cfg.label_map) dataloader = get_dataloader(cfg, dataset_to_analyze) analyze_something(dataloader, cfg)
def calculate_individual_image_result(prediction_boxes, gt_boxes, iou_threshold): """Given a set of prediction boxes and ground truth boxes, calculates true positives, false positives and false negatives for a single image. NB: prediction_boxes and gt_boxes are not matched! Args: p...
The code calculates precision and recall metrics across all images by comparing predicted bounding boxes (all_prediction_boxes) with ground truth boxes (all_gt_boxes) using a specified IoU threshold. For each image, it computes true positives, false positives, and false negatives via `calculate_individual_image_result`...
def calculate_precision_recall_all_images( all_prediction_boxes, all_gt_boxes, iou_threshold): """Given a set of prediction boxes and ground truth boxes for all images, calculates recall and precision over all images for a single image. NB: all_prediction_boxes and all_gt_boxes are not matc...
def get_precision_recall_curve( all_prediction_boxes, all_gt_boxes, confidence_scores, iou_threshold ): """Given a set of prediction boxes and ground truth boxes for all images, calculates the recall-precision curve over all images. for a single image. NB: all_prediction_boxes and all_gt_b...
The function calculates the mean average precision (mAP) for object detection over a dataset using an IoU threshold of 0.5. It aggregates ground truth and predicted boxes with confidence scores, computes precision-recall curves, and derives mAP by averaging precision values across recall thresholds. The result is print...
def mean_average_precision(ground_truth_boxes, predicted_boxes): """ Calculates the mean average precision over the given dataset with IoU threshold of 0.5 Args: ground_truth_boxes: (dict) { "img_id1": (np.array of float). Shape [number of GT boxes, 4] } pred...
def is_ha(subtype: str) -> bool: return bool(re.fullmatch("H\d+", subtype)) def get_signal_offset(subtype: str) -> int: """ subtype should be a string from H1 to H18 """ try: return len(motifs.NTERM_MOTIFS[subtype]) except KeyError: raise InputError("Expected a subtype string (e....
The function extracts specific sequence motifs from a FASTA file based on given bounds, adjusting for signal peptides if specified. It processes input sequences, applies bounds offsets for HA subtypes, extracts motifs using _dispatch_extract, and returns pairs of sequence headers with their corresponding motif sequence...
def extract_bounds( fasta_file: TextIO, bounds: List[Tuple[int, int]], seq_opts: SeqOpts = SeqOpts(), mafft_opts: MafftOpts = MafftOpts(), ) -> List[Tuple[str, List[str]]]: """ Extract a motif """ bounds = [(min(xs), max(xs)) for xs in bounds] if not seq_opts.keep_signal: if...
def referenced_table( faa: TextIO, seq_opts: SeqOpts = SeqOpts(), mafft_opts: MafftOpts = MafftOpts(), aadiff_opts: AadiffOpts = AadiffOpts(), ) -> List[List[str]]: # if this is an HA and we want to trim off the signal peptide if ( seq_opts.subtype is not None and is_ha(seq_opts....
This function generates an HA (Hemagglutinin) subtype annotation table by combining sequence alignment data with reference annotations from a predefined file. It validates input subtypes, maps them to annotations, and appends relevant metadata to a table. The process involves parsing sequence files, checking subtype fo...
def referenced_annotation_table( faa: TextIO, mafft_opts: MafftOpts = MafftOpts(), seq_opts: SeqOpts = SeqOpts(), aadiff_opts: AadiffOpts = AadiffOpts(), ) -> List[List[str]]: """ This is just for HA """ table = referenced_table(faa, seq_opts, mafft_opts, aadiff_opts) subtype_file ...
def parse_motif( motif_str: str, subtype: Optional[str] ) -> Tuple[str, List[Tuple[int, int]]]: """ Parse a motif string provided by the user through the `flutile trim motif` command. Here is the string grammar: motif = range | name "=" range range = number | number "-" num...
The code processes a FASTA file and motif strings to extract sequence segments defined by motif bounds. It parses motifs into a dictionary, concatenates their bounds, and extracts corresponding sequence pairs from the FASTA file using alignment options. The function returns motif names and extracted sequence pairs, ena...
def make_motifs( fasta_file: TextIO, motif_strs: List[str], seq_opts: SeqOpts = SeqOpts(), mafft_opts: MafftOpts = MafftOpts(), ): motifs: Dict[str, List[Tuple[int, int]]] = dict() motifs = { name: bounds for (name, bounds) in [ parse_motif(motif, subtype=seq_opts.su...
def read_payload_file(file_path: str): with open(file_path) as file_obj: return (line.strip() for line in file_obj.readlines() if line) def generate_mutations(company_name: str, mutation_payload: list[str]) -> list[str]: mutations = [company_name] for mutation in mutation_payload: mutations...
The code performs brute-force enumeration of AWS S3 buckets using either generated mutations (if 'generate' is True) or predefined payloads. It reads bucket names from a file, creates payload chunks, runs asynchronous brute-force attacks, and outputs statistics, elapsed time, and found results. The 'generate' flag dete...
def cloud_sherlock(name, generate, buckets, rps): bucketnames_data = read_payload_file(buckets) if generate: mutations = generate_mutations(name, bucketnames_data) gen = generate_enum_payload_chunk(saas_payload=mutations, buckets_payload=mutations) print_s...
def _display_menu_header_elements(self) -> None: header_label_desc = ttk.Label(self.mainframe, text="Task Description").grid(column=2, row=1, sticky=ttkk.NW) header_label_date = ttk.Label(self.mainframe, text="Deadline\n(YYYY-MM-DD)").grid(column=3, row=1, ...
(The code initializes a To Do List GUI application, setting up a main window with a grid layout, configuring UI elements for task display, navigation, and input, and integrating a database for data storage/retrieval. It creates the user interface framework and starts the Tkinter main event loop to enable user interacti...
def __init__(self, db): """ Initiator Parameters: ----------- db: TaskDatabase The database session object the UI stores and retrieves data from """ self.task_page = 1 self.tasks = {} self.task_ui_stringvar_dict = {} root = tt...
def download_all_crypto_dataframe(self): results = [] for crypto in self.pairs: result = self.download_one_crypto(crypto.get('pair')) if result: results.append(pd.DataFrame(result.Close).rename(columns = {'Close': crypto.get('pair').split('-')[0]})) return...
The main task of the code is to download cryptocurrency data, join the resulting dataframes, and convert the merged data into a JSON format representing correlations. It includes error handling to catch and print exceptions during execution.
def main(self): try: download = self.download_all_crypto_dataframe() if download: join_dataframe = self.join_dataframe(download) return self.df_corr_to_json(join_dataframe) except Exception as err: print(f"ERROR: {err}")
def parse_categories(self, nodes: list[Node]) -> Iterator[Category]: """Parse the categories from a list of nodes.""" for node in nodes: yield Category( node.css_first("a").text(), self.parse_url(node.css_first("a").attrs["href"]), ) def parse_ext...
The code parses a webpage into a structured `Page` object by extracting elements like title, categories, external links, content, and references. It handles date formatting, error checks for missing content, and constructs the object with parsed data including last modified time, headers, and table of contents.
def parse(self) -> Page: """Parse the page and return a Page object.""" content = self.parser.css_first("#content") self.title = content.css_first("#firstHeading").text() for b in self.parser.css("div + b"): if b.text(strip=True) == NOT_FOUND_TEXT: raise scr...
def quick_sort(arr, p, r, comparisons=0): if p < r: comparisons, q = partition(arr, p, r, comparisons) comparisons += quick_sort(arr, p, q - 1) comparisons += quick_sort(arr, q + 1, r) return comparisons def median_quick_sort(arr, p, r, comparisons=0): if p < r: if r - p + ...
The main task of the code is to measure and return the number of comparisons made by three quicksort variants—standard, median-of-three, and multi-pivot—when sorting a given array. Each variant operates on a copy of the input array to isolate performance metrics.
def count_comparisons(arr): comp_quick_sort = quick_sort(arr.copy(), 0, len(arr) - 1) comp_median_quick_sort = median_quick_sort(arr.copy(), 0, len(arr) - 1) comp_multi_quick_sort = multi_quick_sort(arr.copy(), 0, len(arr) - 1) return comp_quick_sort, comp_median_quick_sort, comp_multi_quick_sort
def get_title_from_wayback(url): page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') result = soup.find('span', class_='H1') if result is None: result = soup.find('h1', {"align": "center"}) if result is None: return "no-wayback" return format_title_t...
The code processes a range of URLs from 'https://abcbirds.org/', retrieves titles using the Wayback Machine, checks for accessibility, and saves notes (e.g., "no-wayback-machine" or working links) to a link object. It iterates from input values 'a' to 'b', prints progress, and stores results.
def add_all_links(a,b): link.rowNum = a for i in range(a,b): a = get_title_from_wayback(format_url()) current_link = return_working_title("https://abcbirds.org/" + a) print(str(i) + " " + current_link + " \n " + "https://abcbirds.org/" + a) if a in 'no-wayback': li...
def populate_student_names(): global worksheet, stud_name_dict address = 6 for key, value in sorted(stud_name_dict.items()): worksheet.write('A' + str(address), key) worksheet.write('B' + str(address), value) address += 1 def prepare_subject_columns(alpha, subject): global works...
The main task of the code is to generate a structured Excel workbook for student attendance data. It formats headers with college name, department, and date range, maps department codes to full names, populates student registration/name columns, prepares subject-specific columns, and fills attendance data from a dictio...
def prepare_workbook(): global workbook, workbook, merge_format_head, merge_format, sub_code_name, START_DATE, END_DATE, department workbook.add_vba_project('./vbaProject.bin') worksheet.merge_range('A1:DD1', 'xStack: Exported Data - Loyola-ICAM College of Engineering and Technology', ...
def move(self, move_side, move_type=None): repetitions = dict({None: 1, "2": 2, "'": 3})[move_type] if move_side == "R": side_cubies_old = np.array([1, 3, 7, 15, 21, 23, 18, 10]) face_cubies_old = np.array([[8, 9], [16, 17]]) elif move_side == "L": side_cubie...
The main task of the code is to execute a given action by moving the cube, update the cube's state and reduced representation, calculate the reward and termination status, and return the observation, reward, done flag, and additional information for reinforcement learning training. It also tracks step count and resets ...
def step(self, action): move = ACTION_MAP[action] self.move(move[0], move[1]) self.update_cube_reduced() self.update_cube_state() reward, done = self.reward() observation = self.cube_state info = {"cube": self.cube, "cube_reduced": self.cube_reduced} ...
def displayCube(self, isColor=False): # Display the Top Portion for i in range(self.order): for j in range(self.order): sys.stdout.write(self.tileChar) for tile in self.up[i]: sys.stdout.write(self.getTileColor(tile[:],isColor)) for j i...
The code defines an interactive client loop that continuously displays a cube (with color option), processes user input via `minimalInterpreter`, and outputs the system's state vector in binary format. The loop repeats indefinitely, enabling real-time interaction and state monitoring.
def client(self, isColor=False): while True: # clearScreen() self.displayCube(isColor=isColor) userString = str(input("\n---> ")) self.minimalInterpreter(userString) print(self.constructVectorState(inBits=True))
def select_piece(self, row, column): pieces = [] if ((self.matrix[row][column] == 'x' or self.matrix[row][column] == 'xq') and self.its_player_x_turn) or ( (self.matrix[row][column] == 'o' or self.matrix[row][column] == 'oq') and not self.its_player_x_turn): piece = self.upda...
The main task of the code is to handle a click event on a game board by determining the appropriate action: selecting a piece, deselecting a piece, or validating a move (with or without capturing an opponent's piece). It returns the relevant piece(s) based on the context of the click, prioritizing selection, then desel...
def handle_click(self, row, column): pieces = self.select_piece(row, column) if pieces.__len__() > 0: return pieces else: pieces = self.deselect_piece(row, column) if pieces.__len__() > 0: return pieces else: pieces ...
def datagen(frames, mels): img_batch, mel_batch, frame_batch, coords_batch = [], [], [], [] print("\r" + " " * 100, end="\r") if args.box[0] == -1: if not args.static: face_det_results = face_detect(frames) # BGR2RGB for CNN face detection else: face_det_results = fac...
This code processes a video or image with accompanying audio to generate a lip-synced video using a model (likely Wav2Lip). It loads input media, extracts frames, resizes/crops them, splits audio into mel-spectrograms, synchronizes frames with audio using batch processing, applies model predictions for lip movement, an...
def main(): args.img_size = 96 frame_number = 11 if os.path.isfile(args.face) and args.face.split('.')[1] in ['jpg', 'png', 'jpeg']: args.static = True if not os.path.isfile(args.face): raise ValueError('--face argument must be a valid path to video/image file') elif args.face.spl...
def mannshitneyu_for_quant_by_target(target_col, training_df, quantitative_col): predictors = {} subsets, combos = combinations_of_subsets(target_col, training_df) p_exceeds_alpha = [] for i, pair in enumerate(combos): #print(f'{pair[0...
The function performs a Mann-Whitney U test on dataset subsets to analyze predictors against a target variable. It prints significant predictors, failing features, and groups predictors by combinations. The output includes subsets, predictors, p-values, and a dictionary mapping combinations to their associated predicto...
def print_quant_by_target(target_col, training_df, quant_col): subsets, predictors, p_exceeds_alpha, combos = mannshitneyu_for_quant_by_target(target_col, training_df, ...
def quantitative_hist_boxplot_describe(training_df, quantitative_col_names,separate=True): plots, fig = create_subplots(quantitative_col_names) for i, col in enumerate(quantitative_col_names): plots[i].hist(training_df[col]) plots[i].set_xlabel(col) plots[i].set_ylabel('count') plt.s...
Your return The function `overview` performs exploratory data analysis (EDA) on a dataset, generating visualizations (histograms, boxplots, bar charts) and statistical summaries for quantitative variables and their relationships with the target variable. It identifies significant predictors, reduces the dataset using...
def overview(train_df, categories, quant_cols, target_var): quantitative_hist_boxplot_describe(train_df, quant_cols,separate=True) target_freq_hist_count(train_df, target_var) quant_vs_target_bar(train_df, target_var, quant_cols, mean_line=True) describe_quant_grouped_by_target(train_df, qu...
def send(client, msg): message = msg.encode('ascii') msg_length = len(message) msg_length = str(msg_length).encode('ascii') msg_length += b' ' * (1024 - len(msg_length)) client.send(msg_length) client.send(message) def ping(client: socket.socket): send(client, "ping") def server(c: so...
The code acts as a client for a messaging system, connecting to a server via socket. It processes command-line arguments to either subscribe to topics, publish messages, or send a ping. It validates inputs, constructs appropriate commands, sends them over the network, and handles server responses with timeout error han...
def main(): if len(sys.argv) <= 3: print("INVALID INPUT!") sys.exit() if sys.argv[1] == "default": h = '127.0.0.1' else: h = sys.argv[1] if sys.argv[2] == "default": p = 3500 else: p = sys.argv[2] s = socket.socket(socket.AF_INET, socke...
def GetResList(gene,exons_dic): ## Make sure that the exons_dic contains infotmation of target gene if gene in exons_dic: #print gene strand = exons_dic[gene]['strand'] if strand == '+': exon_list = exons_dic[gene]['exons'] else: exon_list = exons_dic[gen...
This function generates a visualization of the CKHS profile and annotations for a specified gene, plotting z-scores, HS regions, exons, conservation scores, domains, secondary structures, and post-translational modifications. It checks gene availability in the database, creates a two-panel figure with customized axes, ...
def Visualization(gene,outputdir,exons_dic,sift_genome_dic,domain_genome_dic,ss_genome_dic,po_dic,ac_dic,me_dic,ub_dic): if gene not in exons_dic: logging.error('The information of ' +Gene +' is not available in the database.' +'Visualization stop... Try another gene alias name') ...
def load_training_data(training_path, limit=None): training_data = [] count = 0 # Loop through all the files in the directory for file in os.listdir(training_path): # Load the image in PIL then turn to NumPy image = load_img(training_path + file, target_size=(416, 416)) image =...
The code's main task is to load and preprocess training data, then create a neural network model using the data's shape. It reads labels, loads limited training data, preprocesses it, checks the input dimensions, and initializes a model compatible with those dimensions for machine learning tasks.
def main(): datapath = 'data/training_data/training_data/' labels = pd.read_csv('data/training_labels.csv')['label'].unique() #print(labels) # Load the data training_data = load_training_data(datapath, limit=100) preprocess_data(training_data) print(training_data[0].shape) create...
def retrieve(self, option, where): """_summary_ This method searches all over self.dict and self.defaults so it can get the direct match about that option, so it can be retrieved for validating it to the current attribute. Args: option (Option): The option...
The main task of the code is to aggregate and format settings from either provided dictionary entries or default settings into a structured dictionary with "native" and "plain" lists. It iterates through options, checks for existing settings, processes nested AppSettings objects, converts values using specialDict or sp...
def getSettings(self): all = { "native": [], "plain": [] } for option in self.options: sdict = self.retrieve(option, self.dict) sdef = self.retrieve(option, self.defaults) if sdict is not None: all['native'].append(sdict...
def prepare_blocks_vocab(data_dir, trace_file, vocab_file, vocab_freq, segment_size): """Create vocabulary file (if it does not exist yet) from trace file. Vocabulary contains the most-frequent tokens up to vocab_freq size. We write it to vocabulary_path in a one-token-per-line format, so that later token in t...
The main task of the code is to process a trace file into sequences of block operations (read/write) grouped by time windows (max_win_ms). It generates sequences of block IDs with operation types (R/W), filters blocks based on access frequency, and writes them to files. The code also creates reduced sequences by halvin...
def prepare_block_sequences(datadir="dataset", trace_file="Financial1.spc", vocab_freq=5, max_win_ms=1024, segment_size=524288): ''' Reads a trace file and creates sequences (sequences of block Ids) of blocks that were read or written less than max_win_ms apart. If a block is read or written after max_win millise...
def have_ipython(): # IPython has started being obnoxious on import, only import # if absolutely needed. # https://github.com/ipython/ipython/issues/9435 try: import IPython # Access a property to verify module exists in case # there's a demand loader wrapping module imports ...
This function determines which version of the IPython shell to execute based on the availability of the 'Shell' attribute in the IPython module. If IPython is present and has the 'Shell' attribute, it calls the v10 implementation; otherwise, it uses the v11 version, passing the provided global and local namespaces to b...
def run_ipython_shell(globals, locals): import IPython if have_ipython() and hasattr(IPython, 'Shell'): return run_ipython_shell_v10(globals, locals) else: return run_ipython_shell_v11(globals, locals)
def chooseShooterUnit(self, listToShoot): idx_shooter = randint(1, len(listToShoot)) - 1 return listToShoot[idx_shooter], idx_shooter def chooseReceiverUnit(self, listToReceive): idx_receiver = randint(1, len(listToReceive)) - 1 return listToReceive[idx_receiver], idx_receiver def shooti...
This function simulates a battle round between attacker and defender units. It alternates turns based on random chance, allowing either side to fire at the opposing units. Each turn selects a firing unit and target, executes the attack, and checks if the defender has no remaining units (declaring a winner). The loop co...
def battleround(self, battle_shipsAttack, battle_shipsDefend, defences, shipsToFireAttacker, shipsToFireDefender, defencesToFire): yetToFire = True winner = False unitsToFireAttacker = shipsToFireAttacker unitsToFireDefender = shipsToFireDefender + defencesToFire ...
def is_add(n): return type(n) == ast.BinOp and type(getattr(n,'op',None)) == ast.Add def fold_constant_factors(lst): '''given a list like [[i; 15; 2]; [i; 40]; [i; 80]; 14; [15;2]; [x;5]; [z; 2]; [z;3];] we want to group by / partition the addends into partitions for each distinct set of identical n...
This function processes binary operation nodes in an AST, transforming them into additive/multiplicative component lists for optimization. It handles Add, Sub, Mult, and Pow operations, expanding expressions into nested factor lists, flattening them, and folding constants. The goal is to represent operations as lists o...
def visit_BinOp_dfs(self, node): if is_add(node): node.adds = [] left = getattr(node.left, 'adds', [node.left]) right = getattr(node.right, 'adds', [node.right]) node.adds.extend(left) node.adds.extend(right) node.adds = fold_constant_fact...
def pl(self, *a): '''print with indentation based on current nesting level in the tree''' if self.verbose: print(' '*self.level, end='') for arg in a: print('', pp(arg), end='') print('') def optimizable_range(iterable): '''Looks for sequential ra...
This code processes Python AST nodes to optimize for loops and sum() operations by identifying optimizable ranges, tracking state via StateMachine objects, and replacing original nodes with optimized versions. It handles list comprehensions, generator expressions, and augmented assignments, while logging optimization s...
def generic_visit(self, node): self.node_id += 1 # our unique ID for this node if self.states and node is self.states[-1].node_iter: # (relevant for list comprehensions where the range() is inside # the expression to be optimized) self.pl('skipping our own range', no...
def normalize_workdir_path(workdir): '''Checks that we get a string for the workdir argument and removes trailing slashes''' if not isinstance(workdir, str): exit_with_error("Need to pass string for workdir but reveiced " + str(type(workdir))) return workdir.rstrip(os.sep) def get_baselines_from_pat...
This function lists all submodules and their associated baselines in a given directory, primarily for debugging or repository analysis. It normalizes the input path, retrieves baseline data, validates it, and logs errors if invalid.
def listsubmodules(workdir): '''Lists all submodules and their respective baselines. Meant for debugging and/or repo analysis.''' workdir = normalize_workdir_path(workdir) baselines = get_baselines_from_path(workdir, 0, False)[0] if not baselines_are_valid(baselines): logger.error("Invalid ...
def normalize_workdir_path(workdir): '''Checks that we get a string for the workdir argument and removes trailing slashes''' if not isinstance(workdir, str): exit_with_error("Need to pass string for workdir but reveiced " + str(type(workdir))) return workdir.rstrip(os.sep) def get_baselines_from_pat...
The function `showbaselines` lists available baselines in a specified directory and validates their consistency across submodules. It normalizes the input path, retrieves baseline data, checks validity, and logs results. If invalid, it reports an error; if valid, it lists the baselines or indicates none were found.
def showbaselines(workdir): '''Lists all available baselines and checks the repo vor validity (e.g. all submodules contain the same ordered set of baselines).''' workdir = normalize_workdir_path(workdir) baselines, order = get_baselines_from_path(workdir, 0, True) if not baselines_are_valid(baselin...
def normalize_workdir_path(workdir): '''Checks that we get a string for the workdir argument and removes trailing slashes''' if not isinstance(workdir, str): exit_with_error("Need to pass string for workdir but reveiced " + str(type(workdir))) return workdir.rstrip(os.sep) def get_baselines_from_pat...
The function reverts a Git repository to the commit immediately before a specified baseline, removing subsequent commits and the baseline itself. If 'all' is True, it identifies the oldest baseline and resets to its prior commit. The 'clean' flag optionally removes untracked files. It validates baseline existence, hand...
def reverttobaseline(workdir, baseline, all, clean): '''Sets the repository structure to the commit before the one marked by the baseline (removing all later commits and the baseline commit).''' workdir = normalize_workdir_path(workdir) baselines = get_baselines_from_path(workdir, 0, True)[0] if al...
def normalize_workdir_path(workdir): '''Checks that we get a string for the workdir argument and removes trailing slashes''' if not isinstance(workdir, str): exit_with_error("Need to pass string for workdir but reveiced " + str(type(workdir))) return workdir.rstrip(os.sep) def get_baselines_from_pat...
The function generates patchsets from a repository by creating individual patches for commits between baselines. Each patchset starts at a baseline, includes all subsequent commits until the next baseline, and links baselines as parent-child pairs. It validates baseline configurations, creates output directories, extra...
def createpatches(workdir, outpath, includebaseline): '''Walks through repo and creates patches and patchset configurations For each found baseline. Each patchset starts at the baseline - taking its name - and contains all commits as single patches until the next baseline. Each baseline has the...
def input_co2(input): inputnp = np.array(input["co2"]) input = inputnp[:, np.newaxis] scaler_data = joblib.load("./model/scaler_co2.gz") scaler = MinMaxScaler() scaler.min_, scaler.scale_ = scaler_data.min_[0], scaler_data.scale_[0] scaled_inputs = scaler.transform(input) predictions_descale...
The function `predict()` processes JSON input data to predict CO2, temperature, and humidity values. It serializes input and prediction data into JSON, stores them in an SQLite database with timestamps, and returns "Done". The task involves data parsing, prediction generation, and database logging for environmental mon...
def predict(): input = request.json prediction_co2, input_json_co2 = input_co2(input) prediction_temp, input_json_temp = input_temp(input) prediction_hum, input_json_hum = input_hum(input) data_json_co2 = {"co2": prediction_co2.tolist()} data_json_temp = {"temp": prediction_temp.tolist()} ...
def get_input(filename: str) -> list[str]: input = [] with open(filename) as file: input = file.read().strip().split("\n") return input def calc_power_consumption(diagnostics): line_length = len(diagnostics[0]) result = [] for i in range(line_length): current_bit = [line[i] for l...
The code processes diagnostic data from a file to calculate two values: the power consumption (Part One) using gamma and epsilon rates, and the life support rating (Part Two) by determining oxygen and CO₂ scrubber ratings. It reads input, executes both calculations, and prints results.
def main(): diagnostics = get_input("./day3_input") print("Part One\n") calc_power_consumption(diagnostics) print("\nPart Two\n") calc_life_support_rate(diagnostics)
def parse_input(filename: str): input = [] with open(filename) as file: input = file.read().strip().split("\n\n") drawn_numbers = input[0].split(",") boards = [b.split("\n") for b in input[1:]] return drawn_numbers, parse_boards(boards) def win_first(drawn_numbers: list[str], boards: Boards...
The code's main task is to solve two parts of a problem involving Bingo-style number drawing. It parses input data containing drawn numbers and boards, then calculates the score of the first board to complete (Part One) and the score of the last board to complete (Part Two) as numbers are drawn sequentially.
def main(): drawn_numbers, boards = parse_input("./day4_input") print("Part one\n") win_first(drawn_numbers, boards) print("\nPart two\n") let_him_win(drawn_numbers, boards)
def get_input(filename): input: list[int] = [] with open(filename) as file: input = [int(i) for i in file.read().strip().split("\n")] return input def part_one(depths): increased = increased_comprehension(depths) print(f"The number of times a depth measurement increases is: {len(increased)}"...
The main task of the code is to process input data for two parts of a problem. It reads depth measurements from a file, then executes `part_one()` to solve the first subtask and `part_two()` for the second, printing results for each section. The code structure separates logic for distinct computational tasks while reus...
def main(): depths = get_input("./day1_input") print("Part one\n") part_one(depths) print("\nPart two\n") part_two(depths)
def make_blobs(mask): bs, h, w, parts = mask.shape.as_list() means, variances = localize(mask, softmax=False, centered=False) means = tf.stack(means, axis=-1) variances = [tf.reshape(v, (bs, -1)) for v in variances] variances = tf.stack(variances, axis=-1) # variances *= 1e-1 part_heatmaps =...
This code defines a neural network graph for a variational autoencoder (VAE) with latent variable modeling, mask-based feature reconstruction, and mutual information estimation. It creates input placeholders, encoders/decoders for latent variables (z0, z1) and appearance features, generates masks via decoders, reconstr...
def define_graph(self): # input placeholders self.views = list() for view_idx in range(2): v = tf.placeholder( tf.float32, shape=( self.config["batch_size"], self.config["spatial_size"], self....
def _is_legal_move(board, row, col, player): ''' board (list): an object created by board_create() row (int): the row coordinate of the proposed move. col (int): the column coordinate of the proposed move. player (int): HUMAN or COMPUTER Return True if a given move is legal. ''' if boar...
The main task of the code is to handle a turn in a two-player board game, placing the human player's piece at specified coordinates if the move is legal, flipping opponent's pieces, then allowing the computer player to make a move and flip the human's pieces. It returns True if the human's move was legal, otherwise Fal...
def game_turn(board, row, col): ''' board (list): an object returned by board_create() row (int): The row coordinate where the piece should be placed. col (int): The column coordinate where the piece should be placed. Place the human player's piece on the board at the coordinates row, col. ...
def _language_mapping(self, language): assert isinstance(language, list) mapping = self.provider.get_language_mapping() if mapping is None: return language return [ mapping.get(i,i) for i in language ] def _country_mapping(self, countries): assert isinstance(countries, list) mapping = self.provider.get_c...
The main task of the code is to retrieve and filter sources from a provider based on input parameters. It maps input lists (countries, categories, language) to internal representations using helper methods, then calls the provider's sources method with these mapped values. The result is processed by `_sourcesset()` bef...
def sources(self, countries=[], categories=[], language=[]): language = self._language_mapping(language) countries = self._country_mapping(countries) categories = self._category_mapping(categories) ret = self.provider.sources(countries=countries, categories=categories, language=language) return ...
def _language_mapping(self, language): assert isinstance(language, list) mapping = self.provider.get_language_mapping() if mapping is None: return language return [ mapping.get(i,i) for i in language ] def _country_mapping(self, countries): assert isinstance(countries, list) mapping = self.provider.get_c...
This method fetches the latest news articles based on optional filters like query, language, countries, categories, domains, and sources. It maps input parameters to internal formats, calls a provider's `last_news` method, processes the raw response into a structured `NewsSet` object, and returns it. The `page` paramet...
def last_news(self, q=None, language=[], countries=[], categories=[], domains=[], sources=[], page=1): language = self._language_mapping(language) countries = self._country_mapping(countries) categories = self._category_mapping(categories) ret = self.provider.last_news(q=q, language=l...
def _language_mapping(self, language): assert isinstance(language, list) mapping = self.provider.get_language_mapping() if mapping is None: return language return [ mapping.get(i,i) for i in language ] def _country_mapping(self, countries): assert isinstance(countries, list) mapping = self.provider.get_c...
This method retrieves historical news articles based on filters like query, language, country, category, source, domain, and date range. It maps input parameters to internal formats, delegates the request to a provider, and returns processed news data as a structured set.
def hist_news(self, q=None, language=[], countries=[], categories=[], sources=[], domains=[], from_date=None, to_date=None, page=1): language = self._language_mapping(language) countries = self._country_mapping(countries) categories = self._category_mapping(categories) ret = self....
def nextQnParamRnd( method, paramFixMu, paramFixCh, paramFixSi, paramRndMu, paramRndCh, paramRndSi, mjiAux, xFix, nFix, xRnd, nRnd, chRndIdx, chRndIdxDiag, drawsFix, drawsRnd, nDraws, nInd, nRow, obsPerInd, rowsPerInd, rowsPerObs, map_obs_to_ind,...
This function performs coordinate ascent variational Bayes (CAVI) to estimate parameters of a probabilistic model with fixed and random components. It iteratively updates parameters (mu, Sigma) for fixed and random variables using QN or NCVMP methods, computes auxiliary variables, and checks convergence based on parame...
def coordinateAscent( method, vb_iter, vb_tol, paramFixMu, paramFixCh, paramFixSi, paramRndMu, paramRndCh, paramRndSi, mjiAux, xFix, nFix, chFixIdx, chFixIdxDiag, xRnd, nRnd, chRndIdx, chRndIdxDiag, drawsFix, drawsRnd, nDraws, nInd, nObs, nRow, o...
def pseudoRandom(nSeq, nDim): seq = np.random.rand(nSeq, nDim) return seq def mlhs(nSeq, nDim): seq = np.empty((nSeq, nDim)) h = np.arange(nSeq) for i in np.arange(nDim): d = h + np.random.rand() seq[:, i] = d[np.random.choice(nSeq, size = nSeq, replace = False)] seq /= nSeq ...
The function `makeUniformDraws` generates uniform random draws across multiple sequences, dimensions, and independent trials using specified methods (e.g., pseudo-random, Latin Hypercube, Halton). It returns both the original 3D array of draws and a reshaped 2D matrix, facilitating analysis or simulation tasks requirin...
def makeUniformDraws(nSeq, nDim, drawsType, nInd = 1): drawsArr = np.zeros((nInd, nSeq, nDim)) for n in np.arange(nInd): if drawsType == "pseudoRandom": drawsArr[n,:,:] = pseudoRandom(nSeq, nDim) elif drawsType == "mlhs": drawsArr[n,:,:] = mlhs(nSeq, nDim) elif dr...
def entropy(data): total_ex = len(data) positive_ex = len(data.loc[data["Play Tennis"] == 'Y']) negative_ex = len(data.loc[data["Play Tennis"] == 'N']) entropy = 0 if(positive_ex > 0): entropy = (-1)*(positive_ex/float(total_ex))*(math.log(positive_ex,2)-math.log(total_ex,2)) if(negative_ex > 0): entropy += (...
This function constructs a decision tree by recursively splitting data based on attribute entropy. It starts with a root node, checks for pure data (zero entropy) to assign labels, selects attributes for splitting, and creates branches for each attribute value, recursively building subtrees until no attributes remain o...
def decision_tree(data): root = Node("NULL") if(entropy(data) == 0): if(len(data.loc[data[data.columns[-1]] == 'Y']) == len(data)): root.label = "Y" return root else: root.label = "N" return root if(len(data.columns) == 1): return else: attrib = get_attrib(data) root.label = attrib value...
def init_params(): global keywords_array global games_array global twitter_bearer_token global url global path #keywords_array = ["lag ","ping (-pong) ","slow ","internetdown ","freeze (-cold) (-ice) ", # "packetloss ","internet ","poorservers ","delay ","internetsucks "] ...
The main task of the code is to initialize parameters, generate combinations of search queries, and collect tweets using those queries. The `main()` function orchestrates tweet collection by first setting up necessary parameters, creating varied query combinations, and passing them to the `tweet_collector` function for...
def main(): init_params() keywords_list = create_queries_combinations() tweet_collector(keywords_list)
def get_parser() -> argparse.ArgumentParser: """ Parse command line arguments. Returns: argparse.ArgumentParser: Argument parser. """ parser = argparse.ArgumentParser(description='Segment images using nnUNet') parser.add_argument('--path-dataset', default=None, type=str, ...
The main task of the code is to perform inference using a pre-trained nnU-Net model on medical imaging data, either from a dataset folder or specific image files. It handles input validation, data preparation, model initialization, and prediction execution, saving results to a specified output directory while allowing ...
def main(): """ Main function to run the script. """ parser = get_parser() args = parser.parse_args() if not os.path.exists(args.path_out): os.makedirs(args.path_out, exist_ok=True) if args.path_dataset is not None and args.path_images is not None: raise ValueError('You can...
def clean_model_summary(filepath): if not filepath.is_file(): print(f"This file does not exist: {filepath}") return None else: clean_lines = [] # Parse the MLTK model summary to grab important metrics with open(filepath, "r", encoding="latin-1") as f: li...
The function parses a TensorFlow Lite benchmarking text file to generate three DataFrames: operator execution order, computation time ranking, and node type summary, aiding performance analysis of machine learning models.
def get_profiling_dataframes_cpu(filepath, model_name): """ Parse "bechmarking.txt" file that has been generated from a .tflite model with TensorFlow benchmarking tool. The native benchmark binary for linux is available from this page: [https://www.tensorflow.org/lite/performance/measurement](https...
def process(file_path: str, filename: str, arg_counter: ArgCounter): """ :param file_path: :param filename: :param arg_counter: :return: """ text_lines = read_input_text(file_path) input_text = ''.join(text_lines) spacy_scores, spacy_syntax_results, spacy_phrase_results = process_sp...
The main task of the code is to process text input (file or directory) using an ArgCounter to analyze argument patterns, generate results, and output them as a CSV report. It checks the input type, processes each text file, aggregates scores, formats data, and writes a structured CSV file with headers and results, hand...
def main(input_path): input_filepath = os.path.join(os.getcwd(), input_path) mode = check_mode(input_filepath) ac = ArgCounter('arg_counter/word_list.txt') if mode == 'file': result = process(input_path, Path(input_path).name, ac) print(f"Results for {result['scores']['filename']}") ...
def solve_ode(method, f, t, X0, use_method_dict=True, **params): """ Solves an ODE from an initial value, t_0 to a final value t_end Parameters: method :(str or function) Numerical method to use f : (function) The ODE to be solved t_values : (array) time values X0 : (numpy ar...
The code solves first and second-order ODEs using the midpoint method and other numerical techniques, compares numerical solutions to true solutions (e.g., exp(t)), visualizes results with plots, and evaluates method accuracy by computing errors and checking tolerance levels. It demonstrates ODE-solving workflows, erro...
def main(): t = np.linspace(0,1,100) X0 = [1] X = solve_ode('midpoint', f, t, X0, dt_max=0.1) plot_solution(t, X, 't', 'x(t)', 'First Order ODE Solution', X_true=exp(t)) t = np.linspace(0,10,30) X0 = [0,1] X = solve_ode('midpoint', g, t, X0) plot_solution(t, X[:,0]...
def cleanPromptsPoemsOld(data_poem, data_p2i): """ """ data_p2i_nws = data_p2i for sub_data, sub_data_nws in zip(data_p2i, data_p2i_nws): poem_id = sub_data["id"] old_prompt = sub_data["prompt"] temp_prompt = old_prompt.split("\"", 1) #Fix corrupted img paths t...
The main task of the code is to consolidate and process JSON data containing poems, prompts, and image metadata. It reads multiple input files, cleans and normalizes poem text, merges processed entries into two structured datasets, and writes them to new JSON files. The code handles whitespace normalization, ID trackin...
def main(): data = { "info": "Stores image location, prompt used to generate, and poem together", "poem2img": [] } data_nws = { "info": "Stores image location, prompt used to generate, and poem together. NO XTRA WHITE-SPACES", "poem2img": [] } with open("data/train_...
def fit_knn(xtrain,xval,ytrain,yval,stratified_splitter): from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier(n_jobs=-1) params = {'n_neighbors':range(2,4),'metric':['minkowski','euclidean']} scoring = {'Precision':'precision','Accuracy':make_scorer(accuracy_score),'AUC'...
The main task of the code is to fit and evaluate multiple classification models (KNN, Logistic Regression, SVM, Random Forest, Decision Tree, GaussianNB) on training and validation datasets. It uses stratified splitting, stores model instances and performance metrics in dictionaries, and returns both. Logistic Regressi...
def model_fitter(xtrain,ytrain,xval,yval): print("\n\n<<<<FITTING CLASSIFICATION MODELS>>>>\n\n") from sklearn.model_selection import StratifiedShuffleSplit stratified_splitter = StratifiedShuffleSplit(test_size=0.2,random_state=101) """Results are dictionaries which contains the model type(knn,linear ...
def emb_subnetwork(self, x): for l in range(self.emb_layer_num): x = self.default_conv(x) return x def recursive_subnetwork(self, x): layer = self.default_conv_layer() y = x outp = y for l in range(self.recursive_layer_num_in): y = layer(y) ...
This code constructs a neural network model for sequence processing. It defines an input layer, applies an embedding subnetwork, processes data through multiple recursive layers, and outputs via a convolutional layer. The model is compiled with Adam optimizer and categorical crossentropy loss for training.
def construct(self): inp = Input(shape=(None, self.utt_in_dim)) all_y = [] x = inp x = self.emb_subnetwork(x) for i in range(self.recursive_layer_num_out): x = self.recursive_subnetwork(x) x = self.out_conv(x) outp = x self._net = Model(inputs=...
def parse_file( self, file_path: str, imports=None ) -> Tuple[ast.AST, Dict[str, str]]: """ Parses a Python file and returns the AST and a dictionary of imported module names and aliases. Args: file_path (str): The path to the Python file to parse. Returns: ...
This function parses the main function in a Python file to identify and process its function calls and branches, using AST analysis. It locates the "main" function, adds participants, and processes function calls and control flow branches within it, leveraging parsed imports for context.
def parse_main_function(self, file_path): """Parses the main function in the given Python file for function calls. Args: file_path (str): The path to the Python file to analyze. """ tree, imports = self.parse_file(file_path) main_function_node = None for no...
def msgSurface (texte): GOTexte = pygame.font.Font('BradBunR.ttf', 75) petitTexte = pygame.font.Font('BradBunR.ttf',20) titreTexteSurf, titreTexteRect = creaTexteObjs(texte, GOTexte) titreTexteRect.center = surfaceW/2,((surfaceH/2)-50) surface.blit(titreTexteSurf, titreTexteRect) petitTexteSur...
The code implements a multiplayer game where players control a bottle to collect glasses within a time limit. It tracks scores, handles player turns, and uses Pygame for rendering, input, and timing. The game progresses through teams and players, resetting score and displaying messages when targets are met, with a game...
def main(): game_over = False while not game_over: i = 1 j = 1 nbre_equipe = 2 nbre_joueur = 3 x=350 y=50 y_move=0 x_verre = randint(10,300) y_verre =250 #espace = bouteilleH*3 score_actuel = 0 start_ticks=pyga...
def modelMultiScaleDiscriminator(self, name=None): x1 = Input(shape=self.img_shape) x2 = AveragePooling2D(pool_size=(2, 2))(x1) #x4 = AveragePooling2D(pool_size=(2, 2))(x2) out_x1 = self.modelDiscriminator('D1')(x1) out_x2 = self.modelDiscriminator('D2')(x2) #out_x4 = se...
This code initializes a CycleGAN model with configurable hyperparameters, setting up discriminators (D_A, D_B) and generators (G_A2B, G_B2A) for image-to-image translation. It compiles models with cyclic loss, adversarial loss, and optional identity/supervised losses, prepares data loaders, configures GPU settings, and...
def __init__(self, lr_D=2e-4, lr_G=2e-4, image_shape=(256*1, 256*1, 1), date_time_string_addition='_test', image_folder='mrict'): self.img_shape = image_shape self.channels = self.img_shape[-1] self.normalization = InstanceNormalization # Hyper parameters self.la...
def analyze_tweet_sentiment(tweet): """ Return a sentiment representing the degree of positive or negative sentiment in the given tweet, averaging over all the words in the tweet that have a sentiment value. If no words in the tweet have a sentiment value, return make_sentiment(None). >>> posi...
The code calculates the average sentiment value of a list of tweets by analyzing each tweet's sentiment, summing valid sentiment values, and dividing by the count of valid sentiments. If no valid sentiments are found, it returns None.
def tweets_average_sentiment(tweets): total, count = 0, 0 for t in tweets: sentiment_of_t = analyze_tweet_sentiment(t) if has_sentiment(sentiment_of_t): count += 1 total += sentiment_value(sentiment_of_t) if count > 0: return to...
def group_tweets_by_state(tweets): """Return a dictionary that aggregates tweets by their nearest state center. The keys of the returned dictionary are state names, and the values are lists of tweets that appear closer to that state center than any other. tweets -- a sequence of tweet abstract data ty...
The code visualizes the sentiment of tweets containing a specified term by mapping average state-level sentiments and plotting individual tweet sentiments as dots on a map. It loads tweets, groups them by state, calculates average sentiments per state, draws the state sentiment map, and overlays individual tweet locati...
def draw_map_for_query(term='my job'): """Draw the sentiment map corresponding to the tweets that contain term. Some term suggestions: New York, Texas, sandwich, my life, justinbieber """ tweets = load_tweets(make_tweet, term) tweets_by_state = group_tweets_by_state(tweets) state_sentiments...
def get_gradients_at_layers(model, layer_index_list, no_of_nodes, image): ''' The function get a list of layers, samples a number of nodes from each of the layers and returns the gradients of these nodes with respect to the input layer of the model evaluated on image. Input: model: the model on whic...
This function computes saliency maps for specified layers and nodes in a neural network model using gradients from a given image. It then fits covariance error ellipses to each saliency map, scaled by standard deviations. The output includes structured arrays of saliency maps and corresponding ellipse objects for each ...
def get_saliency_maps_and_fitted_ellipses(model, layers_index_list, no_of_nodes, image, scale_in_std = 3): ''' The main api procedure to call when fitting covariance error ellipses to saliency maps. It receives a model, the layers saliency is to be calculated and the number of nodes to be sampled from each ...
def change_state(self, pac_man): self.patrol_chase_interchange(pac_man) self.respawn_if_defeated() def execute_states(self, walls, pac_man): self.set_speed() current_pos = self.get_current_tile() # Update the plan if (self.current_state == GhostState.CHASE): ...
This code updates a ghost's behavior in a game by changing its state based on Pac-Man's position, executing movement logic while avoiding walls, animating its appearance, and checking if it has eaten Pac-Man, likely triggering game-over conditions.
def update(self, walls, pac_man): self.change_state(pac_man) self.execute_states(walls, pac_man) self.animate() self.eat_pac_man(pac_man)
def _get_goal_pose(self, robot): """Determines the goal pose for the given command.""" current_pose = robot.get_current_pose(base=self._reference_frame if self._reference_frame else "prbt_base") if self._relative: self._goal = _pose_relative_to_absolute(current_pose, self._goal) ...
The main task of the code is to convert a given command into a `MotionPlanRequest` object for robotic motion planning. It sets parameters like planner ID, group name, velocity/acceleration scaling, and planning time, then constructs goal constraints based on the input command type (Cartesian pose or joint values). The ...
def _cmd_to_request(self, robot): """Transforms the given command to a MotionPlanRequest.""" req = MotionPlanRequest() # Set general info req.planner_id = self._planner_id req.group_name = self._planning_group req.max_velocity_scaling_factor = self._vel_scale req...
def prijetnum_clustering(tx,y=None,jetcol=22): """ Clusters the data into four groups, according to their PRI_jet_num value. PRI_jet_num is found in column 22, can change if needed. Input : tx, y (training set and target), or only tx (test_set) Output : split dataset (clusters) of tx0 to tx3 Add...
The code preprocesses a training dataset by clustering data based on `PRI_jet_num`, applying logarithmic transformations to specific features, removing columns with all `-999` values, replacing remaining `-999` entries with a specified statistic (median by default), and standardizing the data. It splits the dataset int...
def cluster_preprocessing_train(tx_train,y, f="median"): """ Pre-process whole training dataset. Clusters them w.r.t. PRIjetnum, applying log to wanted features, Removing features with all -999 rows, replacing remaning -999 values with f (median by default) Standardizes and returns all sets, targets, an...
def prijetnum_clustering(tx,y=None,jetcol=22): """ Clusters the data into four groups, according to their PRI_jet_num value. PRI_jet_num is found in column 22, can change if needed. Input : tx, y (training set and target), or only tx (test_set) Output : split dataset (clusters) of tx0 to tx3 Add...
The function preprocesses test data by clustering it based on PRI_jet_num, applying logarithms to specific features, removing columns with all -999 values, replacing remaining -999s with mean/median, standardizing using training set statistics, and augmenting features with polynomial expansions. It returns four preproc...
def cluster_preprocessing_test(tX_test, id_del0, id_del1, id_del2, id_del3, means, stds, degs,f="median"): """ Pre-process whole training dataset. Clusters them w.r.t. PRIjetnum, applying log to wanted features, Removing features with all -999 rows, replacing remaning -999 values with f (mean by default) ...
def __connect(self): with connect() as conn: conn.autocommit = True return conn def __getquery(self): with open('query.json') as file: return json.load(file) def __run(self): self.__extensioninit() self.__tableinit() self.__close()
The code initializes a database connection, creates a cursor for query execution, retrieves data using a private method, and triggers a run method to process the data, likely for database operations or data handling tasks.
def __init__(self): self.con=self.__connect() self.cur=self.con.cursor() self.data=self.__getquery() self.__run()
def seed_everything(seed=42): os.environ['PYTHONHASHSEED'] = str(seed) random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) def get_tfrec_dataset(tfrecords, batch_size=64, max_len=64, drop_remainder=False, augment=False, shuffle=False, repeat=False): # Initialize dataset with TFRecords ...
The main task of the code is to train a deep learning model on a specific fold of the dataset using mixed precision, custom learning rate scheduling, and regularization techniques. It prepares training/validation datasets, configures the model architecture, applies optimization strategies (like FGM/AWP), trains the mod...
def train_fold(CFG, fold, train_files, valid_files=None, strategy=STRATEGY, summary=True): seed_everything(CFG.seed) tf.keras.backend.clear_session() gc.collect() tf.config.optimizer.set_jit(True) if CFG.fp16: try: policy = mixed_precision.Policy('mixed_bfloat16') ...
def establish_new_connection(self): self.LOGGER.info(f'Attempting to establish a new connection') try: connection = connection_handler.establish_connection() self.cnx = connection[0] self.cursor = connection[1] except Exception as e: self.LOGGER.de...
The code checks if a person exists in the database using their details. If found, it updates the person data and creates an entry; if not, it creates a new person. It handles exceptions during database queries and uses `create_person` or `new_person` methods based on existence, ensuring data is either retrieved or adde...
def check_exists_or_create(self, person): print("--Checking if person exists, or creating!--") self.establish_new_connection() try: self.cursor.execute(queries.check_for_person(person[0], person[1])) except Exception as e: print("Exception has occured 50: " + str(...
def remove_bad_chars(self, phrase): bad_chars = [';', ':', '!', "*", "?"] for i in bad_chars: phrase = phrase.replace(i, '') return phrase def teach_phrase(self): self.phrase = input( f"What new phrase would you like to teach me?") if self.check_if_known...
This code initializes an object to process a phrase by converting it to lowercase, removing unwanted characters, and splitting it into words. It checks if the phrase is a question or the word "teach," then triggers specific methods (teach_phrase or get_question_format) or labels it as a statement. The main task is to p...
def __init__(self, phrase="None", person="None", person_manager="None"): self.person = person self.person_manager = person_manager lower_phrase = phrase.lower() result = lower_phrase.find("?") self.new_phrase = self.remove_bad_chars(lower_phrase) self.parsed_phrase = self...
def userSearch(conn, email, type): c = conn.cursor() c.execute('SELECT * from requests where email=? COLLATE NOCASE;', (email,)) requests = c.fetchall() makeSelection(conn, email, requests, type) def searchByLcode(conn, email, lcode, type): c = conn.cursor() c.execute('SELECT * from requests whe...
This function allows a user to search for requests either by their own (option 1), by location code (option 2 with suboption 1), or by city (option 2 with suboption 2). It prompts the user for input, validates choices, and delegates to helper functions like `userSearch`, `searchByLcode`, or `searchByCity` based on the ...
def search(conn, email): searchOp = input("Enter 1 to search your requests and 2 to search by location or q to go to the main page: ") # search user's requests if searchOp == '1': userSearch(conn, email, searchOp) # search by location elif searchOp == '2': isLcode = input("Enter 1 to...
def setup_libraries() -> None: """ Set up the libraries to be used in the project. :return: None """ warnings.filterwarnings('ignore') os.environ['TORCH'] = torch.__version__ print(f"Currently running with torch version '{torch.__version__}'. " f"This model was last tested succes...
The main task of the code is to orchestrate the preprocessing and training workflow for GraphComm. It sets up libraries, parses command-line arguments, validates file paths, preprocesses input data using external databases, and executes the training script with preprocessed data and biological interaction files to buil...
def main() -> None: """ The main driver function for GraphComm. Handles setting up the libraries, handling command line arguments, and calling the preprocessing and training scripts as requested. :return: None """ # Set up the libraries setup_libraries() # Handle command line arguments...
def load_in_preprocessed_data(preprocessed_folder_path: str) -> (pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame): """ Load in the preprocessed data from the specified folder. :param preprocessed_folder_path...
The code trains a model for cell communication inference (CCI) by loading preprocessed data, generating embeddings from ground truth, calculating communication probabilities using GAT networks, normalizing results, and saving them as a CSV. It integrates Omnipath databases, KEGG pathways, and consensus paths to predict...
def train(preprocessed_folder_path: str, output_folder_path: str, complexes_file_path: str, kegg_pathways_path: str, consensus_path_path: str, omnipath_database_file: str) -> None: """ Train the model using the preprocessed data in the specified folder. :param preprocessed_folder_path: The path t...
def load_rt1( model_key: str = "rt1simreal", checkpoint_path: str = None, load_specs_from_pbtxt: bool = True, use_tf_function: bool = True, batch_time_steps: bool = False, downloads_folder: bool = None, ) -> LoadedPolicy: """Loads a trained RT-1 model from a checkpoint. Args: mo...
The code runs a demonstration of a policy using a preloaded model. It loads the policy if not provided, processes a sequence of images, and performs step-by-step inference, printing actions. The loop executes three steps, using rewards and state tracking, with the final step terminating the process.
def run_demo(policy: LoadedPolicy = None): if policy is None: policy = load_rt1(FLAGS.model_key, FLAGS.checkpoint_path) # Pass in an instruction through the --instructions flag. # The rewards will not affect the inference at test time. images = get_demo_images(output=os.getcwd()) rewards = ...
def init_ca(): global spectra_array global m_process_var spectra_array = np.ndarray(config.SPECTRA_SIZE, dtype=np.uint32, order='C') spectra_array.fill(0) # Create the Process Variable Object m_process_var = PV(config.PV_NAMES[m_adc]) # Printout the information about the Process Variable ...
The main task of the code is to create a graphical user interface (GUI) for analyzing spectral data using Pygame. It allows users to interact with a spectrum display by setting markers, calibrating channels, and viewing real-time parameters like FWHM, area, and centroid. The program processes keyboard/mouse inputs, upd...
def main(): running = True cursor = 0 marker_l_value = 0 marker_r_value = 0 marker_l = False marker_r = False global input_string global acq_status global loaded_spectra pk_area = 0 FWHM = 0 FWHM_percentual = 0 centroid = 0 global e_time global e_time_old ...
def connect(self, retries=1): tries = 0 while tries < retries and self.is_connected() is False: tries += 1 if self.mac_addr is None: self.mac_addr = self.discover() try: self._periph = btle.Peripheral(self.mac_addr) self...
The code connects to a device or service, retrieves its current values, disconnects, and returns the data as a dictionary for further processing or analysis.
def start(self): self.connect(retries=10) current_values = self.read() self.disconnect() return current_values.to_dict()
def create_new_population(self): self.population = [(generate_game_model(), -1) for _ in range(self.population_size)] self.generation = 0 self.generation_stats = [] def train_generations(self, number_of_generations, generations_label, mean_label, median_label, best_label): for _ in range...
The code creates a Pygame training menu with sliders to adjust parameters like population size, crossover/mutation chances, and generation time. It includes buttons for actions such as generating new populations, training generations, viewing/saving/loading models, and plotting results. The menu provides an interface t...
def _train_menu(self): train_menu = pygame_menu.Menu( title="Training", width=self.window.get_width(), height=self.window.get_height(), theme=pygame_menu.themes.THEME_BLUE, ) train_menu.add.range_slider("Population size", self.population_size, [i ...
def play(self): self.main_menu.disable() self.window = pygame.display.set_mode((self.track_image.get_width(), self.track_image.get_height())) running = True drive = Drive(self.window, self.track_image, self.track_border_image, self.car_image, self.car_specification, ...
This code creates a main menu for the "Intelligent Racer 2D" game using pygame_menu, featuring buttons to play, train AI, create/load tracks, and quit. The menu is themed blue, sized to the window, and returns the menu object for display. Each button triggers specific methods like play(), _train_menu(), etc., enabling ...
def _main_menu(self): menu = pygame_menu.Menu( title="Intelligent Racer 2D", width=self.window.get_width(), height=self.window.get_height(), theme=pygame_menu.themes.THEME_BLUE, ) menu.add.button("Play", lambda: self.play()) menu.add.button...
def get_filters_and_index(callset, chrom, start, end): ''' Def: It checks which SNPs (given a chromosome and a start and end index) are biallelic and singletons and computes the count_alleles and the allele_index for those SNPs that are biallelic and not singletons. Input: - callset...
The function `create_nninput` prepares neural network input data by extracting **biallelic SNP genotypes** or **genotype likelihoods** (and optionally a hybrid) from a genomic dataset, filtering out singletons. Depending on `input_type`, it returns **allele counts (AC)** for imputed genotypes, **3-genotype likelihoods ...
def create_nninput(callset, chrom, start_pos_idx, end_pos_idx, pos, input_type, noncall = -1): ''' Def: This function will output the genotype or genotype likelihoods and position array for those SNPs that are biallelic and are not singletons. If genotypes are requested, the missing genotypes ar...
def JacobiMethod(self, tol=EPSILON): L = np.tril(self.A, -1) D = np.diag(np.diag(self.A)) U = np.triu(self.A, 1) D_invert = np.linalg.inv(D) B = np.dot(-D_invert, L + U) F = np.dot(D_invert, self.f) return _solve_iterative_process(self.A, self.f, self.starting_p...
This class initializes a solver for linear systems Ax = f using specified iterative methods (Jacobi, Fixed Point Iteration, Conjugate Gradient). It sets up parameters like the matrix A, vector f, starting point, and method. Depending on the chosen method, it executes the corresponding algorithm, storing the solution, e...
def __init__(self, A, f, method: str = 'Jacobi', starting_point = None, tau: int = None): """ Jacobi, FPI, CG """ self.A = A self.f = f if starting_point == None: self.starting_point = np.zeros(shape=(A.shape[0], 1)) else: ...
def findPrefixPath(baseRequenceList, treeNode): condPats = {} while treeNode != None: prefixPath = [] ascendTree(treeNode, prefixPath) if len(prefixPath) > 1: condPats[frozenset(prefixPath[1:])] = treeNode.count treeNode = treeNode.nextLink return condPats def cre...
The function recursively mines frequent itemsets of sizes 2, 3, and 4 from an FP-tree. It constructs new itemsets by combining prefixes with current items, appends valid itemsets to their respective lists (f2Itemset, f3Itemset, f4Itemset), and recursively processes conditional subtrees to discover all frequent patterns...
def mineTree(rootTree, headerTable, minSup, preFix, f2Itemset, f3Itemset, f4Itemset): bigL = {v[0]:v[1][0] for v in sorted(headerTable.items(), key=lambda p: str(p[1][0]))} for basePat, freq in bigL.items(): newFreqSet = preFix.copy() newFreqSet.add(basePat) if (len(newFreqSet) == 2): ...
def _check_events(self): # responds to keypress for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif(event.type == pygame.KEYDOWN ): self._check_keydown_events(event) elif(event.type ==pygame.KEYUP): ...
The `run_game` method executes the main game loop, continuously checking for events, updating the player's ship, bullets, and aliens, and rendering the game screen. It maintains the game's state by processing inputs, updating game elements, and redrawing the display in a cycle until the game ends.
def run_game(self): # main loop while True: #watch for the events self._check_events() self.ship.update() self._update_bullets() self._update_aliens() self._update_screen()
def random(a, b): if (a > b): return random(b, a) if (a != 0): return a + random(0, b+a) global state result = b + 1 i = state while (result == b+1): result = ((seed ^ b + seed * state ** 3) ^ i) % (b+1) i += 1 state += 1 return result def shuffl...
This code generates a maze-like path using a depth-first search algorithm with backtracking. It starts at a random position in a grid and explores neighboring cells in randomized directions. If a valid, unvisited cell is found, it marks the path and continues recursively. If no valid moves remain, it backtracks. The pr...
def generation(): stack = [[random(0, grid_x), random(0, grid_y)]] moves = [0, 1, 2, 3] while (len(stack) != 0): current = stack[len(stack) - 1] stack.pop(-1) moves = shuffle(moves) for i in moves: mod_x = current[0] + (i % 2) * (1 - 2 * (i > 1)) mod...
def generation(): stack = [[random(0, grid_x), random(0, grid_y)]] moves = [0, 1, 2, 3] while (len(stack) != 0): current = stack[len(stack) - 1] stack.pop(-1) moves = shuffle(moves) for i in moves: mod_x = current[0] + (i % 2) * (1 - 2 * (i > 1)) mod...
The code defines a game loop that initializes game elements, handles quit events, renders a grid of sprites onto a Pygame display surface at 30 FPS, and maintains the loop until the user closes the window. It uses a 2D grid array to determine which sprites to draw at each cell position, updating the screen repeatedly t...
def gameLoop(): game_over = False generation() new_entrance() new_entrance() while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True dis.fill((0, 0, 0)) #Your Code fo...
def get_estimated_end_time(self): return self.get_estimated_remain_time() + time.time() def _hms(diff): hours = int(diff // (60 * 60)) mins = int((diff // 60) % 60) seconds = int(diff % 60) return hours, mins, seconds def get_estimated_total_time(self): avg_time = self.ge...
The main task of the code is to print a formatted summary of time-related metrics, including elapsed time, estimated end time, total estimated time, and remaining time, using hours, minutes, and seconds for each component. It retrieves these values via helper methods, formats them into a structured string, and outputs ...
def print_summary(self): sttime = time.localtime(self.get_estimated_end_time()) th, tm, ts = self._hms(self.get_estimated_total_time()) rh, rm, rs = self._hms(self.get_estimated_remain_time()) eh, em, es = self._hms(self.get_elapsed_time()) print('Elapsed time: {:02d}h-{:02d}m-{:...
def label_leaf(self, data, depth): c1 = len(data.query("target == 1.0")) c0 = len(data.query("target == 0.0")) total = len(data) if depth >= self.max_depth: return True, 1 if c1 > c0 else 0 elif (c0 / total) >= self.threshold: return True, 0 elif (...
This function constructs a decision tree recursively by selecting the feature with maximum information gain. It creates leaf nodes if data is pure, otherwise splits data based on feature type (continuous/categorical) and thresholds/values, generating child nodes and updating the tree structure with appropriate splits a...
def make_tree(self, data, not_used_features, depth, node): labeled, class_type = self.label_leaf(data, depth) if labeled: node["class"] = class_type node["type"] = "leaf" return node else: features_info_gain, t = self.calculate_info_gain(data, not_...
def Hamiltonian_Monte_Carlo(q0, m, N, T, eps, alpha): # implementation of the Hamiltonian Monte Carlo algorithm q = np.zeros([N+1, 2]) q[0, :] = q0 accepted = 0 rejected = 0 for i in range(N): p = st.norm.rvs(loc=0, scale=np.sqrt(m)) q_star, p_star = Verlet(q[i, :], p, eps, T, alpha,...
The code compares Hamiltonian Monte Carlo (HMC) and Metropolis-Hastings (MH) sampling methods by running both algorithms multiple times, storing their trajectories and final states. It computes statistical properties (mean, variance, autocorrelation, effective sample size) of the samples, visualizes 2D histograms of di...
def main(): # used to test the first implementations, not used to produce the graphs in the report q0 = [0.0, 0.0] eps = 0.01 alpha = 10**3 m = [1, 1] T = 0.1 N = 100 sigma = 0.4 n = 1000 final_q = np.zeros([n, 2]) final_q_ham = np.zeros([n, 2]) ratio = np.zeros(n) ...
def worker(cnn_config_file: str, graphlib_file: str, cnn_models_dir: str, accel_models_dir: str, cnn_model_hash: str, chosen_neighbor_hash: str, autotune: bool, trained_cnn_hashes: list, accel_emb: np.array, accel_hash: str): """Worker to finetune or pretrain the given model Args: cnn_config_file (str...
The main task of the code is to optimize the co-design of CNN models and accelerators using the BOSHCODE algorithm. It searches the design space to identify the best CNN-Accelerator pair by iteratively training models, evaluating performance metrics, and leveraging a surrogate model for efficient exploration. The code ...
def main(): """Run BOSHCODE to get the best CNN-Accelerator pair in the design space """ parser = argparse.ArgumentParser( description='Input parameters for generation of dataset library', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--fix', metavar='', type=str, help='to f...
def LastCheck(self): try: self.request = requests.get(self.adress) self.data = json.loads(self.request.content.decode()) date=self.data['Day'] if date=="": month=datetime.now().month day=datetime.now().day date=str(m...
The code initializes an application by loading a refresh token from a file, exchanges it for authentication credentials, fetches user data from Firebase, populates UI elements with the data, and transitions to the schedule screen. Error handling suppresses exceptions during the process.
def on_start(self): try: with open("kv/refreshToken.txt", "r") as save_file: refreshToken = save_file.read() self.id_token, self.local_id = self.database.exchange_refresh_token(refreshToken) self.request = requests.get( 'https://todo-list-737ca...
def parse_flag(flag, cigar): # 1st or 2nd read in a pair, both false if single end pair1 = (flag & 1 != 0) and (flag & 64 != 0) pair2 = (flag & 1 != 0) and (flag & 128 != 0) chimeric = (flag & 2048 != 0) # "bad" here means unmapped or cigar string unavailable is_bad = (flag & 4 != 0) or (cigar == '*') # or (flag...
This function processes reads from a file (SAM/BAM format) to map them to taxonomic IDs, track abundances, and handle multimapped reads. It updates taxid abundances, normalizes by genome length, and stores hit details or low-memory counts. The output includes taxid abundances, multimapped hits, and low-memory mapping d...
def map_and_process(args, instream, acc2info, taxid2info): taxids2abs, multimapped = {}, [] # taxids to abundances, multimapped reads low_mem_mmap = {} # tracks multimapped read hits per taxon in low_mem mode taxids2abs['Unmapped'] = ([0.0, 0.0] + taxid2info['Unmapped']) #placeholder prev_read, read_hits = '', [...
def map_and_process(args, instream, acc2info, taxid2info): taxids2abs, multimapped = {}, [] # taxids to abundances, multimapped reads low_mem_mmap = {} # tracks multimapped read hits per taxon in low_mem mode taxids2abs['Unmapped'] = ([0.0, 0.0] + taxid2info['Unmapped']) #placeholder prev_read, read_hits = '', [...
This function computes taxonomic abundances from sequencing reads by mapping input files (SAM or raw data), handling multi-mapped reads, filtering low-abundance organisms, and resolving ambiguities. It returns structured results for taxonomic classification, incorporating user-defined thresholds and read processing par...
def compute_abundances(args, infile, acc2info, tax2info): # taxids and higher clades to abundances, and multimapped reads dict taxids2abs, clades2abs, multimapped, low_mem_mmap = {}, [], {}, {} # run mapping and process to get uniq map abundances & multimapped reads #taxids2abs, multimapped = map_and_process(args, ...
def profile_parseargs(): # handle user arguments parser = argparse.ArgumentParser(description='Compute abundance estimations for species in a sample.') parser.add_argument('infiles', nargs='+', help='sam or reads file(s) (space-delimited if multiple). Required.') parser.add_argument('data', help='Path to data/ dire...
This function processes input files (FASTQ/FASTA/SAM) by validating parameters, auto-detecting file types, mapping sequences to NCBI taxonomic data, aggregating results across files by taxonomic ranks, and writing outputs. It ensures proper input formatting, checks database requirements, and prepares data for downstrea...
def map_main(args = None): if args == None: args = profile_parseargs() if args.pct_id > 1.0 or args.pct_id < 0.0: sys.exit('Error: --pct_id must be between 0.0 and 1.0, inclusive.') if args.db == 'NONE' and not args.infiles[0].endswith('sam'): sys.exit('Error: --db must be specified unless sam files are provid...
def standard_confirm(self): self.confirmation_label.setText("Please enter booking details") self.room_label.setText("") self.start_label.setText("") self.end_label.setText("") self.price_label_2.setText("") self.name_label.setText("") self.phone_label.setText("") ...
This code handles date selection for hotel reservations, checking availability, and updating UI elements. It toggles between selecting check-in/check-out dates, validates date ranges, checks room availability, paints the calendar to indicate selections, and updates price labels and confirmation status based on user inp...
def set_range(self): self.price_label.setText("") self.standard_confirm() if self.room_type != None and self.room_type != "Not selected": chosen_date = self.calendar.selectedDate().toPyDate() if chosen_date >= self.today: if self.start_set and self.end_s...
def get_B(): return np.array([5, 0]) def get_F(): s = Symbol("s") t = Symbol("t") sol = list(solve([f3(s)[0]-g1(t)[0], f3(s)[1]-g1(t)[1]], s, t, set=True)[1])[0] s = sol[0] t = sol[1] return [f3(s), s, t] def rotate_vector(v1, v2, k): return np.array([math.cos(k)*v1 - math.sin(k)*v2, mat...
This function computes a point along a rotated direction vector from point F, scaled by parameter t. It calculates the vector from F to B, rotates it by angle 'a', then returns F plus t times the rotated vector, generating a parametric point along the rotated direction.
def h3(t): B = get_B() F = get_F()[0] vecFB = [B[0]-F[0], B[1]-F[1]] vecFO = rotate_vector(vecFB[0], vecFB[1], a) return np.array([F[0] + t*vecFO[0], F[1] + t*vecFO[1]])
def getEdges(n): adjacency = createMatrix() edges = [] for i in range(len(adjacency)): for j in range(i+1, n): if adjacency[i][j] == 1: edges.append(set([i, j])) return edges def makeVariables(n): edges = getEdges(n) variables = [] for i in range(len(edges...
The code generates equations representing the sum of angles around each face in a planar graph, ensuring they equal 2π. It constructs cycles from edges and variables, creates a matrix to track edge-variable mappings, and outputs equations for each face's bounding cycle.
def getEquationsBoundingFace(n, numVertexForFace): edges = getEdges(n) variables = makeVariables(n) cycles = [] boundingFace = boundingFaces(n, numVertexForFace) #[[0]*4 for x in range(4)] matrix = [[0]*len(edges) for x in range(len(boundingFace))] for i in range(len(boundingFace)): ...
def getEdges(n): adjacency = createMatrix() edges = [] for i in range(len(adjacency)): for j in range(i+1, n): if adjacency[i][j] == 1: edges.append(set([i, j])) return edges def makeVariables(n): edges = getEdges(n) variables = [] for i in range(len(edges...
The code generates inequalities for non-bounding faces in a geometric structure by summing edge variables associated with each face's edges and enforcing that their total exceeds 2π. It identifies faces not bounding the structure, maps their edges to variables, and prints inequalities like "var1 + var2 + ... > 2*np.pi"...
def getInequalitiesNotBoundingFace(n, numVertexForFace): cycles = [] edges = getEdges(n) variables = makeVariables(n) nboundingFace = notBoundingFace(n, numVertexForFace) for i in range(len(nboundingFace)): cycle = [] for j in range(len(nboundingFace[i]) - 1): edge = set(...
def get_F(): s = Symbol("s") t = Symbol("t") sol = list(solve([f3(s)[0]-g1(t)[0], f3(s)[1]-g1(t)[1]], s, t, set=True)[1])[0] s = sol[0] t = sol[1] return [f3(s), s, t] def get_O(): s = Symbol("s") t = Symbol("t") sol = list(solve([h1(s)[0]-h3(t)[0], h1(s)[1]-h3(t)[1]], s, t, set=True...
The code calculates a point along a rotated direction from point F towards point O. It computes the vector from F to O, rotates this vector by an angle f, and returns a new point at a distance t times the rotated vector from F.
def g3(t): F = get_F()[0] O = get_O()[0] vecFO = [O[0]-F[0], O[1]-F[1]] vecFD = rotate_vector(vecFO[0], vecFO[1], f) return np.array([F[0] + t*vecFD[0], F[1] + t*vecFD[1]])
def get_O(): s = Symbol("s") t = Symbol("t") sol = list(solve([h1(s)[0]-h3(t)[0], h1(s)[1]-h3(t)[1]], s, t, set=True)[1])[0] s = sol[0] t = sol[1] return [h1(s), s, t] def get_F(): s = Symbol("s") t = Symbol("t") sol = list(solve([f3(s)[0]-g1(t)[0], f3(s)[1]-g1(t)[1]], s, t, set=True...
The function `h2(t)` computes a parametric point along a rotated vector direction from point `O` to `F`, scaled by parameter `t`. It retrieves points `O` and `F`, calculates the vector `vecOF` from `O` to `F`, rotates this vector by an angle of `-(π - e - f)` radians, and returns the coordinates of a point offset from ...
def h2(t): O = get_O()[0] F = get_F()[0] vecOF = [F[0]-O[0], F[1]-O[1]] vecOD = rotate_vector(vecOF[0], vecOF[1], -(np.pi-e-f)) return np.array([O[0] + t*vecOD[0], O[1] + t*vecOD[1]])
def do_table_cheri_api(results): preamble = [r'\begin{table}[t]', r'\begin{center}', r'\begin{tabular}{lcrr}'] preamble += [r'\toprule', r'allocator & API & \# API calls & \# builtin calls \\'] preamble += [r'\midrule'] entries = [] for result in results: if not 'api' in result: ...
The main task of the code is to sort input data by "name" and generate LaTeX tables from the results, writing them into three separate files: "cheri_api.tex", "tests.tex", and "slocs.tex". Each file is populated with a table created by a corresponding function (`do_table_cheri_api`, `do_table_tests`, `do_table_slocs`) ...
def do_all_tables(results): results = sorted(results, key = itemgetter("name")) with open(os.path.join(work_dir_local, "cheri_api.tex"), 'w') as cheri_api_fd: cheri_api_fd.write(do_table_cheri_api(results)) with open(os.path.join(work_dir_local, "tests.tex"), 'w') as tests_fd: tests_fd.write...
def parse_command_line_arguments() -> SignFirmwareArguments: """Parse the command line arguments""" def base_16_int(string): return int(string, 16) def two_hexint_tuple(string): return (int(string.split(':')[0], 16), int(string.split(':')[1], 16)) def str_as_bytes(string): retu...
The main task of the code is to serve as the entry point for a firmware signing application. It configures logging, parses and validates command-line arguments, then executes the firmware signing process using the `sign_firmware` function with the validated arguments.
def main(): """the entry point of the application.""" logging.basicConfig(level=logging.INFO) args = parse_command_line_arguments() validate_command_line_arguments(args) sign_firmware(args)