dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def classify( x, mask, prefix, use_multiclass=False, n_clusters=10, use_sampling=False, adjust_clusters=False): if use_multiclass: labels, probs = multiclass( x, mask, n_clusters=n_clusters, adjust_clusters=adjust_clusters) out = labels, probs...
The main task of the code is to perform multiclass classification on normalized data using a specified number of clusters, generate visualizations of classification labels and probability distributions, and save these as PNG files. It adjusts clusters if required, applies a colormap for visualization, and outputs resul...
def classify_multiclass( normalized, mask, prefix, cat_names, adjust_clusters, cmap='tab10', n_clusters=10): n_clusters = 10 labels_mc, probs_mc = classify( normalized, mask, prefix, use_multiclass=True, n_clusters=n_clusters, adjust_clusters=adjust_clusters)...
def plot_scores(scores, mask, prefix, cmap): scores_arr = np.array(list(scores.values())) minmax = np.nanmin(scores_arr), np.nanmax(scores_arr) score_tot = np.sum(scores_arr, axis=0) score_tot[~mask] = 1.0 normalized = {} for name, s in scores.items(): plot_matrix( s, ...
The code processes input scores and mask to generate visualizations and text files for label classification. It normalizes scores, creates color maps, classifies labels with and without sampling, sorts results, and saves plots and sorted names. The main task is to visualize and compare label classifications using diffe...
def compare(scores, mask, prefix, cmap): normalized = plot_scores(scores, mask, prefix, cmap=cmap) normalized = list(normalized.values()) names = np.array(list(scores.keys())) cmap = cmap_myset n_colors = len(names) plot_cmap( cmap=cmap, n=n_colors, filename=prefix+'labe...
def cluster_hierarchical( x_major, method, n_clusters, x_minor=None, min_cluster_size=None, reduce_dimension=False, location_weight=None): if reduce_dimension: x_major = reduce_embs_dim(x_major, method='pca', n_components=0.99) if x_minor is not None: x_minor = re...
The code performs hierarchical clustering on input data to create a coarser grouping, then refines it using Agglomerative Clustering on centroids to achieve the desired number of clusters. It upscales the final labels to the original image shape, handling non-finite values by setting them to -1. The process combines mu...
def cluster_mbkmagglo(x, n_clusters): img_shape = x[0].shape isin = np.isfinite(x[0]) n_clusters_small = n_clusters * 50 min_cluster_size = max(1, isin.sum() // n_clusters_small // 1000) lab_small = cluster_hierarchical( x, method='mbkm', n_clusters=n_clusters_small, min_cluster_si...
def upscale(x, factor): if factor is not None and factor > 1: shape = np.array(x.shape) * factor x = upsize(x, shape) return x def plot_matrix(x, *args, **kwargs): lower, upper = 0.001, 0.999 x = np.clip( x, np.nanquantile(x, lower), np.nanquantile(x, upper)) plot_matrix_...
The function processes structural data by analyzing scores, applying masks and thresholds, and generating visualizations. It recursively handles subtypes, fills NaN values, scales scores, and plots matrices with a colormap. The output includes processed scores and thresholded versions, stored in a dictionary, with visu...
def analyze( structures, prefix, mask=None, fill_with_min=True, upscale_factor=None): cmap = 'turbo' plot_colorbar( cmap, n_labels=None, filename=prefix+'colorbar.png') score_dict = {} for name, content in structures.items(): score = content['score'].copy() if...
def workspaces(): WORKSPACE_WINDOWS = get_workspaces() workspace_data_dict = {item["id"]: item["windows"] for item in WORKSPACE_WINDOWS} workspace_ids = range(1, 7) workspaces_data = [{"id": ws, "windows": workspace_data_dict.get(ws, 0)} for ws in workspace_ids] return workspaces_data def get_activ...
The code monitors data from a Unix socket using `socat`, captures each line of output, and processes it to generate a structured JSON payload containing workspace details, active status, and application metadata. It continuously writes this JSON to standard output, ensuring real-time updates with immediate flushing to ...
def monitor_socat_output(): socat_command = ["socat", "-u", f"UNIX-CONNECT:/tmp/hypr/{SIGNATURE}/.socket2.sock", "-"] with subprocess.Popen(socat_command, stdout=subprocess.PIPE, text=True) as process: for line in process.stdout: result = { "workspaces": workspaces(), ...
def set_game_obj_images(): # Load images, assign to sprite classes # (do this before the classes are used, after screen setup) player_image = Utility.load_image("player1.gif") # 2 images: tank facing left, tank facing right Player.images = [player_image, pygame.transform.flip(player_image, 1, 0)] ...
The main task of the code is to initialize a Pygame game by setting up the display, loading assets, creating game objects (aliens, shots, bombs), configuring sprite groups, and starting the game loop. It handles audio initialization, screen rendering, and game state setup, including score, lives, and level tracking, be...
def main(winstyle=0): if pygame.get_sdl_version()[0] == 2: pygame.mixer.pre_init(44100, 32, 2, 1024) pygame.init() # set the display mode # will go to full screen if uncommented winstyle = 0 # |FULLSCREEN # checks whether display mode is avaliable bestdepth = pygame.display.mode_o...
def is_string_table(self, asset): return asset.__class__ == unreal.StringTable def reimport_stringtable_from_gdrive(self, doc_url, asset): temp_file_full_name = GDU.download_sheet(doc_url, store_in_file=True) ts = unreal.get_editor_subsystem(unreal.TableSubsystem) result...
The code's main task is to reimport either a string table or a data table from Google Drive based on the asset type. It checks if the asset is a string table using `is_string_table()`, then calls `reimport_stringtable_from_gdrive()` if true, or `reimport_datatable_from_gdrive()` otherwise, using the provided `doc_url` ...
def reimport_asset(self, doc_url, asset): if self.is_string_table(asset): self.reimport_stringtable_from_gdrive(doc_url, asset) else: self.reimport_datatable_from_gdrive(doc_url, asset)
def isWaypointReached(self): """ Checks if waypoint is reached based on pre-defined threshold. @param: self @result: returns True if waypoint is reached, otherwise False """ if not self.waypoints: return False desired_point = self.waypoints[0...
The main task of the code is to process odometry messages by updating the vehicle's position and heading, check if a target waypoint is reached, transition to the next waypoint if necessary, apply a PD control algorithm, and publish velocity commands and waypoint lists for navigation.
def onOdom(self, odom_msg): """ Callback function, handling incoming odometry messages. @param: self @param odom_msg - odometry geometry message @result: update of relevant vehicle state variables """ try: (translation, quat_rotation) = self.listener....
def validate_source_ip(ip_add): flag = 0 ip_add = str(ip_add) + '/32' print(ip_add) # read the env variables blocked_ip_add,visited_ip_add = read_env_variable() # read the in built in file containing visited ip add details f = open("visited_ip_add.txt","r") visited_ip_add ...
The main task of the code is to register users for vaccination alerts by validating their email and area PINs. It creates SNS topics for valid PINs, checks existing subscriptions, and subscribes users if not already registered. Invalid inputs trigger error messages, while successful registrations confirm subscription e...
def lambda_handler(event, context): try: print(event) ip_check = validate_source_ip(event['sourceIP']) # disabling ip check #ip_check = 0 if ip_check == 0: data_to_be_register = event['body'] area_pin = data_to_be_register['pin'...
def clusters(X, centers): clusters = [[] for _ in centers] for x in X: clusters[np.argmin(distances(x, centers))].append(x) return clusters def print_clusters(C): for i, c in enumerate(C): print(f'Cluster {i}:', [list(xs) for xs in c]) def newCenters(C): centers = [] for xs in C:...
The code performs K-means clustering on a 2D dataset with initial centers. It iterates twice, assigning data points to clusters, printing cluster assignments, updating centers based on cluster means, and displaying new centers each iteration. The main task is to demonstrate the K-means algorithm's clustering and center...
def ex1(): X = np.array([[1,2], [2,1], [4,3], [5,4], [6,5], [7,6], [9,8], [10,7]]) centers = np.array([[2, 1], [10, 7]]) for i in range(2): print('Iteration:', i+1) cs = clusters(X, centers) print_clusters(cs) centers = newCenters(cs) print_centers(centers)
def clusters(X, centers): clusters = [[] for _ in centers] for x in X: clusters[np.argmin(distances(x, centers))].append(x) return clusters def print_clusters(C): for i, c in enumerate(C): print(f'Cluster {i}:', [list(xs) for xs in c]) def newCenters(C): centers = [] for xs in C:...
The code performs K-means clustering on a 2D dataset. It initializes three cluster centers, iterates twice to assign data points to clusters, computes new centers based on cluster means, and prints results after each iteration.
def ex2(): X = np.array([[1,2], [2,1], [4,3], [5,4], [6,5], [7,6], [9,8], [10,7]]) centers = np.array([[1,1], [5,4], [9,8]]) for i in range(2): print('Iteration:', i+1) cs = clusters(X, centers) print_clusters(cs) centers = newCenters(cs) print_centers(centers)
def _create_clusters(self, centroids): # assign the smaples to the closest centroids clusters = [[] for _ in range(self.K)] for idx, sample in enumerate(self.X): centroid_idx = self._closest_centroid(sample, centroids) clusters[centroid_idx].append(idx) r...
This code implements the K-means clustering algorithm by initializing centroids randomly, iteratively assigning data points to the nearest centroid, recalculating centroids from cluster means, and stopping when centroids converge. It returns cluster labels for each data point after optimization.
def fit(self, X: np.ndarray): self.X = X self.n_samples, self.n_features = X.shape # initialize centroids random_samples_idxs = np.random.choice(self.n_samples, self.K, replace=False) self.centroids = [self.X[idx] for idx in random_samples_idxs] # optimi...
def _most_common_value_label(self, y) -> int: counter = Counter(y) value = counter.most_common(1)[0][0] return value def _best_split(self, X: np.ndarray, y: np.ndarray, feature_indices: np.ndarray): best_gain = -1 split_idx, split_threshold = None, None for feat_...
This function recursively builds a decision tree by selecting random features, finding the optimal split, and creating child nodes until stopping criteria are met (max depth, pure node, or insufficient samples). It returns a tree node with split details and children, or a leaf node with the most common label if stoppin...
def _grow_tree(self, X: np.ndarray, y: np.ndarray, depth: int = 0) -> None: n_samples, n_features = X.shape n_labels = len(np.unique(y)) ### check the stopping criteria if (depth >= self.max_depth or n_labels == 1 or n_samples < self.min_samples_split): leaf_value = ...
def dedispersion_shifts(nchan, dm, start_freq, bandwidth, sample_time): dfreq = bandwidth / nchan stop_freq = start_freq + bandwidth center_freq = (stop_freq + start_freq) / 2 ref_delay = 4149 * dm * center_freq**(-2) shifts = np.zeros(nchan) for i in range(nchan): # DM delay ch...
The function performs dedispersion on input data for multiple trial dispersion measures (DMs), calculating signal metrics. For each DM, it computes dedispersion shifts, applies dedispersion, and evaluates signal-to-noise ratios (SNRs) across varying window sizes (powers of two). It tracks maximum values, standard devia...
def _dedispersion_search(data, trial_DMs, nchan, start_freq, bandwidth, sample_time): ndm = trial_DMs.size maxvalues = np.zeros_like(trial_DMs) stds = np.zeros_like(trial_DMs) best_snrs = np.zeros_like(trial_DMs) best_windows = np.zeros(ndm, int32) for i in prange(ndm): dm = trial_DMs[i]...
def dedispersion_plan(nchan, dmmin, dmmax, start_freq, bandwidth, sample_time): """ Examples -------- >>> tDM = dedispersion_plan(10, 0, 10, 1400, 128, 0.0005) >>> np.isclose(tDM[0], 0) True >>> np.isclose(tDM[-1], 10., atol=1) True """ # dfreq = bandwidth / nchan stop_freq =...
The function performs dedispersion on input radio astronomical data across a range of trial DM values, computing maximum values, standard deviations, signal-to-noise ratios (SNRs), and optimal rebin windows for each trial DM. It returns a structured table with these metrics and optionally the dedispersed data plane if ...
def dedispersion_search(data, dmmin, dmmax, start_freq, bandwidth, sample_time, show=False): # log.info("Starting search with Dedispersion") nchan = data.shape[0] # log.info("Creating dedispersion plan") trial_DMs = dedispersion_plan(nchan, dmmin, dmmax, start_freq, bandwidth, sample_time) # log.i...
def validating(model, inputs, input_lengths, labels, label_lengths, collapse_repeated=True): preds = model.recognize(inputs, input_lengths) decodes = [] targets = [] for i, args in enumerate(preds): decode = [] targets.append(text_transform.int_to_text(labels[i][:label_lengths[i]].tolist...
The code evaluates a model's performance on a test dataset by computing loss, Character Error Rate (CER), and Word Error Rate (WER). It processes each batch, calculates metrics, and logs them using an experiment tracker. The model runs in evaluation mode, and results are aggregated and printed.
def test(model, device, test_loader, criterion, epoch, iter_meter, experiment): print('\nevaluating…') model.eval() test_loss = 0 test_cer, test_wer = [], [] with experiment.test(): with torch.no_grad(): for I, _data in enumerate(test_loader): spectrograms, labels...
def GreedyDecoder(output, labels, label_lengths, blank_label=28, collapse_repeated=True): arg_maxes = torch.argmax(output, dim=2) decodes = [] targets = [] for i, args in enumerate(arg_maxes): decode = [] targets.append(text_transform.int_to_text(labels[i][:label_lengths[i]].tolist())) ...
The code evaluates a model's performance on a test dataset by computing the average loss, Character Error Rate (CER), and Word Error Rate (WER). It processes test data, calculates loss using a criterion, decodes predictions, and compares them with targets to compute CER/WER. Metrics are logged using the experiment trac...
def test(model, device, test_loader, criterion, epoch, iter_meter, experiment): print('\nevaluating...') model.eval() test_loss = 0 test_cer, test_wer = [], [] with experiment.test(): with torch.no_grad(): for i, _data in enumerate(test_loader): spectrograms, labe...
def form_valid(self, form, **kwargs): """If the form is valid, render Solar Dryer Design details.""" """Return a dictionary of solutions from the solar dryer equations""" solutions = {} # Solar dryer's location weather data solutions['location'] = kwargs['location'] solut...
The code handles POST requests by validating forms for generating dryer data or processing PDF context. It fetches weather data via an API, processes responses, validates forms, and returns appropriate results. For 'generate-dryer', it calculates average temperature and wind speed from weather data, validates the form,...
def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ if 'generate-dryer' in request.POST: form = self.get_form(form_class=AreaForm) location = reque...
def getS(X, L, mu, s_penalty): mu = float(mu) s_penalty = float(s_penalty) s_penalty2 = s_penalty * mu C = np.subtract(X, L, out=None) S = SoftThresholdMatrix(C, s_penalty2) S_l1norm = np.sum(np.abs(S)) return S, s_penalty2 * S_l1norm def getL(X, S, mu, L_penalty): mu = float(mu) L_p...
The code performs Robust Principal Component Analysis (RPCA) to decompose a matrix $ X $ into three components: a low-rank matrix $ L $, a sparse matrix $ S $, and an error matrix $ E $. It iteratively optimizes these matrices using penalty parameters $ L_{\text{penalty}} $ and $ S_{\text{penalty}} $, adjusting them dy...
def RPCA(X, Lpenalty=-1, Spenalty=-1, verbose=True): X = np.array(X).astype('float64').copy() m, n = X.shape # Penality parameters if (Lpenalty == -1): Lpenalty = (1.4) / np.sqrt(min(n, m)) if (Spenalty == -1): Spenalty = (1.4) / np.sqrt(max(n, m)) # Convergence condition ...
def get_header_dict(file): with open(file) as file: header = split(file.readline()) header_dict = {} for index,field in enumerate(header): header_dict[field] = index return header_dict def split(line): return line.rstrip().split("\t") def get_contig_stats(file): conti...
This function processes a cycle summary to rename contigs based on their occurrence frequency. It counts contig appearances, assigns unique "R" prefixes for repeats, or cycle-edge-based names for unique entries. The renamed mappings are written to an output file, preserving original names if no renaming applies.
def get_renamed_contigs(contig_table, cycle_summary, ofile): header = get_header_dict(cycle_summary) contig_count = {} # count how many times each contig appears in cycles contig_to_name = {} # store renamed values line_count = 0 repeat_num = 1 with open(cycle_summary) as cyc_sum: next(c...
def scan_file(): """ Scans the input file. Returns: int: number of rows/columns (n) str[][]: maze loaded in the program """ n = 0 maze = [] # place whole file address for line in fileinput.input(files = "maze.txt"): if fileinput.isfirstline(): n = int...
The code implements an A* algorithm to solve a maze, visualized via a GUI. It reads the maze from a file, identifies start ('S') and goal ('G') positions, initializes a priority queue for pathfinding, and executes the algorithm. The GUI displays the maze, tracks explored nodes, and shows the solution path. Final statis...
def main(): """ Starts the program. """ # scan the input file and store the number of rows/columns and the maze n, maze = scan_file() maze_copy = copy.deepcopy(maze) # get start and end's rows and columns start_coord = find_point('S', maze, n) end_coord = find_point('G', maze, n) ...
def techthulu(): try: print("retrieving from techthulu "+techURL) jsondata = urllib.request.urlopen(techURL).read().decode('utf-8') portalstate = json.loads(jsondata) if (portalstate['result']['controllingFaction'] == "Neutral"): makegray(portalstate['result']['level']) ...
The main task of the code is to continuously read commands from a control file, execute corresponding functions (e.g., techthulu(), forceblue(), etc.), and loop with delays. It initializes with a default 'tech' command if the file is inaccessible, processes each line until 'exit' is received, and sleeps for a specified...
def main(): curstate = "neutral" try: controlfile = open('/tmp/controlfile',mode="rt") controldata = controlfile.readline().rstrip("\n") except OSError: controldata='tech' while (not controldata=='exit'): print(controldata) if (controldata == 'tech'...
def helper_remove_timed_out_sessions(self) -> None: """ Removes all timed out sessions from the session dictionary and the session dLL """ self.sessionLock.acquire() # Remove all timed out sessions session = self.SessionTime.get_front() while session: ...
The main task of the code is to retrieve an existing session if it exists and is alive, or create a new session if it doesn't. It ensures thread safety by acquiring a lock, checks session validity, extends active sessions' lifetimes, and manages a doubly linked list of sessions. Timed-out sessions are removed before pr...
def get_session(self, sessionID) -> Session: """ Retrieves a session based on the provided metadata. If a session with the given session ID exists and is still alive, it is returned. Otherwise, a new session is created. Args: sessionID (str): The session ID to retrie...
def rgb_to_binary(r, g, b): return add_leading_zeros(bin(r)[2:], 8), add_leading_zeros(bin(g)[2:], 8), add_leading_zeros(bin(b)[2:], 8) def extract_hidden_pixels(image, width_visible, height_visible, pixel_count): hidden_image_pixels = '' idx = 0 for col in range(width_visible): for row in range...
The code decodes a hidden image embedded within another image using steganography. It extracts the width and height of the hidden image from the least significant bits (LSB) of the RGB values of the top-left pixel, then retrieves the hidden pixels from the visible image's data to reconstruct the concealed image.
def decode(image): image_copy = image.load() width_visible, height_visible = image.size r, g, b = image_copy[0, 0] r_binary, g_binary, b_binary = rgb_to_binary(r, g, b) w_h_binary = r_binary + g_binary + b_binary width_hidden = int(w_h_binary[0:12], 2) height_hidden = int(w_h_binary[12:24], ...
def choose_best_attribute( self, data: pd.DataFrame, attributes: list[str], target: str ) -> str: information_gains = [] for attribute in attributes: information_gains.append( self.calculate_information_gain(data, attribute, target) ) return at...
This code builds a decision tree by recursively selecting the best attribute to split data, creating nodes for each subset, and handling base cases like uniform labels or no remaining attributes. It constructs a tree structure where each node represents a decision based on an attribute, with children nodes representing...
def fit(self, df: pd.DataFrame, attributes: list[str], target: str) -> None: assert not df.empty assert target in df.columns # Target should be contained in the df attributes = list(set(df.columns) - set([target])) assert len(attributes) > 0 # You can only train if there are a...
def deductedPay(self): return self.grossPay() - self.taxDeduction() def grossPay(self): otHours = self.hours - 40 if self.hours > 40: return 40 * self.wage + otHours * self.wage * 2 else: return self.wage * self.hours def taxDeduction(self): taxBracket = s...
This method formats and prints a pay stub, displaying the employee's name, net pay (deductedPay), gross pay (grossPay), and tax deductions (taxDeduction) with aligned text and currency formatting, using the provided hours to calculate values.
def printBody(self, hours): self.hours = float(hours) print('-' * 67) print() print('{:<10}{:<30}{:<10}${:>,.2f}'\ .format('PAY TO:', self.first + ' ' + self.last,'AMOUNT:',self.deductedPay())) print() print() print('{:<15}${:>,.2f}'\ ....
def std_articles(news_links): """This functions returns a dictionary with candidates as the key and their articles count as the value for standard media""" new_row = {} # The first column is date of the day the count is done new_row["date"] = [datetime.date.today()] for candidate, link in news_lin...
The main task of the code is to count articles related to political candidates (raila, ruto, karua, rigathi) from Standard Media's URLs, store the counts in a dictionary, write them to a CSV file if non-zero, and return the dictionary.
def std_media(): """ This function counts the articles on each link(candidate), records the counts to a csv file, and returns a dictionary of candidate and their counts""" news_links ={ "raila": "https://www.standardmedia.co.ke/topic/raila-odinga", "ruto": "https://www.standardmedia.co.ke/topi...
def nat_articles(news_links): """This functions returns a dictionary with candidates as the key and their articles count as the value for standard nation africa""" new_row = {} # The first column is date of the day the count is done new_row["date"] = [datetime.date.today()] for candidate, link in ...
The function counts articles from specified URLs, writes non-zero counts to a CSV file, and returns a dictionary mapping candidates to their article counts.
def nation_africa(): """ This function counts the articles on each link(candidate), records the counts to a csv file, and returns a dictionary of candidate and their counts""" news_links ={ "raila": "https://nation.africa/kenya/people/raila-amolo-odinga-3809512", "ruto": "https://nation.af...
def nation_africa(): """ This function counts the articles on each link(candidate), records the counts to a csv file, and returns a dictionary of candidate and their counts""" news_links ={ "raila": "https://nation.africa/kenya/people/raila-amolo-odinga-3809512", "ruto": "https://nation.af...
The code merges data from two sources (`nation_africa()` and `std_media()`) into a dictionary (`all_article_count`), summing article counts for specific keys. It checks if all values are non-zero and writes the merged data to a CSV file (`totals_data.csv`) if valid. The task involves data aggregation, validation, and s...
def main(): # def error_handle(function): # """Handle errors arising from network issues""" # try: # result = function() # except Exception as e: # print(e) # result = { # "date": datetime.date.today(), # "raila": [0], ...
def _load_config_yaml(fname: str): with open(fname) as f: data = yaml.load(f, yaml.SafeLoader) return convert_data(data) def _load_config_pyproject(): data = _load_config_toml("pyproject.toml", key="tool.edwh.bundler") data = data or _load_config_toml("pyproject.toml", key="tool.edwh.bundle") ...
The main task of the code is to load configuration files in YAML or TOML formats from specified paths, with fallback logic for default filenames and error handling based on the 'strict' flag. It prioritizes YAML files, handles TOML files (including pyproject.toml), and returns an empty configuration if the file is not ...
def _load_config(fname: str = DEFAULT_INPUT, strict=False) -> tuple[str, dict]: """ Load yaml config from file name, default to empty or error if strict """ if os.path.exists(fname) and fname.endswith((".yml", ".yaml")): # load default or user-defined yaml return fname, _load_config_yaml...
def load_variables(source: str | list[str] | dict[str, typing.Any] | None) -> dict[str, typing.Any]: load_dotenv() if isinstance(source, str): source = replace_placeholders(source) elif isinstance(source, list): source = [replace_placeholders(_) for _ in source] elif source is None: ...
This function extracts and processes CSS content from a file or dictionary, handling SCSS/SASS conversion, variable insertion, and minification. It loads variables from settings, checks for SCSS indicators, wraps content in scopes if needed, converts SCSS to CSS, and returns the processed result as a string.
def extract_contents_for_css(file: dict | str, settings: dict, cache=True, minify=True, verbose=False) -> str: variables = load_variables(settings.get("scss_variables")) scss = False scope = None if isinstance(file, dict): data = file file = data["file"] if block_variables := loa...
def load_config(fname: str = DEFAULT_INPUT, strict=True, verbose=False) -> dict: file_used, data = _load_config(fname, strict=strict) if not data and strict: # empty config! raise ValueError(f"Config data found for `{file_used}` was empty!") elif verbose: print(f"Using config: {file...
The main task of the code is to build a JavaScript bundle by processing specified files using configuration settings, handling output destinations, minification, caching, and versioning. It loads config parameters, resolves CLI flags, prepares settings, and delegates file processing to `_handle_files` with options for ...
def build_js( _, files: list[str] = None, config: str = DEFAULT_INPUT, verbose: bool = False, # overrule config: output: str | typing.IO = None, # DEFAULT_OUTPUT_JS minify: bool = None, use_cache: bool = None, save_hash: bool = None, version: str = None, stdout: bool = False...
def load_config(fname: str = DEFAULT_INPUT, strict=True, verbose=False) -> dict: file_used, data = _load_config(fname, strict=strict) if not data and strict: # empty config! raise ValueError(f"Config data found for `{file_used}` was empty!") elif verbose: print(f"Using config: {file...
The main task of the code is to build a CSS bundle by processing configuration files and command-line arguments. It handles options like minification, caching, hash saving, and output destination, either to a file or stdout. The function loads settings, resolves parameters from both CLI and config, validates input file...
def build_css( _, files: list[str] = None, config: str = DEFAULT_INPUT, verbose: bool = False, # overrule config: output: str | typing.IO = None, # DEFAULT_OUTPUT_CSS minify: bool = None, use_cache: bool = None, save_hash: bool = None, version: str = None, stdout: bool = Fal...
def load_config(fname: str = DEFAULT_INPUT, strict=True, verbose=False) -> dict: file_used, data = _load_config(fname, strict=strict) if not data and strict: # empty config! raise ValueError(f"Config data found for `{file_used}` was empty!") elif verbose: print(f"Using config: {file...
This function retrieves a configuration value by key, using a default if not found. It loads the config if not provided, processes it with regex patterns, and fills variables with regex substitutions before returning the result.
def config_setting(key, default=None, config=None, config_path=None): if not config: config = load_config(config_path or DEFAULT_INPUT_LTS) re_settings = _regexify_settings(config) var = config.get(key, default) return _fill_variables(var, re_settings)
def siblings_until(soup: PageElement, sibling_name: str, stop: str): for sibling in soup.next_siblings: if sibling.name == stop: break if sibling.name == sibling_name: yield sibling def clean_name(text: str, prefix: str) -> (str, str): id = text.split(prefix)[0].strip() ...
The code extracts service details from HTML elements. It iterates through siblings of the input `h2` element, processes each `h3` tag to clean the service name and ID, retrieves related paragraphs for purpose, description, and outcome, collects functions, then appends a `Service` object with these attributes to a list,...
def find_services(h2: BeautifulSoup) -> [Service]: services = [] for elem in siblings_until(h2, "h3", "h2"): if elem.name == "h3": id, name = clean_name(elem.text, "Service") purpose = find_paragraph(elem, "h3", "Purpose") description = find_paragraph(elem, "h3", "Des...
def clean_name(text: str, prefix: str) -> (str, str): id = text.split(prefix)[0].strip() name = text.split(prefix)[1].strip(":").strip() return id, name def md(soup, **options): try: return MarkdownConverter(**options).convert_soup(soup) except Exception as e: return "" def all_sibli...
This function parses HTML content from a response to extract service area information. It identifies sections marked by "Service Area" in <h2> tags, extracts associated IDs, names, descriptions (from sibling elements until an <h3> is reached), and services. These are compiled into ServiceArea objects and returned as a ...
def find_service_areas(resp: requests.Response) -> [ServiceArea]: service_areas = [] soup = BeautifulSoup(resp.text, "html.parser") h2s = soup.find_all("h2") for h2 in h2s: if "Service Area" in h2.text: id, name = clean_name(h2.text, "Service Area") description = "\n".joi...
def read_in(): """It reads the json object as string from input stream and converts it into dict type and returns it""" sensordata = sys.stdin.readlines() #Since our input would only be having one line, parse our JSON data from that return json.loads(sensordata[0]) def organize_all_sensor_data(...
The main task of the code is to process sensor data based on attribute types (quantitative/qualitative), generating bar graphs, histograms, and heat maps. It organizes data from input arrays, prepares visualizations using specialized functions, and compiles results into a structured JSON output for each attribute set.
def main(): #get our data as an array from read_in() data = read_in() frequency = data[0] attribute_set = data[1] sensor_sets = data[2]; start_time = data[3]; end_time = data[4] annual_data = data[5] monthly_data = data[6] daily_data = data[7] hourly_data = data[8] ...
def creating_route_label(df): """creating label for routes""" label = 1 for i in range(len(df)): if i == df['time'].count()-1: df.loc[i, 'route_label'] = label break else: #creates a new label if the time difference between the current and previous record ...
The code processes CSV files in a specified directory by reading each file, splitting data into routes, generating summaries with metrics like distance, speed, and time, and exporting each route's summary to a separate CSV file at the given export path.
def implement(directory_path, export_file_path): #Loops through the files in the directory path for file in os.listdir(directory_path): filename = os.fsdecode(file) if filename.endswith(".csv"): #checks if the file is in csv format df = pd.read_csv(directory_path+filename) ...
def getEmail(id): status, maildata = mailbox.uid('fetch', bytes(id), '(RFC822)') if status == 'OK': return maildata else: return 'Error' def extractHeaders(message): subject_whitespaces = message['Subject'] subject = str(make_header(decode_header(subject_whitespaces))) date = mes...
The main task of the code is to fetch and process email data from a specified mailbox, extracting headers, body content, and attachments, while checking for duplicates and storing the structured data into a pandas DataFrame for further analysis or storage.
def fetchEmailData(folder, emails): # Allows the function to use mailbox and progessbar. global mailbox global pbar # The data will be stored in a pandas dataframe object. retData = pd.DataFrame(columns=['Mailbox', 'ID', 'From', 'To', 'Subject', 'Date', 'Time', 'T...
def _check_events(self): 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: self._check_keyup_events(ev...
The code manages a game loop with three states: starting the game (s=0), running the main game (s=1) with updates for player movement, bullets, and screen rendering, and displaying a win screen (s=2) after triggering a win condition. It handles events, updates game elements, and transitions between states based on `sel...
def run_game(self): # Nathan Smith helped create start button and start screen while True: if self.start.s == 0: self.start.run_start() elif self.start.s == 1: self._check_events() self._update_screen() self.guy.upda...
def preprocess(): i = inputNumber() np.random.seed(i) image28 = X[i] ans = Y[i] return image28, ans def preWB(): w1 = random(MiddleNodeNum, D, D) b1 = random(MiddleNodeNum, 1, D) w2 = random(ClassNum, MiddleNodeNum, MiddleNodeNum) b2 = random(ClassNum, 1, MiddleNodeNum) wb = w1, ...
The main task of the code is to perform image classification using a simple neural network. It preprocesses an image and labels, applies a two-layer network with sigmoid and softmax activations, computes the predicted class, compares it to the true answer, and displays the input image.
def main1(): (img, ans) = preprocess() (w1, b1, w2, b2) = preWB() x = inputLayer(img) y1 = sigmoid(combine(x, w1, b1)) a = combine(y1, w2, b2) y2 = softmax(a) max = np.argmax(y2) print("result: " + str(max)) print("answer: " + str(ans)) plt.imshow(img, cmap=cm.gray) plt.show(...
def loadOrTemplate(): ynL = input("Do you have a file? y/n ") if ynL == "y": name = input("What's your file's name? ('.npy' isn't needed!) ") try: return np.load(name + ".npy") except: print("Not found!") return loadOrTemplate() elif ynL == "n": ...
This code trains a neural network for classification by iterating over epochs and batches. It loads model parameters, processes image data, performs forward and backward propagation to compute loss and update weights, accumulates total loss and accuracy, and prints metrics per epoch. Finally, it saves the trained model...
def main3(): (w1, b1, w2, b2) = loadOrTemplate() total = 0. accuracy = 0 for i in range(Epoc): for j in range(int(ImageNum/BatchSize)): (img, ans) = preprocess() prop = propagation(img, ans, w1, b1, w2, b2) ((w1, b1, w2, b2), max, e) = backPropagation(w1, b1, ...
def svd_compact(self, H): U, s, V = linalg.svd(H, full_matrices=False) U = U[:,:self._m] s = s[:self._m] V = V[:self._m,:] return U, s, V def EAS_gradient(self, Y): G = np.zeros((self._m+self._n, self._m)) for i in range(self._length): G-= EAS_log(Y, ...
This function performs gradient descent using the EAS method, iteratively updating Y via SVD decomposition of the negative EAS gradient and Armijo line search. It runs for 't' iterations, optionally orthogonalizing Y at each step to maintain constraints. The goal is to optimize Y by minimizing the EAS objective functio...
def EAS_steepest_gradient(self, Y_0, t, orthogonalize = False): Y=Y_0 for i in range(t): U, s, V = self.svd_compact(-self.EAS_gradient(Y)) j, Y = self.EAS_armijo_linesearch_svd(Y, U, s, V) if orthogonalize == True: Y = orthogonalized(Y) return ...
def EAS_gradient(self, Y): G = np.zeros((self._m+self._n, self._m)) for i in range(self._length): G-= EAS_log(Y, self._Alist[i]) return G def svd_compact(self, H): U, s, V = linalg.svd(H, full_matrices=False) U = U[:,:self._m] s = s[:self._m] V = V[:s...
This function performs conjugate gradient optimization on a manifold using SVD-based Armijo line search, iteratively updating the search direction with gradient information and orthogonalization if enabled, while periodically resetting the direction vector to ensure convergence. It returns the final optimized point and...
def EAS_conjugate_gradient(self, Y_0, t, reset, orthogonalize = False): Ylist = [] Y_old = Y_0 G_old = self.EAS_gradient(Y_old) P = -G_old for i in range(t): U, s, V = self.svd_compact(P) s, Y_new = self.EAS_armijo_linesearch_svd(Y_old, U, s, V) ...
def num_unvisited_successors(self, action): sum = 0 if self.map.access(self.agentX-1, self.agentY) == self.map.UNVISITED: sum += 1 if self.map.access(self.agentX+1, self.agentY) == self.map.UNVISITED: sum += 1 if self.map.access(self.agentX, self.agentY-1) == self...
The function `succAndProbReward` determines the successor state and reward for a given action in a reinforcement learning context. If no unvisited successors exist for the action, it returns the next location, updated map state, a probability of 1, and a reward increased by 100. Otherwise, it returns the same structure...
def succAndProbReward(self,state, action): if self.num_unvisited_successors(action)==0: return [((self.next_location(state[0],action),totuple(self.next_entire_map(state,action))),1,self.reward()+100)] else: return [((self.next_location(state[0],action),totuple(self.next_entire_ma...
def startState(self): return ((self.agentX,self.agentY),totuple(self.entire_map())) def actions(self, state): return self.available_actions(state) def succAndProbReward(self,state, action): if self.num_unvisited_successors(action)==0: return [((self.next_location(state[0],action),tot...
The main task of the code is to compute all reachable states from the initial state using a breadth-first search approach. It initializes a queue with the start state, iteratively explores all possible transitions via actions, and collects unique states into a set. The process ensures every reachable state is identifie...
def computeStates(self): self.states = set() queue = [] print(self.startState()) self.states.add(self.startState()) queue.append(self.startState()) while len(queue) > 0: state = queue.pop() for action in self.actions(state): for new...
def get_shortest_path(direc): global obstacle text = "" start = (0,0) #get the end point end = get_end_point(direc) # Create a priority queue to store the next nodes to visit heap = [(0, start)] # Create a dictionary to store the cost of visiting each node cost = {start: 0} # Cr...
The function `follow_path` determines the shortest maze route using `get_shortest_path`, then selects between graphical (`turtle`) or text-based maze-solving methods based on command-line arguments. It prints a start message, executes the chosen solver, and returns a success status along with the text result.
def follow_path(name,direction): print(" > "+name+" starting maze run..") path ,end ,text = get_shortest_path(direction) if len(sys.argv) == (3) or (len(sys.argv) == (2) and sys.argv[-1] != "text" ): if sys.argv[-1] == "turtle" or sys.argv[1] == "turtle" : solve_maze_path(path,end,dire...
def selectPlayer(): global playerOne print("Choose:\n1. Two Player(Human vs Human)\n2. One Player(Human vs Computer)") x = input("Select '1' or '2': ") if x == "1": playerOne = True else: playerOne = False def printBoard(): print(f" | | \n {board[1]} | {board[2]} | {board[3...
The main task of the code is to execute a tic-tac-toe game between two players, alternating turns to place "O" and "X" on a 3x3 board. It checks for a winner after each move, declares a tie if the board fills without a winner, and prints the game outcome. The loop continues until a win or tie is determined, with the bo...
def main(): global board board = [0, " ", " ", " ", " ", " ", " ", " ", " ", " "] selectPlayer() printBoard() while True: makeMove(playerOneTurn(), "O") printBoard() if checkWinner(board): print("\nO Won the game") break if len(avaliablePosit...
def play(): fullBundle, dealerCards, playerCards = playerTurn() fullBundle, dealerCards = dealerTurn(fullBundle, dealerCards) printLine() print("Your Cards: {} \nYour Sum: {}".format( playerCards, playerCards.sum)) print("Dealer Cards: {} \nDealer Sum: {}".format( dealerCards, dealer...
The main task of the code is to manage a game loop where the player can repeatedly play a game, add money to their balance, and choose to continue or exit. It displays the player's final balance, shows a thank-you message, and waits for user input to exit. The loop continues until the player declines to play again.
def main(): playerBank.addMoney() while True: play() x = input("Do you want to play again.(Y/N):") if x.lower() == "y": clearConsole() continue else: break print("You can get your ${} at checkout.".format(playerBank.getBalance)) p...
def getNumber(): x = 0 while True: try: x = input("Enter your number: ") x = int(x) printLine() print("Prime factorization of {}:".format(x), end=" ") print(primeFactorization(x)) except: print("Enter valid Number") ...
The code's main task is to repeatedly execute the `getNumber()` function in a loop, allowing the user to choose whether to continue or exit. It clears the console and restarts the loop if the user inputs "Y", otherwise it exits after displaying a thank-you message and waiting for a key press.
def main(): while True: # Call Main Function() getNumber() x = input("Do you want to play again.(Y/N):") if x.lower() == "y": clearConsole() continue else: break print("\n\n---------------------\n Thank You :)\nCome Back Soon\n Coded...
def dyeAllButtonsWhite(): button1.configure(fg = 'white') button2.configure(fg = 'white') button3.configure(fg = 'white') button4.configure(fg = 'white') button5.configure(fg = 'white') openFileManagerBtn.configure(fg = 'white') def update_progress(current, total): progress['value'] = int(cu...
The code defines a function `button1_clicked` that processes user input for number of runs and node deletion percentage, validates these inputs, executes multiple simulation runs, updates progress, disables/enables buttons, and generates/updates visual results including a convolution matrix image.
def button1_clicked(): dyeAllButtonsWhite() update_progress(0,100) button1.configure(fg = 'Yellow') picture1.pack_forget() picture2.pack_forget() picture3.pack_forget() if not isNumberOfRunsValid(): messagebox.showinfo("Alert", "Invalid input. Please enter a valid number of rows") ...
def update_odom_object(self): self.odom_object = rospy.wait_for_message("/odom" , Odometry) def get_heading(self): # waiting for the most recent message from topic /odom# # msg = rospy.wait_for_message("/odom" , Odometry) msg = self.odom_object orientation = msg.pose.po...
This code implements a PID controller for a robot's movement, continuously calculating linear and angular velocity commands based on position and orientation errors. It accumulates error over time, applies proportional, integral, and derivative gains, and publishes corrected velocities to guide the robot toward its tar...
def PID_controller(self): twist = Twist() sum_angular_error = 0 sum_linear_error = 0 prev_angular_error = 0 prev_linear_error = 0 while not rospy.is_shutdown(): self.update_odom_object() self.orientaion = self.get_heading() self.po...
def goal_following(self): twist = Twist() sum_angular_error = 0 prev_angular_error = 0 while True: wall_angle ,wall_distance = self.find_wall() if wall_distance <= 0.4: self.cmd_publisher.publish(Twist()) sleep(1) ...
The code defines a `run` method that continuously executes three navigation tasks in a loop until the ROS node shuts down: goal following, left turning, and wall following, enabling autonomous robot navigation and obstacle avoidance.
def run(self): while not rospy.is_shutdown(): self.goal_following() self.turn_left() self.wall_following()
def testSeries(myPath): for root,dirs, files in os.walk(myPath): #print(dirs) for f in files: if f.endswith(tuple(video_ext)) and re.match(main_serie_pattern, f): # serie_pattern main_serie_pattern if os.path.exists(series_path + getFolderName(root)): ...
The function `runAllSorters` executes multiple sorting and cleanup tasks in a specific order: testing a series, sorting movies, sorting games, extracting files, and removing empty folders from the specified directory path. The sequence ensures organized media file management and directory cleanup.
def runAllSorters(the_path): # The Order Can Matter! testSeries(the_path) movieSorter(the_path) gameSorter(the_path) extractFiles(the_path) remove_empty_folders(the_path)
def parseLine(self, line): documentsInfo = [] line = line.strip() stem = line.split(":")[0] line = line[len(stem)+1:] # Read [length to read]{doc1 json}[length to read]{doc2 json} curidx = 0 while curidx < len(line): jsonlenstr = "" for c...
The code updates index files by calculating and appending TF-IDF scores to document postings, sorting them by score (except for bigram_index), and rewriting the updated data. It processes each index path, temporarily renames files, and replaces old entries with sorted, scored information, then deletes the temporary fil...
def post_index_score(self, num_stems): for index_path in self.ALL_INDEX_PATHS: if not index_path in self.index_num: continue print(f"Scoring/sorting {index_path}...") os.rename(f"{index_path}.txt", f"{index_path}.old.txt") with open(f"{index_path}....
def tokenizeProcTextContent(self, text): # tokens from text content file pos = 0 for token in text.split(): yield [token, pos] pos += len(token) + 1 def processStemPositions(self, stemPositions, index_path): for stem, positions in stemPositions.items(): ...
This code indexes a document by extracting and combining stemmed tokens from its title and content, merging their positions, updating an index data structure, tracking document counts, and offloading data when thresholds are met for efficient storage management.
def index(self, filepath, title, importantTagExtentList, numTokens): # extract data from file if not os.path.isfile(filepath): print("WARNING: called index with file that doesn't exist.") return with open(filepath) as f: textContent = f.read() ...
def tokenizeProcTextContent(self, text): # tokens from text content file pos = 0 for token in text.split(): yield [token, pos] pos += len(token) + 1 def processStemPositions(self, stemPositions, index_path): for stem, positions in stemPositions.items(): ...
The code processes a text file to build a bigram index, combining title and content tokens into a stem-position dictionary. It tokenizes text, maps stems to positions (with negative values for titles), merges data, and stores it. When the document count reaches a threshold, it offloads the index to disk and resets, ena...
def bigram_index(self, filepath, title, importantTagExtentList, numTokens): # not saving importantTagExtentList, numTokens because it is saved in self.index(...) if not os.path.isfile(filepath): print("WARNING: called bigram_index with file that doesn't exist.") return #...
def response_invalid(resp): return resp.status != 200 or not resp.raw_response or not resp.raw_response.content def is_valid(url): # Decide whether to crawl this url or not. # If you decide to crawl it, return True; otherwise return False. # There are already some conditions that return False. try: ...
The code processes a given URL to fetch and parse its robots.txt file, extracting sitemap URLs. It validates responses, delays requests, and adds discovered sitemap URLs to a frontier for crawling. If a sitemap is a .txt file, it parses its lines as URLs; otherwise, it adds the sitemap URL directly. The function tracks...
def process_robots(self, url): robotsurl = url.split(self.netloc)[0] + self.netloc+"/robots.txt" time.sleep(crawler.config.time_delay) resp = download(robotsurl, crawler.config) if response_invalid(resp) or not is_valid(resp.url): return ...
def extract_next_links(url, resp): global previouspage, unique_url_count # url: the URL that was used to get the page # resp.url: the actual url of the page # resp.status: the status code returned by the server. 200 is OK, you got the page. Other numbers mean that there was some kind of problem. # r...
(The code processes extracted links from a webpage by validating them (checking for blacklist/traps), sorting by query parameters, and filtering based on subdomain restrictions. Valid links are stored in a set (`outlinks`) and mapped to their sorted query versions in a dictionary (`prevURL`), then returned as the final...
def scraper(url, resp): links = extract_next_links(url, resp) outlinks = set() #Process links by query. Check link is valid, blacklisted, or trap. Process subdomain info. for link in links: sortedq = sort_by_query(link) if allurlchecks(sortedq) and subdomainInfo.process_url(sortedq).can...
def check_win(state, p): # Horizontal if isP(state[1], p) and isP(state[2], p) and isP(state[3], p): return True if isP(state[4], p) and isP(state[5], p) and isP(state[6], p): return True if isP(state[7], p) and isP(state[8], p) and isP(state[9], p): return True # Vertical ...
The main task of the code is to manage a turn-based game loop, allowing human or AI players to take turns making moves on a 3x3 grid. It checks for win/draw conditions after each move, updates the game state, and handles AI decision-making using specified heuristics and strategies. The AI uses functions like `check_win...
def start_game(ai=None): my_state = deepcopy(start) while True: print("\nCurrent state:") print(f"Player {my_state[0]}'s turn") print(my_state[1:4], "= 1, 2, 3") print(my_state[4:7], "= 4, 5, 6") print(my_state[7:10], "= 7, 8, 9") if check_win(my_state, 1): ...
def slider_updated(self, value, i): self.lables_arr[i].setText(str(value)) def interpolation(self): self.latex_widget.axes2.cla() self.latex_widget.draw() print("inside interpolation") print(self.polynomial_degree_slider.value()) self.degree = self.polynomial_degree_slid...
The main task of the code is to initialize a GUI application's main window by loading a UI layout, configuring dark style themes, setting up menu bars, sliders, radio buttons, labels, and plotting components. It connects UI elements to functions for data processing, visualization, and user interactions, preparing the i...
def __init__(self): super(Main_window, self).__init__() uic.loadUi('gui_main.ui', self) self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5')) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) # Menu Bar self.menubar = self.findChild(QtWidgets.QMenuBar, "men...
def add_new_client(self, client): self.refresh(self.current_time) self.process_new_client(client) def refresh(self, current_time): while not self.busy_servers.empty() and self.busy_servers.top()[0] <= current_time: time = self.process_next_service() if not self.client_que...
The code simulates a system with multiple clients, tracking time and generating reports. It initializes a new report, iterates over clients to update the current time using client distribution, adds each client, processes the simulation to completion, records the total simulation time, and finalizes the report.
def simulate(self): start = time.time() self.report.add_new_report() self.curr_report = self.report.get_current_report() for client in range(self.n_clients): self.current_time = self.current_time + self.client_distribution() self.add_new_client(client) se...
def getLeaguesFromLeague(leagueid: int): uniqueleagueids = set() uniqueleagueids.add(leagueid) print(f"Calling API for {leagueid}") response = requests.get(f"https://www.thesportsdb.com/api/v1/json/{env("API_KEY")}/lookup_all_teams.php?id={leagueid}") data = response.json() for team in data['tea...
This function processes a form submission to add a sports league. It validates the form, retrieves league data using a team ID, filters leagues, fetches league, team, match, and standings data, and displays success messages at each step. Finally, it renders the 'addleague.html' template with the form.
def addLeague(request): form = AddLeagueForm(request.POST) if request.method == 'POST': form = AddLeagueForm(request.POST) if form.is_valid(): pk = request.POST['teamid'] messages.success(request, 'Getting Leagues') leagues = getLeaguesFromLeague(pk) ...
def normalize_excludes(rootpath, excludes): f_excludes = [] for exclude in excludes: if not os.path.isabs(exclude) and not exclude.startswith(rootpath): exclude = os.path.join(rootpath, exclude) f_excludes.append(os.path.normpath(exclude) + os.path.sep) return f_excludes def find...
The code processes Java source files from specified input paths, generating reST documentation for non-private classes organized by package under an output directory. It supports excluding paths via regex, caching, overwriting files, and customizing output formats. Key tasks include parsing command-line options, locati...
def main(argv=sys.argv): logging.basicConfig(level=logging.WARN) parser = OptionParser( usage="""\ usage: %prog [options] -o <output_path> <input_path> [exclude_paths, ...] Look recursively in <input_path> for Java sources files and create reST files for all non-private classes, organized by package u...
def compile_type(self, declaration): signature = util.StringBuilder() formatter.output_declaration(declaration, signature) doc = self.__output_doc(declaration) directive = util.Directive('java:type', signature.build()) directive.add_content(doc) return directive def co...
This function compiles a structured documentation document for a Java type and its members, including package information, type declaration, enum constants, fields, constructors, and methods. It organizes content with appropriate headings, sorts members alphabetically, and adds metadata like 'outertype' for nested type...
def compile_type_document(self, imports_block, package, name, declaration): """ Compile a complete document, documenting a type and its members """ outer_type = name.rpartition('.')[0] document = util.Document() document.add(imports_block) document.add_heading(name, '=') ...
def run_exercise(self, name): s.success_exercise = False print("TRAINING: Exercise ", name, " start") s.req_exercise = name say(name) time.sleep(10) # Delay the robot movement after the audio is played while s.req_exercise == name: time.sleep(0.00000001) # P...
The code's main task is to execute a training routine involving waving, camera calibration, and either adaptive or standard training sessions. It initializes the "hello_waving" exercise, waits for waving completion, calibrates the camera, pauses, and then proceeds with adaptive or regular training based on the 'adaptiv...
def run(self): print("TRAINING START") self.run_exercise("hello_waving") print("Training: start waving") while not s.waved: time.sleep(0.00000001) # Prevents the MP to stuck continue print("Training: Calibration") s.camera.init_position() ...
def initialization(field): gas = [] diameter = 2 * radius for i in range(width // diameter): for j in range(height // diameter): fi = random.uniform(0, 2 * math.pi) v = random.uniform(velocity / 2, velocity) v_x = v * math.cos(fi) v_y = v * math.sin(fi...
The code creates a GUI application using Tkinter to visualize gas particles. It initializes particles, renders them on a canvas, and allows user interaction via keyboard inputs (space to pause, arrow keys for movement, q/e for gas adjustments). The main loop handles events and updates the visual simulation in real-time...
def main(): root = Tk() root.geometry(str(width) + 'x' + str(height) + '+' + str(window_x) + '+' + str(window_y)) field = Canvas(root, width=width, height=height, bg='silver') field.pack() gas = initialization(field) print("n = " + str(len(gas))) render(root, gas, field) ...
def initialization(field): gas = [] diameter = 2 * radius for i in range(width // diameter): for j in range(height // diameter): fi = uniform(0, 2 * pi) v = uniform(velocity / 2, velocity) v_x = v * cos(fi) v_y = v * sin(fi) gas.append(Mole...
This code creates a GUI application using Tkinter to simulate gas particles. It initializes a canvas, sets up window properties, binds keyboard controls for movement and interaction, and runs a main loop to display and update the simulation in real-time.
def main(): root = Tk() root.geometry(str(width) + 'x' + str(height) + '+' + str(window_x) + '+' + str(window_y)) field = Canvas(root, width=width, height=height, bg='silver') field.pack() gas = initialization(field) print("n = " + str(len(gas))) render(root, gas, field) ...
def password_submenu(user): password_menu = TerminalMenu( [ "View Passwords", "Update Password", "Get Average Password Length", "Back", ] ) while True: user_selection = password_menu.show() if user_selection == 0: vi...
The code presents a user menu for managing passwords, entries, categories, and tags via submenus. It loops until the user selects "Logout," which terminates the session after displaying a logout confirmation. Each submenu call continues the loop if it returns None, ensuring seamless navigation between management option...
def user_menu(user): user_menu = TerminalMenu( [ "Manage Passwords", "Manage Entries", "Manage Categories", "Manage Tags", "Logout", ] ) while True: user_selection = user_menu.show() if user_selection == 0: ...
def read_mic_and_send_to_grpc(self, LastWrite): with self.Mic_Lock: if self.stream: data = self.stream.read(CHUNK) else: log("read_mic_and_send_to_grpc - could not read mic stream since it is none", 1) data = bytes() if self.Co...
This function handles starting/stoping audio capture. When active, it updates UI to "Processing...", performs final audio read, stops mic. When inactive, it resets UI, starts mic, manages session IDs, stops ongoing audio, saves config, and initializes a gRPC stream for real-time audio processing.
def on_start_talking_btn_click(self): if (self.IsCapturingAudio): # Change UI with self.UI_Lock: self.StartTalking_Btn_text = "Processing..." # self.StartTalking_Btn_text = "Start Talking" self.StartTalking_Btn_state = False ...
def reset_scene() -> None: """Resets the scene to a clean state.""" # delete everything that isn't part of a camera or a light for obj in bpy.data.objects: if obj.type not in {"CAMERA", "LIGHT"}: bpy.data.objects.remove(obj, do_unlink=True) # delete all the materials for material...
The code renders multiple images of a 3D object from varying camera angles, saving them to a directory. It sets up lighting, camera positions (fixed or random), and exports rendered images along with metadata like camera poses and calibration matrices for subsequent use in training or analysis tasks.
def save_images(object_file: str) -> None: object_uid = os.path.basename(object_file).split(".")[0] os.makedirs(args.output_dir, exist_ok=True) reset_scene() # load the object load_object(object_file) # object_uid = os.path.basename(object_file).split(".")[0] normalize_scene() # create...
def transform_gt(vertices, rot_angle): vertices = norm_coords(vertices) R = transforms3d.euler.euler2mat(-np.deg2rad(rot_angle), 0, 0, 'szyx') vertices = vertices @ R.T return vertices def get_gt_rotate_angle(object_name): angle = 0 if object_name == 'sofa': angle -= np.pi / 2 elif ...
The main task of the code is to compute and log the Chamfer distance and Intersection-over-Union (IoU) between a predicted mesh and a ground truth mesh. It parses input arguments, reads and transforms the ground truth mesh using a rotation angle derived from its name, reads the predicted mesh, calculates metrics via `g...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--pr_mesh', type=str, required=True) parser.add_argument('--pr_name', type=str, required=True) parser.add_argument('--gt_dir', type=str, required=True) parser.add_argument('--gt_mesh', type=str, required=True) parser.add_argumen...
def send_to_client(message, client_socket, server_socket): file_name = str("log/" + clients[client_socket].username + ".txt") with open(file_name, 'a+') as f: f.write(message) f.close() for client in sockets_list[1:]: if client == client_socket and client != server_socket: ...
The function `join_room` handles a client's request to join a specified room. It checks if the room exists, ensures the client isn't already in it, adds them to the room, broadcasts the join event, updates the client's default room, and sends appropriate feedback. If the room is invalid or the client is already present...
def join_room(room, client_socket, server_socket): if room: if room in rooms: if room in clients[client_socket].rooms: send_to_client("\r[SERVER] You are already in the room!\n", client_socket, server_socket) else: clients[client_socket].rooms.append(r...
def send_to_client(message, client_socket, server_socket): file_name = str("log/" + clients[client_socket].username + ".txt") with open(file_name, 'a+') as f: f.write(message) f.close() for client in sockets_list[1:]: if client == client_socket and client != server_socket: ...
The function allows a client to join a private room if not already a member. It checks room existence, updates client membership, sends confirmation messages, broadcasts the join event to room members, sets the room as default, and logs the action.
def join_private_room(room, client_socket, server_socket): if room: if room in clients[client_socket].rooms: send_to_client("\r[SERVER] You have already in the room!", client_socket, server_socket) else: for r in privroom: if r[0] == room:...
def can_change_password(): # if user tries to change his own password, user need to provide old password if 'password' in data: if 'old_password' not in data: raise http.HttpErrorUnauthorized(id_message='MISSING_PARAM_OLD_PASSWORD', ...
The main task of the code is to allow a user to change their own password after validating the new password's compliance and encrypting it. It checks if password changes are permitted, verifies the new password's validity, updates the user's password, encrypts it, removes the plain password from data, and returns True ...
def user_change_his_own_password(): if can_change_password(): plain_password = data['password'] if allow_password(user, plain_password): user.password = plain_password user.password = encrypt_password(user) del data['password'] ...
def resetWholeResponse(self): self.wholeResponse = '' def _initBasicFunctionalities(self) -> str: """ First step in initialization of the device """ ''' + at_write_full_phone_functionality | AT+CFUN=1 + at_write_eps_status_codes (can be saved t...
The main task of the code is to initialize basic functionalities and connection setup for a module. It executes two steps: `_initBasicFunctionalities()` and `_initForConnection()`, then determines whether to trigger `AT_RESET_MODULE` based on the setup outcome. The function resets the response buffer, performs initiali...
def doInitialSetup(self) -> str: """ First step: initBasicFunctionalities(), Second step: initForConnection() Decide on AT_RESET_MODULE after setup """ self.resetWholeResponse() self._initBasicFunctionalities() self._initForConnection() return self.whole...
def tensorsFromPair(pair): input_tensor = tensorFromSentence(input_lang, pair[0]) target_tensor = tensorFromSentence(output_lang, pair[1]) return (input_tensor, target_tensor) def train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_L...
This function trains an encoder-decoder sequence-to-sequence model for a specified number of iterations using SGD optimization. It tracks training loss statistics, prints average loss values periodically, and collects loss data for visualization. The model is trained on randomly selected input-target pairs converted to...
def trainIters(encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01): start = time.time() plot_losses = [] print_loss_total = 0 # Reset every print_every plot_loss_total = 0 # Reset every plot_every encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate) ...
def system_tags(self) -> Union[tuple[str], None]: """ Returns the system tags. Returns: tuple[str]: The system tags. """ if self.system_tag_open is not None and self.system_tag_close is not None: return (self.system_tag_open, self.system_tag_close) ...
This method updates or adds a system message in a message list. It first checks if system tags are set; if not, it raises an error. If tags are set, it verifies if the first message has the correct system tags. If so, it edits that message; otherwise, it adds the new system message to the start of the list.
def edit_system_message(self, new_content:str) -> None: if self.system_tags() is None: raise ValueError("System tags are not set, this model does not support system messages.") else: if self.messages[0].tag_open == self.system_tag_open and self.messages[0].tag_close == self.syste...
def _check_loaded(self) -> None: """ Check if the model is loaded, load it if not. Raises an exception if loading fails. """ if not self._loaded: try: self.load() raise Warning("Model not loaded, trying a default reload...") ...
This method generates text using a language model based on input prompts, handling validation, model loading checks, and streaming output. It adjusts token limits, stops at specified strings, and returns a generator for incremental text output, with options to control output format and stopping behavior.
def infer( self, text: str, only_string: bool = True, stop_at_str=None, include_stop_str=True, ) -> Generator[str, None, None]: """ Generate inference text for the input prompt. Args: text (str): The prompt text. only_string (b...
def install_prerequisites(): # install ESP-IDF prerequisites ESP_LOGI('Ready to install ESP-IDF prerequisites..') cmd = '' if sys.platform == 'linux': cmd = 'sudo apt-get install git wget flex bison gperf python3 python3-pip python3-venv python3-setuptools cmake ninja-build ccache libffi-dev lib...
The code's main task is to configure and build an ESP-IDF project by detecting the platform, handling command-line arguments, unsetting IDF_PATH, installing prerequisites, selecting project configurations, applying patches, setting environment variables, and executing builds with specified parameters, while supporting ...
def main(): if sys.platform == 'win32': init(autoreset=True) argv = sys.argv[1:] # unset IDF_PATH if os.environ.get('IDF_PATH'): os.environ['IDF_PATH']='' # install prerequisites if (len(argv) == 1 and sys.argv[1] == 'install'): install_prerequisites() platform_nam...
def decode_image(encoded_image_bytes): """Decodes an image. Args: encoded_image_bytes: encoded image string. Returns: The decoded image tensor [H, W, 3]. """ return tf.image.decode_jpeg(encoded_image_bytes) def normalize_value_range(image, vmin = -1, ...
The main task of the code is to preprocess image data by validating input, decoding the image, normalizing its value range, generating multiscale patches, and updating the input dictionary with the processed image. The function ensures the input is a dictionary containing an 'image' key, applies sequential preprocessin...
def _preprocess_fn(data): """The preprocessing function that is returned.""" # Validate input if not isinstance(data, dict) or 'image' not in data: raise ValueError('Argument `data` must be a dictionary, ' 'not %s' % str(type(data))) # Apply all the individual steps in seq...
def init_logger(): coloredlogs.install() logging.basicConfig(level=logging.INFO, format='(%(asctime)s) %(levelname)s -> %(message)s') def init_db(): global engine engine = create_engine(f'sqlite:////{config.DB_PATH}', echo=False) Base.metadata.create_all(engine) def proccess_request(request: Request...
The main task of the code is to continuously query and process unprocessed requests from a database. It initializes logging and database connections, then enters an infinite loop to fetch all `Request` records marked as `found=False`. Each request is processed via `proccess_request()`, and changes are committed to the ...
def main(): init_logger() init_db() SessionFactory = sessionmaker(bind=engine) session = SessionFactory() # r = Request(id='327934741', name='aviad', phone_number='0556657219', wanted_locations='2161') # session.add(r) # session.commit() while True: all_requests = session.query(...
def audit(json_file_path,json_data, task_name,run_id,status,value): """ create audit json file and audits event records into it""" try: if path.isfile(json_file_path) is False: log1.info('audit started') # Data to be written audit_data = [{ "pipeline_i...
The function orchestrates task or pipeline execution by initializing status logs, checking dependencies, handling restart logic, and auditing processes. It sends status emails, executes jobs, validates cyclic dependencies, and consolidates audit logs. On failure, it notifies via emails and logs errors, ensuring proper ...
def orchestrate_calling(prj_nm,paths_data,task_nm,pip_nm,run_id,log_file_path,log_file_name, restart): """executes the orchestration at task or pipeline level based on the command given""" # if __name__ == "__main__": global STATUS_LIST STATUS_LIST=[] try: if (str(pip_nm) == "-9999" ) or (ta...
def reconstruct_path(came_from,current,draw): while current in came_from: current=came_from[current] current.make_path() draw() def h(p1,p2): x1,y1=p1 x2,y2=p2 return abs(x1-x2)+abs(y1-y2) def draw(win,grid,rows,width): win.fill(WHITE) for row in grid: for spot in...
This code implements a pathfinding algorithm (likely Dijkstra's or A*) to find the shortest path from a start node to an end node on a grid. It uses a priority queue (open_set) to explore nodes, tracks distances (dist), and updates predecessors (came_from). When the end node is reached, it reconstructs and draws the pa...
def algorithm(draw,grid,start,end): count=0 open_set=PriorityQueue() open_set.put((0,count,start)) came_from={} dist={spot:float("inf") for row in grid for spot in row} dist[start]=0 ## ## for row in grid: ## for spot in row: ## open_set.put((,count,dist[spot])) open_s...
def make_grid(rows,width): grid=[] gap=width//rows for i in range(rows): grid.append([]) for j in range(rows): spot=Spot(i,j,gap,rows) grid[i].append(spot) return grid def draw(win,grid,rows,width): win.fill(WHITE) for row in grid: for spot in row:...
This code implements a pathfinding visualizer using Pygame. It allows users to set start/end points, create barriers, and run an algorithm (e.g., A*) to find paths. The main task is to handle grid interactions, event processing, and pathfinding visualization with dynamic updates.
def main(win,width): ROWS=50 grid=make_grid(ROWS,width) start=None end=None run=True while run: draw(win,grid,ROWS,width) for event in pygame.event.get(): if event.type==pygame.QUIT: run=False if pygame.mouse.get_presse...
def get_json(url, user, passwd): """ This function requests the tickets data in json format for teh given API, user & password. This function also throws ConnectionError if connection cannot be established for thr given credentials and print & quit if its any error from the API. Parameters : url (str) : the ...
This function provides a CLI frontend for interacting with a Zendesk API. It allows users to view all tickets (with pagination) or retrieve details of a specific ticket by ID. The interface handles API authentication, fetches JSON data, and displays ticket information while managing navigation between pages using previ...
def ui(url, user, passwd): """ This function runs the frontend of the program. It uses a Command line Iterface for the user to interact with the program Parameters : url (str) : the url of the API user (str) : the user id of the API passwd (str) : the password needed for the API """ global url_master, h...
def get_dataset(config): ds_raw = load_dataset(f"{config['datasource']}", f"{config['lang_src']}-{config['lang_tgt']}", split="train") # we will split ourself # build tokenizer tokenizer_src = get_or_build_tokenizer(config, ds_raw, config["lang_src"]) tokenizer_tgt = get_or_build_tokenizer(config, ds...
This code trains a sequence-to-sequence transformer model using specified configurations, handling device placement (GPU/TPU), loading pre-trained weights, and logging training progress with TensorBoard. It performs forward/backward passes, computes cross-entropy loss with label smoothing, validates after each epoch, a...
def train_model(config): # define the device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if config["TPU"]: import torch_xla import torch_xla.core.xla_model as xm device = xm.xla_device() print(f"Using device {device}") # make sure weights folder i...
def clsass_prefixes(pfixes): if len(pfixes)>0: prefixes_by_length = {} for pfix in pfixes: if pfix is not None: prefix_length = int(pfix.split('/')[-1]) if prefix_length in prefixes_by_length: prefixes_by_length[prefix_length].append(pf...
The code processes target IP prefixes by categorizing them by length, generating addresses, tracing routes, and identifying common prefixes. It tracks discovered IPs/ASes, calculates detection efficiency, and handles different prefix length ranges (32-64 and others) separately. The function returns unique common prefix...
def total_comprefixes(targetpres): global packet global total_budget global lap global start_time totalcomps=[] Prx=[] add_no_prefix_class=[] Tmp_aip=set() Tmp_naip=set() Tmp_as=set() cround=0 Len=0 lenprefixes=0 elapsed_time2=0.0 prefixes_by_length=...
def compute_start_state_value(environment, Q, num_episodes=1000, max_num_steps_per_episode=1000000): sum_of_expected_rewards = 0 for _ in range(num_episodes): state = environment.starting_state for _ in range(max_num_steps_per_episode): action = eps_greedy_action_selection(Q, state, ...
The code runs multiple simulations to evaluate the average start-state value over time using a policy update method. It initializes Q-values, performs epsilon-greedy action selection, updates Q-values based on environment transitions, and tracks start-state values at specified steps. Results are averaged across runs to...
def run_on_policy_updates(num_runs, num_steps_per_run, start_value_computation_steps, num_states, num_actions, b, eps): start_state_value = np.zeros(len(start_value_computation_steps)) for _ in range(num_runs): environment = Environment(num_states, num_actions, b) Q = np.zeros((num_states, num_a...
def photometric_distort(image): """ Distort brightness, contrast, saturation, and hue, each with a 50% chance, in random order. :param image: image, a PIL Image :return: distorted image """ new_image = image distortions = [FT.adjust_brightness, FT.adjust_contrast, ...
The code transforms an image and its associated bounding boxes/labels during training or testing. For training, it applies photometric distortions, random expansion, cropping, flipping, and normalization. It resizes the image to 512x512, converts it to a tensor, and normalizes using ImageNet statistics. Testing uses fe...
def transform(image, boxes, labels, split): """ Apply the transformations above. :param image: image, a PIL Image :param boxes: bounding boxes in boundary coordinates, a tensor of dimensions (n_objects, 4) :param labels: labels of objects, a tensor of dimensions (n_objects) :param split: one of ...
def import_file(): filename = input("enter filename: ") straight_line() # check if file exists file_exists = exists(filename) if not file_exists: print("file name does not exist") return -1 # open file and read lines print("file imported") file = open(filename, 'r') ...
The main task of the code is to process a file by removing empty lines and comments, filtering specific lines, grouping them, and printing intermediate results. It first checks if the file exists, handles errors, and returns success/failure status.
def ppalms(): lines = import_file() if(lines == -1): # if file don't exist straight_line() return -1 lines = rem_empty_lines(lines) lines = rem_comments(lines) print_lines(lines) lines = exclude_lines(lines) print_lines(lines) lines = group_lines(lines) ...
def seat_id(row, column, nseats_by_row = 8): return row * nseats_by_row + column def find_row(row_selectors, min_row = 0, max_row = 127): return binary_search(row_selectors, 'F', 'B', min_row, max_row) def find_column(column_selectors, min_col = 0, max_col = 7): return binary_search(column_selectors, 'L', '...
Your return The function `find_seat_id` processes a boarding pass string to determine a seat ID. It splits the input into a row selector (first 7 characters by default) and a column selector (remaining characters). These selectors are passed to `find_row` and `find_column` to compute the row and column numbers, which...
def find_seat_id(boarding_pass, row_selector_len = 7): row_selector = boarding_pass[:row_selector_len] col_selector = boarding_pass[row_selector_len:] return seat_id(find_row(row_selector), find_column(col_selector))
def read_boot_code_from(path): instructions = [] for line in read_lines_from(path): instructions.append(parse_instruction(line.strip())) return instructions def run(boot_code): index = 0 accumulator = 0 executed = [ False ] * len(boot_code) while index < len(boot_code) and not execut...
The main task of the code is to solve two parts of a boot code problem. Part 1 calculates the accumulator value before an infinite loop occurs, while Part 2 modifies the boot code to resolve the loop and computes the corrected accumulator value. The code reads input from a file, executes the original boot code, applies...
def main(): boot_code = read_boot_code_from("./input.txt") print(f"Accumulator before infinite loop: {run(boot_code)} (part 1)") print(f"Accumulator after fix: {run(fixed(boot_code))} (part 2)")
def read_numbers_from(path): numbers = [] for line in read_lines_from(path): numbers.append(int(line.strip())) return numbers def find_intruder(xmas_numbers, preamble_size = 25): index = preamble_size found = False while index < len(xmas_numbers) and not found: preamble = xmas_nu...
The code reads numbers from a file, identifies the first "intruder" number that violates a validation rule (using a window of 25 previous numbers), finds a contiguous subsequence of numbers summing to the intruder, and outputs the intruder value and the sum of the minimum and maximum values in that subsequence.
def main(): numbers = read_numbers_from("./input.txt") intruder = find_intruder(numbers, 25) contiguous_range = find_contiguous_range(numbers, intruder) print(f"First intruder: {intruder} (part 1)") print(f"Contiguous range: {min(contiguous_range) + max(contiguous_range)} (part 2)")
def read_boarding_passes_from_input(path): with open(path, 'r') as file: lines = file.readlines() return [line.strip() for line in lines] def find_seat_id(boarding_pass, row_selector_len = 7): row_selector = boarding_pass[:row_selector_len] col_selector = boarding_pass[row_selector_len:] ret...
(The code reads boarding passes from a file, extracts seat IDs, determines the highest seat ID (part 1), and identifies the user's missing seat ID (part 2) by analyzing gaps in the sequence of assigned seats.)
def main(): boarding_passes = read_boarding_passes_from_input("./input.txt") seat_ids = [find_seat_id(bp) for bp in boarding_passes] print(f"The highest seat ID on a boarding pass is {max(seat_ids)} (part 1)") print(f"My seat id is {find_my_seat(seat_ids)} (part 2)")
def read_lines_from_input(path): with open(path, 'r') as file: lines = file.readlines() return [line.rstrip() for line in lines] def read_passports_from(lines): passports = [] current_passport = "" for line in lines: if line == "": passports.append(parse_passport(current_...
The code reads input data from a file, parses it into passport entries, and validates each passport against predefined criteria. It checks for the presence and correctness of required fields (e.g., birth year, issue year, height) using specific validators. The script then counts how many passports meet all validation r...
def main(): lines = read_lines_from_input("./input.txt") passports = read_passports_from(lines) requirements = { "byr": { "required": True, "validator": v.byr_validator}, "iyr": { "required": True, "validator": v.iyr_validator}, "eyr": { "required": True, "validator": v.eyr_validato...
def read_joltage_ratings(path): with open(path, 'r') as file: lines = file.readlines() return [ int(line.strip()) for line in lines ] def get_joltage_differences_distribution(source, adapters, device): chain = get_adapters_chain(source, adapters, device) distribution = {} for i in range(1, l...
The code calculates the product of the counts of 1-jolt and 3-jolt differences in a sequence of adapters, given a starting voltage of 0 and a built-in device adapter. It reads input values, computes the distribution of differences between consecutive adapters, and outputs the result for part 1 of the problem.
def main(): joltage_ratings = read_joltage_ratings("./input.txt") differences_distribution = get_joltage_differences_distribution( source=0, adapters=joltage_ratings, device=get_builtin_adapter_rating(joltage_ratings) ) answer = differences_distribution[1] * differences_distribut...
def read_rules_from_input(path): with open(path, 'r') as file: lines = file.readlines() rules = {} for line in lines: rules.update(read_rule(line.strip())) return rules def count_possible_bad_parent_for(child_color, rules): count = 0 for color in rules.keys(): if exist_wa...
The code reads bag containment rules from a file, calculates two values: (1) the number of distinct bag colors that can directly or indirectly contain a "shiny gold" bag, and (2) the total count of individual bags required to hold a single "shiny gold" bag according to the rules. It then prints both results.
def main(): rules = read_rules_from_input("./input.txt") count_part_01 = count_possible_bad_parent_for('shiny gold', rules) count_part_02 = count_children('shiny gold', 0, rules) print(f"Number of bag colors that can contain shiny gold bags: {count_part_01} (part 1)") print(f"Number of required indi...
def _row(self, m: int) -> DataFrame: return DataFrame()._set(self.columns, self.attributes, self._drow(m)) def _rows(self, ms: list[int]) -> DataFrame: return DataFrame()._set(self.columns, self.attributes, self._drows(ms)) def _cols(self, ns: list[int]) -> list[list[str]]: if len(ns) == 0: ...
This code implements flexible indexing for a custom data structure, enabling access to rows, columns, or specific cells based on input types. It handles integers for rows, tuples for cell values, lists for row/column slices, and strings for column names, returning corresponding data via methods like _row, _rows, _col, ...
def __getitem__(self, item): if isinstance(item, int): return self._row(item) elif isinstance(item, tuple): m, n = item if isinstance(m, int) and isinstance(n, int): return self.attributes[n][self.data[n][m]] else: raise Typ...
def update(self): """Sends update packets to all neighbouring routers""" self.router.print_forwarding_table() logger("Sending routing update to neighbouring routers...", 1) for neighbour in self.router.config.outputs.keys(): packet = RipPacket(self.router.config.router_id, ...
This infinite loop manages RIP protocol events by handling periodic updates, timeout/garbage collection of routing table entries, and incoming packet processing. It checks update intervals, triggers updates, removes expired entries, and processes received packets to maintain accurate routing information.
def event_loop(self): """Infinite loop, handles all RIP events specific to this implementation""" while True: current_time = time() # SCHEDULED AND TRIGGERED UPDATE HANDLER # if (current_time - self.last_update) > UPDATE_FREQ or \ ((current_time -...