dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def read_error(self): self.error = self.reader_process.exception self.update_error_display(self.error) def stop_acquisition(self): """ Properly shuts down the task currently running, in turn destroying the currently running MultiProcessing process """ # Stop t...
This function updates a graph widget with real-time data from a reader process. It checks if the process is alive, handles errors, retrieves data from a queue, appends new sample data to the plot's x/y axes, adjusts the x-axis view dynamically, and redraws the graph. If no data is available or the process fails, it sto...
def update_graph(self, _): """ Updates the graph widget with the newest sample from the reader process """ if self.reader_process.is_alive(): # If the reader process is alive, we can keep reading data from our queue and checking for errors if self.reader_process.e...
def __calculate_ni(self) -> None: for i in range(self._n - 1): self.__ni[i + 1] = self.__ni[i] * (self._x - self._points[i][0]) def __calculate_n(self): a = [0.0] * len(self.__ni) for i in range(len(a)): a[i] = self.__calculate_ai(0, i) for i, ni in enumerate(self...
The code initializes an object with a list of 2D points, sets up symbolic expressions for interpolation or calculation, computes related values, and prepares for output. It extends a parent class, initializes symbolic expressions, calculates necessary parameters, and triggers a print method for debugging or visualizati...
def __init__(self, points: list[(float, float)]): super().__init__(points) self.__ni: list[sp.Expr] = [1] * self._n self.__calculate_ni() self.__calculate_n() self.__print()
def __calculate_ni(self): t = ((self._x - self._points[-1][0]) / (self._points[1][0] - self._points[0][0])).simplify() # t=(x-x_n)/h for i in range(1, self._n): self.__ni[i] = (self.__ni[i - 1] * (t + (i - 1)) / i).simplify() def __calculate_p(self): ai: list[float] = [0] * self._n ...
This code initializes an object with a list of 2D points, computes symbolic expressions (`ni`) and parameters (`p`) using these points, and prints the results. The `__calculate_ni()` and `__calculate_p()` methods likely derive mathematical relationships from the points, while `__print()` outputs the computed values. Th...
def __init__(self, points: list[(float, float)]): super().__init__(points) self.__ni: list[sp.Expr] = [1] * self._n self.__calculate_ni() self.__calculate_p() self.__print()
def find_property_answer(parse, entity_tag, entity_name, entity_tag2, entity_name2): prop_name = '' prop_tag = '' for counter, token in enumerate(parse, 0): if token.dep_ == 'compound': # compound property if parse[counter + 1].dep_ == 'attr' or parse[counter + 1].dep_ == 'appos': ...
This function determines yes/no answers for entity-related queries by checking property matches, death status, and entity correspondence. It prints debug info, evaluates entity properties, checks if entities are dead/alive, and defaults to property-based or fallback queries if no direct match is found.
def answer_yes_no(parse, entity_tag, entity_name, is_yes_no, found_result, entity_tag2, entity_name2): print("Y/N Entity2: " + entity_name2 + " " + entity_tag2) answer_ent = find_property_answer(parse, entity_tag, entity_name, entity_tag2, entity_name2) print("Answer using property: " + str(answer_ent)) ...
def find_property_answer(parse, entity_tag, entity_name, entity_tag2, entity_name2): prop_name = '' prop_tag = '' for counter, token in enumerate(parse, 0): if token.dep_ == 'compound': # compound property if parse[counter + 1].dep_ == 'attr' or parse[counter + 1].dep_ == 'appos': ...
This function determines if a yes/no answer can be derived from a parsed text based on entity properties and death status. It checks if an entity's state (dead/alive) matches the query, uses property answers, or defaults to a yes/no query if no explicit property is found. The result is printed and returned as a boolean...
def answer_yes_no(parse, entity_tag, entity_name, is_yes_no, found_result, entity_tag2, entity_name2): answer_ent = find_property_answer(parse, entity_tag, entity_name, entity_tag2, entity_name2) dead_or_alive = death_in_yes_no(parse) if dead_or_alive: if dead_or_alive == 'died': if is_d...
def find_tag(name, ent_or_prop, index, is_age, ent_tag, is_location): print("name: " + name) if ent_or_prop == ENTITY: # Currently looking for the most referenced entity params = {'action': 'wbsearchentities', 'language': 'en', 'format': 'json'} if ent_or_prop == PROPERTY: # Currently looking for ...
The function `find_answer` identifies a property's tag and retrieves an answer related to an entity. It first finds a property tag using `find_tag`, then attempts to print the answer with `print_answer`. If unsuccessful, it uses `try_disambiguation` to resolve ambiguities. The function returns both the property tag and...
def find_answer(property_name, entity_name, entity_tag, is_count, is_age, is_location): property_tag = find_tag(property_name, PROPERTY, FIRST_TRY, is_age, entity_tag, is_location) found_result = print_answer(property_tag, entity_tag, is_count, is_age) if not found_result: found_result = try_disambi...
def find_tag(name, ent_or_prop, index, is_age, ent_tag, is_location): if ent_or_prop == ENTITY: # Currently looking for the most referenced entity params = {'action': 'wbsearchentities', 'language': 'en', 'format': 'json'} if ent_or_prop == PROPERTY: # Currently looking for the most referenced propert...
The function's main task is to determine a property value for an entity by first identifying the appropriate property tag, then attempting to retrieve the answer. If unsuccessful, it performs disambiguation based on entity/property names and contextual flags (count, age, location) to resolve ambiguities and return the ...
def find_answer(property_name, entity_name, entity_tag, is_count, is_age, is_location): property_tag = find_tag(property_name, PROPERTY, FIRST_TRY, is_age, entity_tag, is_location) found_result = print_answer(property_tag, entity_tag, is_count, is_age) if not found_result: found_result = try_disambi...
def tell_story(self): if self.text_box == None: text = monsters[self.current_monster]["story"] self.create_text_box(text) keys = self.get_input() if keys[pygame.K_SPACE]: self.text_box = None self.state = "user turn" def monster_turn(self): ...
The `update_state` method manages game state transitions by playing background music and executing specific actions based on the current state. It triggers `tell_story()` when the state is "tell story", initiates `monster_turn()` if the monster's animation isn't "take hit" during "monster turn", starts `user_turn()` up...
def update_state(self): self.background_music.play(True) if self.state == "tell story": self.tell_story() if self.state == "monster turn" and self.monster.current_animation != animations[self.current_monster]["take hit"]: self.monster_turn() if self.state == "us...
def firehose_exists(firehose_name): # Get the description of the Firehose if get_firehose_arn(firehose_name) is None: return False return True def create_firehose_to_s3(firehose_name, s3_bucket_arn, iam_role_name, firehose_src_type='DirectPut', ...
The code creates an AWS Firehose delivery stream to an S3 bucket, using provided ARN and IAM role parameters. It checks if the Firehose exists, creates it if not, waits for activation, and logs progress. If the IAM role doesn't exist, it is created. The script ensures data is directed from Firehose to S3, handling erro...
def main(): # arg 1: 'arn:aws:s3:::reservationfirehosedestinationbucket' # arg 2: 'firehose_to_s3_stream' # arg 3: 'firehose_to_s3' # Assign these values before running the program # If the specified IAM role does not exist, it will be created bucket_arn = sys.argv[1] firehose_name = s...
def _init_w_clusters(self, clusters): data = [] i = 0 for c in clusters: data.extend(c.rep) c.rep_idx = [i + j for j in range(len(c.rep))] i += len(c.rep) data = np.vstack(data) self._create_kdtree(data) self.heap_ = clusters f...
This code processes data to reduce the number of clusters to `n_clusters` by iteratively merging the closest clusters. It uses a heap for efficient selection, updates cluster relationships, and adjusts distances during merges.
def _process(self, data, n_clusters, init_w_clusters=False): if init_w_clusters: self._init_w_clusters(data) else: self._create_kdtree(data) self._create_heap(data) u = heappop(self.heap_) while len(self.heap_) > n_clusters: logging.info(f...
def get_all_templates(self, all=False): template_file_paths = [] if all: logger.info("Gathering all template files...") environments = self.get_target_envs(all) for region in self.regions: region_dir = self.deployment_dir / region for env in environmen...
This function determines which files to include in the scope based on their type (parameters/templates) and environment. It processes Git diff changes (add, modify, delete, rename) to identify relevant files, maps parameter files to their associated templates, and appends them to the scope if they match target environm...
def set_scope(self): if self.environment is None: self.get_all_templates(True) elif self.__diff is None: self.get_all_templates() else: change_types = ["A", "M", "D", "R"] environments = self.get_target_envs() for change_type in change_...
def get_regions(self): regions = [] for region in self.deployment_dir.iterdir(): if region.is_dir(): if region.name in self.valid_regions: regions.append(region.name) else: message = "{} is not a valid AWS ".format(regio...
The code initializes a class to manage deployment tasks by setting up lists for tracking create, update, and delete operations. It configures the environment, retrieves regions, generates a deployment tag, fetches the last deployment commit, calculates differences, and sets the deployment scope. The main task is prepar...
def __init__(self, branch) -> None: self.create_list = [] self.update_list = [] self.delete_list = [] self.environment = Configuration(branch).environment self.regions = self.get_regions() self.deploy_tag = "-".join((self.tag_prefix,branch)) self.__last_deploy = s...
def setbitstoip(n): ansip = [] while n >= 8: ansip.append(255) n-=8 if n > 0: s = '1'*n s += '0'*(8-n) ansip.append(bintodecimal(s)) while len(ansip) != 4: ansip.append(0) return ansip def andip(ip1,ip2): ansip = [] for i in range(4): a...
This function calculates and prints subnet details based on IP class (A/B/C) and subnet bits. It determines the network ID, computes the number of subnets and hosts per subnet, then iterates through each subnet to display its network ID, start/end IP range, and broadcast address.
def printallsubnets(c,ip,mask,sb): if c == 'A': ander = setbitstoip(8) elif c == "B": ander = setbitstoip(16) else: ander = setbitstoip(24) networkid = andip(ip,ander) curr = networkid if c == 'A': nb = 8 hb = 24 elif c == 'B': nb = 16...
def _make_data(lower_itemid: int, number_of_items_per_chunk: int): """Run the datagen function for all items and return the result as a string.""" max_itemid = _get_max_itemid() if not max_itemid: errorstr = "Couldn't determine the greatest item ID." logger.error( errorstr, ...
The main task of the code is to update a wiki module (Module:Iteminfo/data) with generated item data. It creates a data chunk, adds version/timestamp metadata, compares it to the existing module content, and saves the updated code if changes are detected. The script logs progress, handles dry runs, and includes error h...
def script_main(): logger.info("Started update_iteminfo.") summary = Bot.summary("[[User:Ryebot/bot/scripts/iteminfodata|Updated]].") target_module_name = "Module:Iteminfo/data" lower_itemid = 0 # item ID to start at number_of_items_per_chunk = 100 start_time = time.gmtime() # pure data ...
def init_args(): parser = argparse.ArgumentParser() parser.add_argument('--data_path', '-d', type=str, default='data/cleaned_datasets/homo_hydrogenation.csv') parser.add_argument('--save_dir', '-s', type=str, default='.') parser.add_argument('--time_data', '-t', type=int, default=None, help='Are you usi...
The code processes reaction data by loading, cleaning, and analyzing it. It filters out rows with missing critical values, corrects specific entries, and performs either temporal analysis (if time_data is provided) or standard analysis, saving results to a specified directory.
def main(): args = init_args() data_path = args.data_path save_dir = args.save_dir time_data = args.time_data remove_negative_rxns = args.remove_negative_rxns Path(save_dir).mkdir(parents=True, exist_ok=True) # Import data. df = pd.read_csv(data_path) df = df.loc[pd.isna(df...
def init_args(): parser = argparse.ArgumentParser() parser.add_argument('--data_path', '-d', type=str, default='data/cleaned_datasets/buchwald.csv') parser.add_argument('--save_dir', '-s', type=str, default='.') parser.add_argument('--time_data', '-t', type=int, default=None, help='Are you using time da...
The main task of the code is to process and analyze reaction data by cleaning and filtering a CSV dataset, renaming specific reagent entries, and performing either temporal analysis (if time_data is provided) or standard analysis (otherwise), saving results to a specified directory.
def main(): args = init_args() data_path = args.data_path save_dir = args.save_dir time_data = args.time_data remove_negative_rxns = args.remove_negative_rxns Path(save_dir).mkdir(parents=True, exist_ok=True) # Import data. df = pd.read_csv(data_path) df = df.loc[pd.is...
def init_args(): parser = argparse.ArgumentParser() parser.add_argument('--data_path', '-d', type=str, default='data/cleaned_datasets/hetero_hydrogenation.csv') parser.add_argument('--save_dir', '-s', type=str, default='.') parser.add_argument('--time_data', '-t', type=int, default=None, help='Are you u...
The main task of the code is to process a reaction dataset by cleaning and preprocessing it, then perform either temporal analysis or standard analysis based on input arguments. It reads a CSV file, filters out invalid rows, standardizes catalyst names, and executes analysis functions (`temporal_changes` or `standard_a...
def main(): args = init_args() data_path = args.data_path save_dir = args.save_dir time_data = args.time_data remove_negative_rxns = args.remove_negative_rxns Path(save_dir).mkdir(parents=True, exist_ok=True) # Import data. df = pd.read_csv(data_path) df = df.loc[pd.isna(df...
def tutorial_instance(): N = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] P = [(0, 0), (0, 2), (0, 4), (1.5, 5.5), (3, 4), (3, 2), (3, 0)] L = [] for i in range(len(N)): for j in range(i + 1, len(N)): L.append([N[i], N[j], dist_int(P[i], P[j])]) return WG(L) def check_edges(edges1, edges...
The code tests the `greedily_select_edges` method of a graph by comparing its output against predefined edge sets in two scenarios: a tutorial example and a European cities graph. It prints results and skips if the method is unimplemented.
def test1(): print('Testing' + Blue + ' greedily_select_edges' + Black + ':') wg = tutorial_instance() S = {('d', 'e'), ('b', 'c'), ('a', 'g'), ('a', 'b'), ('c', 'd'), ('f', 'g'), ('e', 'f')} R = wg.greedily_select_edges() if(R is None): print(Yellow + ' Skipping.' + Black + ' Not implement...
def get_user_root(): #current_user is imported from flask_login uroot = os.path.join(root, str(current_user.id)) return(uroot) def http_get_directory(path, rel_path, hide_dotfile): global ignored contents = [] total = {'size': 0, 'dir': 0, 'file': 0} for filename in os.listdir(path): ...
This code handles HTTP GET requests to serve files or directories. It checks if 'hide-dotfile' is specified in arguments/cookies, constructs the file path, and serves directory listings or files. If the file has a 'Range' header, it returns partial content; otherwise, it sends the full file. If the path is invalid, it ...
def get(self, p=''): hide_dotfile = request.args.get('hide-dotfile', request.cookies.get('hide-dotfile', 'no')) path = os.path.join(get_user_root(), p) if os.path.isdir(path): res = ht...
def upload(self): """ Redirects the file to the multipart upload function if the file is large. If it is small enough, it puts the file as an object in s3. """ if not self.is_multi: body = read_file(self.src) bucket, key = find_bucket_key(self.dest) ...
This code implements a move operation between local and S3 storage systems. It determines the source and destination types, then performs an upload, copy, or download accordingly. After executing the transfer, it deletes the original file to complete the move operation.
def move(self): """ Implements a move command for s3. """ src = self.src_type dest = self.dest_type if src == 'local' and dest == 's3': self.upload() elif src == 's3' and dest == 's3': self.copy() elif src == 's3' and dest == 'local...
def _set_base_url(self, **options): base_url = self.DEFAULTS['base_url'] if 'base_url' in options: base_url = options['base_url'] del(options['base_url']) return base_url def generate_uiid(self): return str(uuid.uuid1()) def segment_identify(self): segme...
This code initializes a Client object for API interactions, setting up authentication (access_key/secret_key), session handling, and resource classes. It configures headers, initializes utility/resource modules, and prepares authentication tokens, enabling the client to interact with a service via pre-defined classes a...
def __init__(self,access_key=None,secret_key=None, session=None, auth=None, **options): """ Initialize a Client object with session, optional auth handler, and options """ self.session = session or requests.Session() self.auth = auth # file_dir = os.path.dirname(_...
def args_kwargs_checker(arguments, kwarguments, **defaults): if len(arguments) > len(defaults): raise TypeError(str(len(defaults)) + "total arguments required but " + str(len(arguments)) + " args given") # for each argument in args, check to see if it is not in kwargs repeats = set(list(defaults.keys())[:len(arg...
The function processes input arguments by validating their types and structure, creates a PageObject for handling output operations, and directs the execution of the corresponding function using the PageObject. It ensures proper argument formatting, checks for exceptions, and returns the result of the directed function...
def add_output(self, *args, **kwargs): args_dict = args_kwargs_checker(args, kwargs, function=None, title="", ref="", escape=True, access=self.default_access) exception = type_checker(args_dict, ref=str, escape=bool, access=bool) if exception is not None: raise exception prargs_dict = separate_dict(args_dict, [...
def args_kwargs_checker(arguments, kwarguments, **defaults): if len(arguments) > len(defaults): raise TypeError(str(len(defaults)) + "total arguments required but " + str(len(arguments)) + " args given") # for each argument in args, check to see if it is not in kwargs repeats = set(list(defaults.keys())[:len(arg...
This method adds a toggle UI element by validating input arguments, creating a PageObject instance, and directing the setter function to handle the toggle's configuration and access controls.
def add_toggle(self, *args, **kwargs): args_dict = args_kwargs_checker(args, kwargs, setter=None, getter=None, title="", ref=None, escape=True, view_access=self.default_access, toggle_access=self.default_access) exception = type_checker(args_dict, getter=callable, ref=str, escape=bool, view_access=bool, toggle_acce...
def args_kwargs_checker(arguments, kwarguments, **defaults): if len(arguments) > len(defaults): raise TypeError(str(len(defaults)) + "total arguments required but " + str(len(arguments)) + " args given") # for each argument in args, check to see if it is not in kwargs repeats = set(list(defaults.keys())[:len(arg...
The code adds an input page object by validating arguments, determining the number of function parameters, setting field titles, and preparing the object for addition to a list, ensuring correct configuration before appending.
def add_input(self, *args, **kwargs): args_dict = args_kwargs_checker(args, kwargs, function=None, title="", number_of_arguments=-1, field_titles=[], ref="", escape=True, access=self.default_access) exception = type_checker(args_dict, ref=str, field_titles=list_of(str), number_of_arguments=int, escape=bool, access=...
def _is_cloud_execution_mode(): if EXECUTION_MODE == 'cloud': return True return False def _read_csv_cloud(s3_source_path, s3_object_meta): logging.info('Extracting csv file from s3.') separator = s3_object_meta.get('separator', ',') decimal_char = s3_object_meta.get('decimal-char', '.') ...
The function determines the execution environment (cloud or local) and reads a CSV file accordingly, delegating to either `_read_csv_cloud` or `_read_csv_local` based on the detected mode.
def read_csv(source_file_path, event, s3_object_meta): if _is_cloud_execution_mode(): return _read_csv_cloud(source_file_path, s3_object_meta) elif _is_local_execution_mode(): return _read_csv_local(event)
def _is_cloud_execution_mode(): if EXECUTION_MODE == 'cloud': return True return False def _save_to_s3_as_parquet(dataframe, table_name, partition_cols, compression, source_file_path, s3_object_meta): logging.info('Saving dataframe to s3.') dest_path = f's3://{TARGET_...
The function `save_as_parquet` saves a DataFrame as Parquet files to either S3 or local storage based on execution mode. It uses `_save_to_s3_as_parquet` for cloud environments, specifying S3 paths, partitioning, and compression. In local mode, it uses `_save_to_local_as_parquet`, leveraging event parameters for output...
def save_as_parquet(dataframe, s3_object, s3_object_meta, partition_cols, event, compression='snappy'): if _is_cloud_execution_mode(): _save_to_s3_as_parquet(dataframe=dataframe, ...
def perform_k_means_and_get_internal_indices( embedding: np.ndarray, n_clusters_list: list = None, random_state: int = 42) -> pd.DataFrame: """ Performs k-means clustering and return the internal indices dataframe. """ if n_clusters_list is None: n_clusters_list = list(n...
The function performs clustering using k-means and DBSCAN on UMAP-embedded data, selecting the optimal method based on internal validation metrics. It first applies k-means, returning results if valid; otherwise, it switches to DBSCAN with the same UMAP embedding and metric, ensuring robust clustering through method co...
def clustering(umap_results_dict: dict) -> dict | None: """ Coordinates the clustering process by applying k-means and DBSCAN, then selecting the best method based on various metrics. """ embedding = umap_results_dict['embedding'].copy() k_means_internal_indices_df = perform_k_means_and_get_int...
def reset(self): self.snake = Snake() self.food = Food(self.snake.positions) self.score = 0 self.game_reward = 0 return self.get_state() def step(self, action): # Map the numeric action to the actual game direction direction_mapping = { 0: pygame.K_UP,...
The code trains a Q-learning agent using experience replay and epsilon-greedy exploration. It interacts with an environment, stores experiences in a buffer, samples minibatches to update a neural network model, and decays exploration (epsilon) over episodes. The agent learns to maximize cumulative rewards by adjusting ...
def train(self, num_episodes=1000): for episode in range(num_episodes): self.episodes += 1 state = self.reset() game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: ...
def initCentroids(features, info): #Init centroids based on Cao Paper #Empty list of centroids cntrds = [0 for i in range(info['n_clstrs'])] #Density of each point dens = np.zeros(info['n_rows']) #Iterate through features for feat in features: #Update point density dens += (feat....
This code fits a KModes clustering model by initializing centroids, iterating to update cluster memberships and centroids until convergence, handling numerical/categorical features, and saving results like outliers, membership matrix, centroids, and cost. It standardizes data if enabled, checks cluster validity, and re...
def fit(self, X, types): #Fit KModes to data #Convert Pandas to np array for k,v in info.items(): self.info[k] = v assert self.info['n_clstrs'] <= self.info['n_rows'], 'More Clusters than rows' if self.std == True: rdd = standardizeRDD(rdd, info['n_ftrs'], in...
def calc_attribute_weights(X): weights = {} num_zero = 0 PE_zero = [] num_attr = X.shape[1] for col_index in range(num_attr): sig = calc_attribute_significance(X, col_index) if sig > 0: weights[col_index] = 1 + sig else: num_zero += 1 ...
The code calculates a weighted significance measure for each attribute in a dataset matrix X. It computes partition entropies and object significances for each attribute and higher attributes, then combines them using weights to generate a significance factor matrix. The final result is the row-wise sum of these factor...
def peof(X): num_rows = X.shape[0] peof_factors = np.zeros(X.shape) sorted_attribute_weights = calc_attribute_weights(X) for j in range(len(sorted_attribute_weights)): w_j = sorted_attribute_weights[j] higher_attrs = sorted_attribute_weights[j+1:] W_j = sum(higher_attrs)/len...
def get_full_projection_transform(self, **kwargs) -> Transform3d: """ Return the full world-to-camera transform composing the world-to-view and view-to-camera transforms. If camera is defined in NDC space, the projected points are in NDC space. If camera is defined in screen spac...
This function transforms 3D points from PyTorch3D's world/camera coordinate system (+X left, +Y up) to normalized device coordinates (NDC) space (+X left, +Y up, origin at image center). It applies a projection transformation, composing camera-to-NDC conversions if needed, and uses an optional `eps` parameter to clamp ...
def transform_points_ndc( self, points, eps: Optional[float] = None, **kwargs ) -> torch.Tensor: """ Transforms points from PyTorch3D world/camera space to NDC space. Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up. Output points are in NDC spa...
def get_docker_client() -> docker.DockerClient: """returns a docker client, just in case I want to run this remotely yes, premature optimization, no I don't care for your judgement. """ return docker.from_env() def check_if_need_to_build_image(version: str) -> bool: """ checks if you need to rebuil...
The function builds a Docker image for a specified Kanidm version, handling build dependencies, error logging for package issues, and cleanup based on flags. It checks if rebuilding is necessary, constructs the image with dynamic tags and build arguments, and optionally stops after building or proceeds with further set...
def build_version( version_string: str, force_build: bool, keep_volume: bool, just_build_image: bool, ) -> bool: """ builds a particular version """ client = get_docker_client() version_tag = f"kanidm_{version_string}" container_build = check_if_need_to_build_image(version_string) i...
def recalc_covmat(self): idx_reduced = [] for i in range(self.loc.shape[0]): if not tf.where(tf.equal(self.idxs, i)).shape[0]: idx_reduced.append(i) self.idx_reduced = tf.constant(idx_reduced, dtype=tf.int32) self.loc_reduced = tf.gathe...
The code performs an iterative optimization using simulated annealing to refine a probabilistic model's parameters. It updates the proposal distribution (MultivariateNormalTriL) by adjusting the temperature (T) and sampling steps, aiming to converge on the optimal log-likelihood. The process involves computing inverse ...
def calc_point(self, zip_data): vals, idxs, file_number = zip_data print(rank,':',idxs, file_number) self.val = vals if not tf.reduce_all(idxs == self.idxs): self.idxs = idxs self.recalc_covmat() T=1.0 self.prop_dist...
def maybe_ask_user(option, msg, default): if option: return option else: if default: return ask_user(f'{msg} (leave empty for default [{default}]) = ', default) else: return ask_user(f'{msg} = ', default) def maybe_confirm_user(option, msg): if option: ...
This code configures a plugin by collecting user inputs for parameters like name, format support (VST2/AU), macOS target, company details, filenames, and C++ namespace. It generates a configuration summary, requests confirmation, and sets up project structure variables for plugin development.
def config(plugin): plugin['name'] = maybe_ask_user(args.plugin, "Plugin Name (must be a valid C++ class name)", None) plugin['enable_vst2'] = "ON" if maybe_confirm_user(args.vst2, "Enable VST2") else "OFF" plugin['enable_audio_unit'] = "ON" if maybe_confirm_user(args.au, "Enable Audio Unit") else "OFF" ...
def load(self): """ This function loads the original power data from a CSV file Add: if argument 'multi-csv' is True, meaning there is a lot of csv file together, the data is concatenated first before entering the preprocessing """ print('[INFO] Read original powe...
The code processes data by loading, filtering, generating histograms, labeling, creating post-labeling histograms, and relocating images using parallel processing with 5 processes to optimize efficiency.
def start(self): self.load() self.filter() self.hist() self.labeling() self.hist_after_labeling() self.relocate_image(num_processes=5)
def buildings_from_polygon(date, polygon, retain_invalid=False): """ Get building footprints within some polygon. Parameters ---------- date : string query the database at a certain timestamp polygon : Polygon retain_invalid : bool if False discard any building footprints with an invalid geometry Returns -...
This function retrieves OpenStreetMap (OSM) building data based on user-provided spatial inputs, such as polygons, addresses, points with radii, places, or bounding boxes. It queries OSM using Osmnx tools, processes the region of interest, and returns a GeoDataFrame of buildings alongside the polygon and bounding box d...
def create_buildings_gdf_from_input(date="", polygon=None, place=None, which_result=1, point=None, address=None, distance=None, north=None, south=None, east=None, west=None): """ Retrieve OSM buildings according to input data Queries data for input region (polygon, place, point/address and distance around, or bound...
def find_start(mat): for y,line in enumerate(mat): x = line.find('S') if x != -1: return (x,y) assert False, "couldn't find start" def walk(mat, start): curr_pos = start path = {} steps = 0 prev_pos = None start_type = None horiz_pipes = [ HORIZONTAL, SO...
The code reads a grid from "input.txt", identifies the starting position, traverses the grid to determine a path, and calculates the number of enclosed positions within that path. It outputs this count as "num inside". The main task involves parsing a grid, locating a starting point, navigating the grid to trace a path...
def main(): with open("input.txt") as input: mat = list(map(lambda l: l.strip(), input.readlines())) start = find_start(mat) path = walk(mat, start) print("num inside",get_num_inside(mat, path))
def read(self, i): self.pointer += i return self.file_data[self.pointer - i:self.pointer] def TIFF_decoder(self): tiff = {} self.header_offset = self.pointer tiff["Byte align"] = str(self.read(2).hex()) tiff["Tag mark"] = str(self.read(2).hex()) tiff["Link"] = str...
This function decodes the APP1 segment of an image file, extracting Exif/TIFF headers and IFD data. It reads markers, sizes, and headers, then decodes IFD0, subIFD, and IFD1 by adjusting pointers to their respective positions, returning structured metadata in a dictionary.
def app1_decoder(self): app1 = {} app1["APP1 Marker"] = str(self.read(2).hex()) app1["APP1 Size"] = str(self.read(2).hex()) app1["Exif Header"] = str(self.read(6).hex()) app1["TIFF Header"] = self.TIFF_decoder() app1["IFD0"] = self.IFD_decoder() subIFD_link = se...
def mutate_jpg(self): self.change_vector = self.randomize_change_vector() self.mutate_app1(self.change_vector) print(self.mutated_json) return def bit_flip(self, byte): if not byte: return r = random.choice([1, 2, 4, 8, 16, 32, 64, 128]) return self.b_...
The code mutates data by randomly applying bit-flip or magic transformation methods to selected indexes, then writes the modified data to a file. It calculates flip count based on data length and a ratio, selects random positions, applies chosen mutation methods, and saves the altered data.
def mutate(self): self.mutate_jpg() config = self.config data = self.o_data flips = int((len(data) - 4) * FLIP_RATIO) flip_indexes = random.choices(range(2, (len(data) - 6)), k=flips) methods = [0, 1] for idx in flip_indexes: c = random.choice(methods)...
def num_flagged(self, x, y): num = 0 if x > 0: if self.board[x - 1][y].flagged: num += 1 if x < self.row - 1: if self.board[x + 1][y].flagged: num += 1 if y > 0: if self.board[x][y - 1].flagged: num += 1 ...
The code implements an AI move strategy in a Minesweeper-like game. It iterates through the board to analyze revealed cells, comparing flagged and unrevealed adjacent cells. If flags match a cell's value, it reveals remaining cells; if unrevealed cells match the cell's value minus flags, it flags the rest. The AI uses ...
def make_AI_move(self): for i in range(len(self.board)): for j in range(len(self.board[0])): if self.board[i][j].revealed: flags = self.num_flagged(i, j) open = self.num_unrevealed(i, j) if open != 0 and flags != open: ...
def take_manual_turn(self, player): # TODO: Ask the user for a row, col until a valid response # is given them place the player's icon in the right spot while(True): rowcord = int(input("input the row you want ")) colcord = int(input("input the column you want ")) ...
The function `take_turn` handles a player's move in a game. If the player is 'X', it calls `take_manual_turn` for human input. For other players, it uses the minimax algorithm with alpha-beta pruning to determine the optimal move, then places the player's symbol at the calculated coordinates. The task involves switchin...
def take_turn(self, player): # TODO: Simply call the take_manual_turn function if player == 'X': self.take_manual_turn(player) else: (temp, rowcord, colcord) = self.minimax(player, 2, -1000, 1000) self.place_player(player, rowcord, colcord) return
def draw_board(self): for row in self.board: print(row) def make_first_move(self): cord = self.get_input() self.board[cord[0]][cord[1]].reveal() self.place_mines(cord[0], cord[1]) self.assign_nums() self.clear_blanks(cord[0], cord[1]) def make_move(self): ...
The code implements a game loop where the user and computer alternate turns making moves on a board. It starts by drawing the board, letting the user choose to move or let the AI move. After each move, the board is redrawn. The loop continues until the board is full ("W" condition) or the user ends it. The game conclud...
def play_game(self): self.draw_board() self.make_first_move() self.draw_board() condition = "N" while condition == "N": type = int(input("Do you want to make a move(0) or should the computer make a move(1): ")) if type == 0: condition = sel...
def print_instructions(self): # TODO: Print the instructions to the game print("Place X's and O's until a tie or someone gets three in a row") return def print_board(self): for row in self.board: print(row) return def take_turn(self, player): # TODO: Simply ca...
The code implements a game loop for a tic-tac-toe game, alternating turns between players 'X' and 'O', checking after each move for a win or tie condition. If a player wins or the game ties, it prints the result and exits. The loop continues until a terminal game state is reached.
def play_game(self): # TODO: Play game player = 'X' self.print_instructions() self.print_board() while(True): print("") self.take_turn(player) self.print_board() if self.check_win(player) is True: print("player " + p...
def get_subject_wide_data(subject_list, bandpass_filter=False, excluded=[], augment=False): X_tr, Y_tr, X_val, Y_val, X_te, Y_te = get_split_data(subject_list[0], bandpass_filter=bandpass_filter, excluded=excluded, augment=augment) arr = [X_tr, Y_tr, X_val, Y_val, X_te, Y_te] for i in range(1, len(subject_list))...
The main task of the code is to load or generate training, validation, and test datasets for machine learning, applying specified preprocessing steps (bandpass filtering, normalization, augmentation) and excluding certain labels. It either loads pre-saved data if `load_data` is True or processes raw data from subjects,...
def get_training_data(subject_list, bandpass_filter, normalize, excluded_y, augment, load_data): print(f'Applying Bandpass Filter: {bandpass_filter}.') print(f'Normalizing: {normalize}.') print(f'Augmenting: {augment}.') suffix = '' if normalize: suffix += '_norm' if augment: suffix += '_aug' if load_dat...
def get_subject_wide_data(subject_list, bandpass_filter=False, excluded=[], augment=False): X_tr, Y_tr, X_val, Y_val, X_te, Y_te = get_split_data(subject_list[0], bandpass_filter=bandpass_filter, excluded=excluded, augment=augment) arr = [X_tr, Y_tr, X_val, Y_val, X_te, Y_te] for i in range(1, len(subject_list))...
This function processes and returns testing data for a given subject, applying a bandpass filter, normalization, and augmentation. It either loads preprocessed data from files or generates it by calling get_subject_wide_data, applying exclusions, normalization (if enabled), and saving the processed data. The function r...
def get_testing_data(subject, bandpass_filter, normalize, excluded_y, augment, load_data): print(f'Applying Bandpass Filter: {bandpass_filter}.') print(f'Normalizing: {normalize}.') print(f'Augmenting: {augment}.') suffix = '' if normalize: suffix += '_norm' if augment: suffix += '_aug' if load_data: X ...
def test_opt(self, opt, do=True): #dbg("TEST " + str(opt)) self.send(Telnetd.IAC) if do: self.send(Telnetd.DO) else: self.send(Telnetd.DONT) self.send(opt) def send_string(self, msg): self.sock.send(msg) def recv_line(self): line = "" while True: byte = self.recv() if byte == Telnetd.IAC: ...
This code handles a login session with timeout management, prompting for credentials, authenticating via a session object, and processing shell commands until the session exceeds a time limit or encounters an error.
def loop(self): self.session = Session(self.send_string, self.remote[0]) dbg("Setting timeout to " + str(self.timeout) + " seconds") self.sock.settimeout(self.timeout) try: self.test_opt(1) # Kill of Session if longer than self.maxtime ts_start = int(time.time()) self.send_string("Login: ") u...
def read_txt_file(self, f): for index, line in enumerate(f): if (line[:3] == "EOF"): break; if index == 0: # get the map details prev_pos = -2 for pos, char in enumerate(line): if (char == ";"): n...
The code initializes a 3D path planning system for a drone (quad_rotor), reads obstacle data from a file, visualizes obstacles, generates a path using A* algorithm, reduces waypoints for efficiency, and plots the optimized trajectory in 3D space. It handles obstacle avoidance, path optimization, and real-time navigatio...
def __init__(self, start, goal, f): self.map = [] self.obstacles = [] self.start = start self.goal = goal self.read_txt_file(f) # print(self.obstacles) fig = plt.figure() ax = fig.add_subplot(projection ='3d') self.plot_obstacles(fig, ax) s...
def _loop_uniq_valid_choices(self) -> int: w_tot = 0 while w_cnt := self._write_uniq_valid_choices(): w_tot += w_cnt return w_tot def _is_solved(self) -> bool: return np.all(self._grid > 0).item() def _branch_less_vals(self) -> Iterator[tuple[int, int, int]]: ii, jj =...
The main task of the code is to solve a Sudoku-like puzzle by recursively attempting valid values in cells with the fewest options. It first checks for uniquely valid choices, then backtracks by copying the grid and testing possibilities. If any path solves the puzzle, it updates the grid state and returns True; otherw...
def solve(self) -> bool: try: self._loop_uniq_valid_choices() except ValueError: return False if self._is_solved(): return True for v, i, j in self._branch_less_vals(): cp = self.copy() cp.write(v, i, j, unsafe=False) ...
def done(self): return self.value() == 0 def _data(self): return self._table_row()[1] def _known(self, part): return part.equiv(self.zero_part, self.one_part)
The code identifies three specific parts from a collection that meet conditions related to their size and known status. It first verifies the problem is solved, then filters parts based on equivalence to a reference part or size criteria from the solution data. The result is a tuple of these three parts, ensuring exact...
def solution(self): assert self.done() parts = self.parts.values() soln = self._data() sizes = tuple(s for s in range(1, 4) if soln[s - 1]) ones = tuple( p.i for p in parts if p.equiv(self.one_part) or (p.size() in sizes and not self._known(p)...
def calcKernel(self, X, m): self.K = np.zeros((m, m)) for i in range(m): for j in range(m): self.K[i][j] = self.kernel(X[j], X[i]) def getW(self): if self.kernel_stdev is not None: print("Warning kernel is not linear ") return np.dot(self.X.T, se...
The main task of the code is to train a Support Vector Machine (SVM) using a kernel method. It initializes parameters, computes kernel matrices, identifies KKT violators (support vectors), and iteratively optimizes the model by adjusting hyperplanes. The code tracks KKT violations, updates dual variables (gamma), and r...
def fit(self, X): m, _ = X.shape self.X = X self.high = 1/(self.v1*m) self.highPrime = self.epsilon/(self.v2*m) self.gamma = np.random.rand( m)*(self.high + self.highPrime)-self.highPrime print(np.min(self.gamma), np.max(self.gamma)) self.calcKern...
def _create_new_graph() -> Graph: g = Graph() g.vp.id = g.new_vertex_property('string') g.vp.type = g.new_vertex_property('string') g.vp.data = g.new_vertex_property('python::object') g.vp.metadata = g.new_vertex_property('python::object') return g def _process_workflow_step(g: Graph, step: Dict...
The code parses a JSON workflow file into a graph structure by processing each step's class type (Workflow or CommandLineTool), creating nodes and edges, combining input/output relationships, and returning the constructed graph for further analysis or visualization.
def parse(path_to_file: Path) -> Graph: with open(path_to_file) as f: workflow = json.load(f) steps = workflow.get('$graph', []) workflow_graph = _create_new_graph() for step in steps: step_class = step.get('class') if step_class == 'Workflow': workflow_graph = _pr...
def getFuncNode(self, index: int, func_name: Token, func_list: List[Token]) -> Union[FunctionNode, Token]: if func_name[1] == func_list[index][0]: return func_list[index] else: return self.getFuncNode(index+1, func_name, func_list) def getFuncVarList(self, index: int, callArgsLis...
This method evaluates a function call by retrieving the corresponding function node and its variables, executing the function's body to obtain a result, and returning the result along with the original global variable and function lists. It processes the function's arguments, creates a scoped variable list, and execute...
def visit_CallFunctionNode(self, node: CallFunctionNode, var_list: List[Token], func_list: List[Token]) -> Tuple[Union[None, int], List[Token], List[Token]]: # Get the function name func_call_name = node.node_to_call index = 0 # Get the function node with that name function_node...
def get_all_topics(): items = list(Path("./topics").glob("*")) topics = filter(lambda item: os.path.isdir(item), items) topics = map(lambda topic: str(topic), topics) new_topics = [] for topic in topics: new_topics.append(get_props("./" + topic)) return new_topics def get_all_modules_for...
The code aggregates data about topics, modules, and courses into a structured state dictionary. It retrieves all topics and their associated modules, then collects courses while calculating their total estimated time from module properties. The result is a state object containing lists of topics, modules, and courses w...
def get_state(): state = { "topics": [], "modules": [], "courses": [] } # topics & modules for topic in get_all_topics(): modules = get_all_modules_for_topic(topic["path"]) for module in modules: state["modules"].append(module) state["topics"]....
def popgalaxy(size):#this function creates all the planets based on the number it is given for i in range(size): contact = True while contact == True: recpalanet = planet(random.randint(0, (screenW - PLANET_WIDTH)), random.randint(0, (screenH - PLANET_HIEGH...
The main task of the code is to run a simulation involving AI (neural network) and visual rendering using Pygame. It initializes a galaxy, processes user input, updates the simulation state, executes AI logic, and renders the visual map. The loop continues until termination conditions are met, tracking a "Fitness" metr...
def Run(net, a=None, g=None): global planets, Fitness print("Sim Starting") popgalaxy(10) run = True pygame.display.set_caption("Visual Map Gen: " + str(g) + "AI: " + str(a)) clock = pygame.time.Clock() T = 0 Fitness = 0 while run: clock.tick(FPS) T += 1 for e...
def get_signed_url(bucket, obj): # The number of seconds the presigned url is valid for. By default it expires in an hour (3600 seconds) SIGNED_URL_EXPIRATION = os.environ.get('SIGNED_URL_EXPIRATION', 3600) return s3_client().generate_presigned_url( 'get_object', Params={'Bucket': bucket, '...
The code processes a cloud event to extract metadata from a video file. It retrieves the source bucket and video name, generates a signed URL, uses `mediainfo` to analyze the video's structure (container, video/audio/text tracks), parses the output, and compiles metadata. This data is added to the event, logged, and a ...
def main(context: Context): source_attributes = context.cloud_event.get_attributes() logger.info( f'REQUEST:: {to_json(context.cloud_event)}', extra=source_attributes) try: data = context.cloud_event.data srcBucket = data['srcBucket'] srcVideo = data['srcVideo'] me...
def check(self, *args, **kwargs): return self.check_func(*args, **kwargs) def commit(self, *args, **kwargs): return self.respond({}, message="commit not overrode", status=500) def respond403(self): return self.respond({}, "Not Authorized", 403)
This code defines a callable method that checks conditions using `self.check()`. If the check passes, it executes `self.commit()` with provided arguments; otherwise, it returns a 403 Forbidden response via `self.respond403()`. The primary task is to conditionally process inputs with access control or validation logic, ...
def __call__(self, *args, **kwargs): if self.check(*args, **kwargs): return self.commit(*args, **kwargs) else: return self.respond403()
def parseStudentInfo(self, lines): for line in range(len(lines)): if "Term" in lines[line]: yearline = lines[line + 1] break self.student.yearJoined = int(yearline[2]) self.student.termJoined = yearline[3].strip() for line in range(len(lines)): if "Important" in lines[line]: majorline = lines[...
The code reads a PDF file, extracts text, splits it into lines and words, then processes student information, courses taken, and tiles from the parsed data.
def parseInfo(self, path): reader = PdfReader(path) text = "" for page in reader.pages: text += page.extract_text() + "\n" #print for testing ########################### # file_object = open("output.txt", "w+") # file_object.write(text) ########################### lines = text.splitlines() for l...
def get_csv_file(self): # open the csv file, save in self if self.request.files.get('targets_csv', False): csv_file = self.request.files['targets_csv'][0]['body'].decode( 'utf-8').splitlines() return csv_file self.write('csv file missing') def message_gen...
The code processes a CSV file to send personalized emails to recipients. It retrieves configuration details, validates the sender email, extracts subject and recipient data from the CSV, generates email content for each row, and sends emails using a server. If any email fails, the process stops. It returns a "Done" res...
def post(self): config = authenticate.Config.getInstance() server = config.Server sender_email = config.Email if not sender_email: self.set_status(400) self.write({"status": 400}) return subject = self.get_body_argument('subject_field') ...
def _initialize_main(self): root_piece = self._parents[0].pieces[int(random.uniform(0, self._pieces_length))] self._add_pieces_to_main(root_piece.id, (0, 0)) def add_piece_possible(self, piece_id, orientation, position): shared_piece = self._get_shared_piece(piece_id, orientation) if sel...
The main task of the code is to process candidate pieces in priority order, adding them to the main structure if their positions are available and not already present. It uses a priority queue to select pieces, skips duplicates or occupied positions, and either adds them as possible placements or directly integrates th...
def run(self): self._initialize_main() while len(self._candidate_pieces) > 0: _, (position, piece_id), relative_piece = heapq.heappop(self._candidate_pieces) if position in self._taken_positions: continue if piece_id in self._main: s...
def _allocateIP(self): cli_command = f"aws lightsail --no-paginate allocate-static-ip --static-ip-name {uuid.uuid4()} --region {self.__region} --no-cli-pager" result = self._exec_aws_command(cli_command) try: if result["operations"][0]["status"] == "Succeeded": # prin...
The main task of the code is to replace an instance's IP address by allocating a new IP, attaching it to the server, and releasing previously unattached static IPs. It includes error handling and logging, with delays between operations to ensure proper execution.
def _replace_instance_ip(self): try: result = self._allocateIP() time.sleep(1.5) if result != -1: self._attach_static_ip(result, self.__server_name) time.sleep(1.5) result = self._release_static_ip(self._get_unattached_static_ip...
def get_collection(path): return glob.glob(path + '/*.DIR') def get_products(path): """ Get filenames of files in path :param path: CAMS product path, expected AOT, MR and RH in netCDF4 :return: filenames """ files_list = glob.glob(path + '/*') file_mixing_ratio = [b for b in files_list ...
The main task of the code is to generate a synthetic plot from CAMS netCDF data for a specified geographic location (latitude/longitude), using the closest grid point values without interpolation. It accepts input parameters like data directory, coordinates, and an optional site name, then produces a PNG file visualizi...
def main(): """ Produce a synthetic plot from CAMS products for a give site defined by its latitude/longitude. Be aware that the profiles plotted will match the closest (lat,lon) grid of the netCDF files, values are not interpolated to the exact location you give in input. Site name is not mandatory byt...
def context_menu(): # function to display the menu items menu_item = int(input("""Welcome to the book keeper!\nchoose an option from the menu (1-3). 1. add new book 2. view my books 3. search books 4. delete books(s) 5. mark book as read 6....
The main task of the code is to provide a menu-driven interface for managing a reading list, allowing users to add books, retrieve/search books, delete books, mark books as read, or exit. It continuously prompts for input, executes corresponding actions, and handles invalid choices or errors gracefully with a try-excep...
def main(): while True: try: choice = context_menu() if choice == 1: addBook() continue elif choice==2: books = retrieveBooks()...
def to_front(self, bid=None): if bid is not None: num = len(self.render_order) for i in range(num): if self.render_order[i].id == bid: self.render_order.insert(num, self.render_order.pop(i)) break def remake_chains(self, top, bottom...
The code handles dragging an element by bringing it to the front, checking if it belongs to block chains, and remaking the chains if necessary to maintain structure. It updates the visual outline after dragging, ensuring proper element positioning and chain integrity.
def drag(self): if self.hovering_over: self.drag_this = self.hovering_over[-1] self.to_front(self.drag_this.id) if self.drag_this in chain.from_iterable(list(self.block_chains.values())): # remakes blockchains self.remake_chains(top=self.drag_this.parent, bottom=sel...
def create_population(self, n) -> List[List[int]]: population : List[List[int]] = [] for _ in range(self.individuals): population.append(self.create_individual(n)) return population def selection(self, population, c): selection = [(individual, self.fitness(i...
The code implements a genetic algorithm to evolve a population of individuals toward a target fitness value. It parses a formula, initializes a population, iterates through generations by selecting individuals, checking if the best meets the target fitness (m), and breeding new generations if not. If the target is achi...
def Solve(self, n, m, c): formula = parse_formula(c) population = self.create_population(n) for _ in range(self.generations): selection = self.selection(population, formula) if self.fitness(selection[0], formula) == m: return selection[0]...
def _get_height(self, node): if node is None: return 0 return node.height def _balance(self, node): balance = self._get_balance(node) if balance > 1: if self._get_balance(node.left) < 0: node.left = self._rotate_left(node.left) return s...
This function inserts a key-value pair into a binary tree, recursively placing the value in the appropriate left or right subtree. It updates the node's height based on its children's heights and ensures balance using a balancing method, maintaining the tree's structural integrity for efficient operations like search a...
def _insert(self, node, key, value): if node is None: return Node(key, value) elif key < node.key: node.left = self._insert(node.left, key, value) else: node.right = self._insert(node.right, key, value) node.height = 1 + max(self._get_height(node.left...
def _from_ox( term: Optional[Union[ox.NamedNode, ox.BlankNode, ox.Literal, ox.Triple]] ) -> Optional[Union[Node, Tuple[Node, Node, Node]]]: if term is None: return None if isinstance(term, ox.NamedNode): return URIRef(term.value) if isinstance(term, ox.BlankNode): return BNode(te...
The main task of the code is to generate iterator of triples matching a given pattern, converting quads to triples and associating each with their graph context (excluding default graph). It processes input patterns, iterates over matching quads, and yields tuples of converted triples along with their graph name iterat...
def triples( self, triple_pattern: _TriplePattern, context: Optional[Graph] = None, ) -> Iterator[Tuple[_Triple, Iterator[Optional[Graph]]]]: return ( ( (_from_ox(q.subject), _from_ox(q.predicate), _from_ox(q.object)), iter(((_from_ox_graph...
def reset_rotation(self): if self.object == None: return self.object.rotation["angles"] = [0, 0] self.object.rotation["matrix"] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] self.update_canvas() def change_color(s...
The main task of the code is to initialize a GUI application with a canvas for visual elements, right and bottom panels containing interactive controls (buttons, color pickers, checkboxes) for adjusting settings like rotation, zoom, colors, and file operations. It sets up event bindings for mouse interactions (drag, zo...
def __init__(self): super().__init__() # root self.minsize(900, 500) self["bg"] = self.backgroundColor self.title("Obj thing") canvasOffset = [0.015, 0.02] # canvas self.canvas = tk.Canvas(self, background=self.canvasColor) self.canvas.place(rel...
def printa_puzzle(self,puzzle) : print("+----+----+----+") print("| %d | %d | %d |" % (puzzle["a1"], puzzle["a2"], puzzle["a3"])) print("+----+----+----+") print("| %d | %d | %d |" % (puzzle["b1"], puzzle["b2"], puzzle["b3"])) print("+----+----+----+") print("| %d | %d | %d |" % (puzzle["c1"], puz...
This function implements a uniform-cost search algorithm. It sorts nodes by cost, iterates through them to check if any match the goal state, and if found, reconstructs and prints the path of actions taken. If not, it processes successors.
def custo_uniforme(self, lista_nos, objetivo, lista_ordenada) : print("Objetivo: ") self.printa_puzzle(objetivo) print("-----------------------") lista_ordenada = sorted (lista_nos, key = no.custo) for no in lista_ordenada : print("-----------------------") self.printa_puzzle(no.estado) print(no.aca...
def printa_puzzle(self,puzzle) : print("+----+----+----+") print("| %d | %d | %d |" % (puzzle["a1"], puzzle["a2"], puzzle["a3"])) print("+----+----+----+") print("| %d | %d | %d |" % (puzzle["b1"], puzzle["b2"], puzzle["b3"])) print("+----+----+----+") print("| %d | %d | %d |" % (puzzle["c1"], puz...
The code performs a breadth-first search (BFS) to find a path from the initial state to the goal state. It iterates through nodes in a list, checking if a node's state matches the objective. If found, it reconstructs the path by backtracking through parent nodes, collecting actions. If not, it generates successors and ...
def busca_largura(self, lista_nos) : i = 0 for no in lista_nos : print("ESTADO") self.printa_puzzle(no.estado) print("OBJETIVO") self.printa_puzzle(self.objetivo) print(len(lista_nos)) if self.compara(no.estado) == True : print("Achou") print(no.acao) lista_acao = [] pai = no.pai ...
def compara(self,original) : for chave in original : if original[chave] != self.objetivo[chave] : return False return True def sucessor(self, puzzle, lista) : base_up = copy.deepcopy(puzzle.estado) base_down = copy.deepcopy(puzzle.estado) base_left = copy.deepcopy(puzzle.estado) ba...
The main task of the code is to recursively search for a goal state in a list of nodes. If the goal is found, it backtracks through the node's parent chain to collect and return the sequence of actions taken to reach the goal. If not found, it processes the next node by generating successors, sorting them, and continui...
def gme (self, lista_nos, h) : no = lista_nos[0] if self.compara(no.estado) == True : print("Achou") print(no.acao) lista_acao = [] pai = no.pai lista_acao.append(no.acao) while (pai != None) : pai_acao = pai.acao print(pai_acao) lista_acao.append(pai_acao) pai = pai.pai retu...
def compara(self,original) : for chave in original : if original[chave] != self.objetivo[chave] : return False return True def sucessor(self, puzzle, lista) : base_up = copy.deepcopy(puzzle.estado) base_down = copy.deepcopy(puzzle.estado) base_left = copy.deepcopy(puzzle.estado) ba...
This code implements the A* (A-star) algorithm to find a path to a goal state. It recursively explores nodes, checks if the current node's state matches the goal, and if not, generates successors, sorts them using a heuristic, and continues the search. If the goal is found, it reconstructs and returns the sequence of a...
def aEstrela(self, lista_nos, h) : no = lista_nos[0] if self.compara(no.estado) == True : print("Achou") print(no.acao) lista_acao = [] pai = no.pai lista_acao.append(no.acao) while (pai != None) : pai_acao = pai.acao print(pai_acao) lista_acao.append(pai_acao) pai = pai.pai r...
def compara(self,original) : for chave in original : if original[chave] != self.objetivo[chave] : return False return True def printa_puzzle(self,puzzle) : print("+----+----+----+") print("| %d | %d | %d |" % (puzzle["a1"], puzzle["a2"], puzzle["a3"])) print("+----+----+----+") print("|...
This function performs a depth-limited search to find a goal state. It iteratively explores nodes from a list, checking if each node's state matches the objective. If not, it generates successors (if within the depth limit) and continues searching. It returns the solution node if found, otherwise returns None after exh...
def busca_profundidade_limitada (self, lista_nos, objetivo, limite) : while len(lista_nos) > 0 : no = lista_nos.pop() if self.compara(no.estado, objetivo) == True : print("Achou") self.printa_puzzle(no.estado) return no else : if no.profundidade < limite : self.sucessor(no, lista_nos)...
def download(download_url = None, filename_to_save = None): """function for python 2/3 compatible file download from url""" if download_url is None or download_url == '': show_error('[RPA][ERROR] - download URL missing for download()') return False # if not given, use last part of url as f...
This function downloads essential TagUI files from GitHub to a specified directory, ensuring they are only downloaded once per version. It checks for existing files, skips download if already present, sets execution permissions on Linux/Mac, and creates a version marker file to prevent redundant downloads in future ses...
def _tagui_delta(base_directory = None): """function to download stable delta files from tagui cutting edge version""" global __version__ if base_directory is None or base_directory == '': return False # skip downloading if it is already done before for current release if os.path.isfile(base_directo...
def tagui_location(location = None): """function to set location of TagUI installation""" global _tagui_location if location is not None: _tagui_location = location return _tagui_location def download(download_url = None, filename_to_save = None): """function for python 2/3 compatible file download ...
This function patches macOS systems by downloading and installing PhantomJS v2.1.1 to resolve OpenSSL compatibility issues. It checks the operating system, downloads a specific ZIP file, extracts it, renames directories, sets permissions, and ensures the updated PhantomJS is used while handling errors if the download f...
def _patch_macos_pjs(): """patch PhantomJS to latest v2.1.1 that plays well with new macOS versions""" if platform.system() == 'Darwin' and not os.path.isdir(tagui_location() + '/.tagui/src/phantomjs_old'): original_directory = os.getcwd(); os.chdir(tagui_location() + '/.tagui/src') print('[RPA]...
def download(download_url = None, filename_to_save = None): """function for python 2/3 compatible file download from url""" if download_url is None or download_url == '': show_error('[RPA][ERROR] - download URL missing for download()') return False # if not given, use last part of url as f...
The code's main task is to generate an offline update script (update.py) for RPA for Python on air-gapped systems. It downloads latest RPA/TagUI files, zips them, and embeds the zip as base64 in update.py. The script extracts the update to a system-specific directory, sets permissions, and replaces the existing rpa.py ...
def update(): """function to update package and TagUI files on an air-gapped computer without internet""" print('[RPA][INFO] - pack() is to deploy RPA for Python to a computer without internet') print('[RPA][INFO] - update() is to update an existing installation deployed from pack()') print('[RPA][INFO...
def tagui_location(location = None): """function to set location of TagUI installation""" global _tagui_location if location is not None: _tagui_location = location return _tagui_location def _python3_env(): """function to check python version for compatibility handling""" return not _python2_en...
This code installs and configures TagUI in the user's home directory across Linux/macOS/Windows. It handles OS-specific setup: downloads/unzips TagUI, sets execution permissions, patches dependencies (PHP, OpenSSL), installs Visual C++ Redistributable on Windows, and verifies prerequisites. It ensures TagUI is ready fo...
def setup(): """function to setup TagUI to user home folder on Linux / macOS / Windows""" # get user home folder location to setup tagui home_directory = tagui_location() print('[RPA][INFO] - setting up TagUI for use in your Python environment') # special check for macOS - download() will fail du...
def editRecipient(index, recipient): donationsTable.update_item( Key = {'index':index}, UpdateExpression = f'set recipient = :a', ExpressionAttributeValues={':a':recipient}, ) def editStatus(index,status): donationsTable.update_item( Key = {'index':index}, UpdateExpre...
This function processes a POST request to remove a specific item from a user's priority list in a DynamoDB table. It validates the request, checks user existence, verifies the item index, updates the user's priority items, and triggers status and recipient updates. The response indicates success or errors related to in...
def acceptItem(request): if request.method != 'POST': return HttpResponse(json.dumps({'status':300,'error':'Invalid Request'})) body = request.body obj = json.loads(body.decode('utf-8').replace("'", '"')) username = obj['username'] index = obj['index'] response = usersTable.query( ...
def _demote_node(self, i, n): """Demotes a node, e.g. following a collision. randomize: demote at random this: demote this otherwise, demotes the other slot.""" # We demote the node and go to the unaffected child. assert n >= 0 m = 2 ** n assert 0 <= i < m...
This function updates network node incentives and policies based on collision/usage events. It adjusts kind_incentive and empty_incentive values through division/multiplication with adaptation factors, tracks collision/usage counts, and conditionally demotes nodes or inserts new policies using random probabilities. Fin...
def learn(self, collision=0, used=0, name=None): """collision = a collision occurred on the network; used = the network slot was used (by us or others)""" # What we did was in self.decision and self.transmit. # Let us try then to compute the four cases. if collision: ...
def HuffmanCodeSolve(): N = int(input("How many char? ")) print("Enter {} line: <char> <frequency>".format(N)) C = ['?' for _ in range(N)] P = [0 for _ in range(N)] for i in range(N): L = input("Data {}: ".format(i + 1)).strip().split(' ') C[i], P[i] = L[0], int(L[1]) T = sum(P) ...
The code implements a Huffman coding interface, allowing the user to choose between encoding or decoding data. It initializes a HuffmanCodeSolve instance and directs execution to either the Encode or Decode function based on user input, with an error message for invalid choices.
def HuffmanCode(): H = HuffmanCodeSolve() Choice = int(input("1: Encode, 2: Decode. Your choice? ")) if Choice == 1: Encode(H) elif Choice == 2: Decode(H) else: print("Are you kidding me?")
def get_month_names(): """ Return list with months names """ result = [] # If it possible get months names in system language try: with TimeEncoding("%s.%s" % getdefaultlocale()) as time_enc: for i in range(1, 13): result.append(month_name[i].decode(time_enc)) ...
The main task of the code is to prepare date-related data for UI display. It retrieves month names (local/English), day abbreviations, sets the current date, constructs a title with month/year, and identifies the current quarter. This prepares information for rendering calendar widgets or date-based interfaces.
def prepare_data(self): """ Prepare data for showing on widget loading """ # Get days abbrs and month names lists self.month_names = get_month_names() self.month_names_eng = get_month_names_eng() self.days_abrs = get_days_abbrs() # Today date se...
def readin(puzzle_input): a = puzzle_input.splitlines() b = [x.split('contain') for x in a] bagsdict = {} for y in b: if y[1] == ' no other bags.': bagsdict[y[0].strip().rstrip('s')] = 0 else: bagsdict[y[0].strip().rstrip('s')] = [s[2:].strip('s.').strip() for s ...
The code solves a puzzle involving counting bags that can contain or are required to carry a "shiny gold bag." It reads input data twice, processes it to find combinations of bags that can hold the target bag and calculates the total count of individual bags needed. The function yields two results: the number of distin...
def solve(puzzle_input): bag1 = 'shiny gold bag' bagsdict = readin(puzzle_input) qb = readin2(puzzle_input) s1 = findcombos(bagsdict,bag1) s2 = count(qb,bag1) yield s1 yield s2
def maskrep2(dec,mask): bin = str(dectobin(dec)) maskedbin = "" for i in range(1,len(mask)+1): if mask[-i] == 'X' or mask[-i] == '1': maskedbin += mask[-i] else: if i <= len(bin): maskedbin += bin[-i] else: maskedbin += '0' ...
The code processes a list of instructions to apply a bitmask to memory addresses, generating all possible addresses from the masked values. It stores the given value at each derived address in a dictionary and returns the sum of all stored values.
def part2followinst(instructions): mem = {} for inst in instructions: if inst[0] == 0: mask = inst[1] elif inst[0] == 1: addr0 = inst[1][0] val = inst[1][1] maskedaddr = maskrep2(addr0,mask) addrlist = floattolist(maskedaddr) ...
def readin(puzzle_input): preproc = puzzle_input.splitlines() instr = [] for i in range(len(preproc)): if re.match("mask",preproc[i]) is not None: instr.append( ( 0, preproc[i][7:] ) ) else: instr.append( (1, ( int(preproc[i].split('[')[1].split(']')[0]), int(preproc...
The code processes a puzzle input by reading it, then computes two separate solutions (s1 and s2) using part1followinst and part2followinst functions. It yields both results sequentially, likely for a two-part puzzle challenge, returning answers for each section.
def solve(puzzle_input): instr = readin(puzzle_input) s1 = part1followinst(instr) s2 = part2followinst(instr) yield s1 yield s2
def readin(puzzle_input): a = puzzle_input.splitlines() time = int(a[0]) l = [] for x in a[1].split(','): if re.match('\d',x) is not None: l.append(int(x)) return (time,tuple(l),tuple(a[1].split(','))) def finddeparttime(time,buslist): percent = [time%x for x in buslist] ...
The code processes a puzzle input to compute two key values: the earliest departure time (`s1`) based on given time and bus schedule, and a sequence of subsequent departure times (`s2`) using the bus list and original list for reference. It reads input data, calculates these values via helper functions, and yields them...
def solve(puzzle_input): time, buslist,oglist = readin(puzzle_input) s1 = finddeparttime(time,buslist) s2 = findsubseqtimes(buslist,oglist) yield s1 yield s2
def plot_shap_pairwise(df1, df2,ignore=[],nbrmax=20): target='fake_target_547454889' x=df1.copy() x[target]=0 xx=df2.copy() xx[target]=1 x=pd.concat([x,xx],axis=0) return plot_shaps(x,target,ignore,nbrmax) def pairwise_feature_stat_per_day(df1,df2,target,figsize=(20,4),linewidth=2.0,me...
The main task of the code is to generate a comparative analysis report between two dataframes (df1 and df2), focusing on SHAP values, feature statistics, missing values, and correlation metrics. It optionally targets specific variables, detects time-series data, and visualizes differences in feature importance, data di...
def pairwise_report(df1,df2,target=None,ignore=[],nbrmax=None,full=True,nbrmax20=20): if target!=None and target not in df.columns.to_list(): print("{} not in dataframe - Ignore".format(target)) target=None nbrmax=nbrmax if nbrmax!=None else max(df1.shape[1],df2.shape[1]) ...
def get_feature_info(df,feature): if feature in df.columns: cardinality = df[feature].nunique() missed= 100 * df[feature].isnull().sum() / df.shape[0] feature_type = get_feature_type(df[feature]) return [feature_type,cardinality,missed] else: return "","","" def plot_stat...
The function `print_features` analyzes and visualizes the statistical properties of features in a DataFrame, including their data types, cardinality, missing values, and relationships with a target variable. It generates histograms, box plots, scatter plots, and performs ANOVA tests to explore feature distributions, co...
def print_features(df,target=None,sorted_features=[]): #explore features selected by shap (sorted_features) features = sorted_features if len(sorted_features)>0 else df.columns.to_list() _,tg_cardinality,_ = get_feature_info(df,target) numeric=df.select_dtypes(include=np.number).columns.tolist() ...
def get_feature_info(df,feature): if feature in df.columns: cardinality = df[feature].nunique() missed= 100 * df[feature].isnull().sum() / df.shape[0] feature_type = get_feature_type(df[feature]) return [feature_type,cardinality,missed] else: return "","","" def header(ti...
The main task of the code is to analyze feature interactions in a dataset by identifying significant relationships between candidate features and numeric targets using ANOVA tests, visualizations, and post-hoc analysis. It processes categorical/boolean and binned numeric features, filters top-value combinations, and re...
def interactions2x(ddf,feature=[],target=[],maxnbr=4,bins=True): df=ddf.copy() with pd.option_context('mode.use_inf_as_na', True): if df.isnull().values.any(): print('Warning: dataframe contains nan or inf , please fix or drop them to obtain better results. \n') df=...
def safe_convert(s): try: return pd.to_datetime(s, errors='ignore') except: a=0 return s def header(title,sz='h2'): print('\n \n') display(HTML("<hr>")) display(HTML("<{} align=\"center\">{}</{}>".format(sz,title,sz))) print('\n ') def print_na(df,maxnbr=None): max...
This function performs Exploratory Data Analysis (EDA) on a DataFrame, checking for missing values, visualizing SHAP values for feature importance, time series patterns, Pearson/Cramers V correlations, and top correlated features. It handles data types, ignores specified columns, and returns sorted important features f...
def do_eda(df,target,ignore=[],nbrmax=None,figsize=(20,4),linewidth=2): if target!=None and target not in df.columns.to_list(): print("{} not in dataframe - Ignore".format(target)) target=None if nbrmax==None: print('Shap values for max 20 most important features will be pl...
def analytical(target): x,y,z,roll,pitch,yaw = target theta = np.zeros(6) -math.pi/2 theta[0] = math.atan2(-(y+0.4),-x) # if theta[0] < 0: # theta[0] = theta[0] + 2 * math.pi angle_1 = (np.square(0.63)+ np.square(x)+np.square(y)+np.square(z) - np.square(0.58))/ (2*0.63*math.sqrt(np.square(x...
This code performs inverse kinematics (IK) to compute joint angles (new_theta) that position a robotic end-effector at a target location. It uses a numerical method combining Jacobian transpose updates, momentum-based velocity adjustment, and joint angle constraints. The loop iterates until the end-effector error falls...
def IK(current_theta,target_pos, ACCEPTANCE = 0.0005): # new_theta = current_theta.copy() new_theta = analytical(target_pos) d_err = target_pos - fwd_kinematics( new_theta ) # fwd_kinematics is to calculate the End effector ### Momentum Parameter ### alpha = 1 ########################## ...
def read_csv(filepath : str) : """Read csv file as UTF8 encoding. Args: filepath (str) : directory of csv file. Returns: pd.read_csv(filepath, sep=",", encoding="UTF8") """ import pandas as pd return pd.read_csv(filepath, sep=",", encoding="UTF8") def return_data_dir(Game_name...
This function deletes data from specified files based on their type. For type 1 (Game_list.txt), it removes a game's directory after verifying its existence. For type 2 (Package_data_Game_name.txt), it deletes a package's data and recalculates efficiency. Unsupported types trigger error messages with available options.
def delete_data(File_path : str, File_type : int) -> None: """Delete data at [File_path] file Args: File_path (str): File_path (str): directory of file File_type (int): type of [File_path] file. More details at check_file_type(File_path : str) function. """ import pandas as pd if ...
def read_csv(filepath : str) : """Read csv file as UTF8 encoding. Args: filepath (str) : directory of csv file. Returns: pd.read_csv(filepath, sep=",", encoding="UTF8") """ import pandas as pd return pd.read_csv(filepath, sep=",", encoding="UTF8") def create_game_list(Game_nam...
The code adds data to a specified file based on its type. For type 1 (Game_list.txt), it prompts the user for a game name and updates the game list, creating directories if empty. For type 2 (Package_data_Game_name.txt), it collects package details (name, price, value), validates inputs, and appends them to the game's ...
def add_data(File_path : str, File_type : int) -> None: """Add data to [File_path] file Args: File_path (str): directory of file File_type (int): type of [File_path] file. More details at check_file_type(File_path : str) function. """ import pandas as pd is_empty = False try :...
def read_csv(filepath : str) : """Read csv file as UTF8 encoding. Args: filepath (str) : directory of csv file. Returns: pd.read_csv(filepath, sep=",", encoding="UTF8") """ import pandas as pd return pd.read_csv(filepath, sep=",", encoding="UTF8") def check_file_type(File_path...
The main task of the code is to manage a data file by reading its contents, displaying game-related data or empty status, and allowing users to perform operations like adding/deleting data based on input validation. It checks file existence, handles errors, restricts operations when the file is empty, and executes corr...
def manage_data(File_path : str) : """Excute specific operation to [File_path] file Args: File_path (str): directory of file """ is_empty = False try : data = read_csv(File_path) print("Revealing data in file...") print("-------------------------------------------...
def face_embedding(img): if model_name=='lbp': imgr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) imgr = cv2.resize(imgr,(108,108)) ##return the reshaped image x = extract_hist(imgr) elif model_name == 'dlib': fl = [[0,len(img)-1,len(img[0])-1,0]] x = face_model.face_encodin...
The function `saliency_minusFast` computes a saliency map by iteratively removing regions from image B to minimize its similarity to image A. It calculates initial embeddings for A and B, then iteratively updates B by removing Gaussian masks that reduce their similarity score. The process tracks score differences (dsc)...
def saliency_minusFast(A,B,nh,d,n,nmod,th): N = A.shape[0] M = A.shape[1] H1 = np.zeros((N,M)) xA = face_embedding(A) xB = face_embedding(B) sc0 = np.dot(xA,xB) st = "{:7.4f}".format(sc0) print('minus t = 000 sc[0]='+st) #imshow(cv2.hconcat([A,B]),show_pause=1,title=...
def MaskedImages(A,s,d,gauss_min,origin,Ao,type='Remove'): height = A.shape[0] width = A.shape[1] H2 = height+2*s; W2 = width+2*s; nh = range(0,H2-s,d) nw = range(0,W2-s,d) N = len(nh)*len(nw) xy = np.zeros((N,2)) h = 1-gaussian_kernel(s,s/8.5,type='Max') k = 0 xo = np.ones((H2,W2)) ...
This function computes a saliency map 'D' by processing input images (Ao) with parameters (ss, th, steps, min_gauss), generating masked image coordinates (xy), calculating errors (S) through ComputeError, and marking high-saliency regions (>th) in a 2D grid. It returns a saliency map highlighting significant regions ba...
def saliency_1(Ao,B,p,model_name,origin, target, fmt,face_model=None,show=False): print('computing saliency-1...') ss = p[0] th = p[1] steps = p[2] min_gauss = p[3] A = Ao height = A.shape[0] width = A.shape[1] ix = np.ones((50000,1)) xy,N...
def MaskedImages(A,s,d,gauss_min,origin,Ao,type='Remove'): height = A.shape[0] width = A.shape[1] H2 = height+2*s; W2 = width+2*s; nh = range(0,H2-s,d) nw = range(0,W2-s,d) N = len(nh)*len(nw) xy = np.zeros((N,2)) h = 1-gaussian_kernel(s,s/8.5,type='Max') k = 0 xo = np.ones((H2,W2)) ...
This function computes a saliency map 'D' by iteratively generating masked images, processing them with a model, and updating saliency values based on error reduction. It initializes parameters from 'p', loops until error threshold 'th' is met, updates the image 'A' with processed results, and marks saliency at each it...
def saliency_2(Ao,B,p,model_name,origin, target, fmt,face_model=None,show=False): print('computing saliency-2...') ss = p[0] th = p[1] steps = p[2] min_gauss = p[3] A = Ao err = 0 k = 0 height = A.shape[0] width = A.shape[1] D = np.zeros((heigh...
def MaskedImages(A,s,d,gauss_min,origin,Ao,type='Remove'): height = A.shape[0] width = A.shape[1] H2 = height+2*s; W2 = width+2*s; nh = range(0,H2-s,d) nw = range(0,W2-s,d) N = len(nh)*len(nw) xy = np.zeros((N,2)) h = 1-gaussian_kernel(s,s/8.5,type='Max') k = 0 xo = np.ones((H2,W2)) ...
This function computes a saliency map D by iteratively optimizing an image A through masked processing, error computation, and updates. It initializes random A, applies masked transformations (via MaskedImages), processes images with a model (process_folder), computes errors (ComputeError), and updates D with error val...
def saliency_3(Ao,B,p,model_name,origin, target, fmt,face_model=None,show=False): print('computing saliency-3...') ss = p[0] th = p[1] steps = p[2] min_gauss = p[3] height = B.shape[0] width = B.shape[1] A = np.random.rand(height,width,3) err = 1 k =...
def MaskedImages(A,s,d,gauss_min,origin,Ao,type='Remove'): height = A.shape[0] width = A.shape[1] H2 = height+2*s; W2 = width+2*s; nh = range(0,H2-s,d) nw = range(0,W2-s,d) N = len(nh)*len(nw) xy = np.zeros((N,2)) h = 1-gaussian_kernel(s,s/8.5,type='Max') k = 0 xo = np.ones((H2,W2)) ...
The function computes saliency-minus maps through iterative error minimization. It generates masked images, processes folders, computes errors, and updates saliency maps (Ho, H) by subtracting errors from initial values. The loop iterates up to kmax times, adjusting the input image (A) each step to refine saliency esti...
def saliency_minus(Ao,B,p,model_name,origin, target, fmt,face_model=None,show=False,error_Yo='dot'): print(' ') print('computing saliency-minus:') print('=========================') ss = p[0] th0 = p[1] steps = p[2] min_gauss = p[3] kmax = p[4] th1 = p[...
def MaskedImages(A,s,d,gauss_min,origin,Ao,type='Remove'): height = A.shape[0] width = A.shape[1] H2 = height+2*s; W2 = width+2*s; nh = range(0,H2-s,d) nw = range(0,W2-s,d) N = len(nh)*len(nw) xy = np.zeros((N,2)) h = 1-gaussian_kernel(s,s/8.5,type='Max') k = 0 xo = np.ones((H2,W2)) ...
The function computes a saliency-plus map by iteratively adjusting an image (A) to minimize error between masked regions and target outputs. It uses a model to process images, computes error metrics, and updates a saliency map (H) based on error differences. The loop runs up to kmax iterations, refining the map until e...
def saliency_plus(Ao,B,p,model_name,origin, target, fmt,face_model=None,show=False,error_Yo='dot'): print(' ') print('computing saliency-plus:') print('=========================') ss = p[0] th0 = p[1] steps = p[2] min_gauss = p[3] kmax = p[4] th1 = p[5]...
def identify_connections(to_process): if len(to_process) == 1: return [[str.strip(n) for n in to_process[0].split(',')]] elif len(to_process) == 2: nodes = [] parents = [str.strip(n) for n in to_process[0].split(',')] children = [str.strip(n) for n in to_process[1].split(',')] ...
This code translates Mermaid diagram syntax into BUGS model code by parsing nodes, their connections, and generating corresponding probabilistic model definitions with variable substitutions and distribution functions. It processes Mermaid lines to identify nodes, creates node objects, and constructs BUGS code with pro...
def translate_v2(mermaid_code): # Array of order to create everything, add stuff to this after each line of the file is processed nodes_to_process = [] lines = [str.strip(line) for line in mermaid_code.splitlines()] for index, line in enumerate(lines): # Skip blank lines if line ==...
def __is_account_already_exists(self, account: Account) -> bool: accounts = self.get_all_accounts() res = [True if equal_accounts(account, acc) else False for acc in accounts] return any(res) def get_all_accounts(self) -> List[Account]: with open('{}.csv'.format(self.__filename), 'r') as...
This code removes an existing account from a CSV file by checking its existence, retrieving all accounts, finding its index, removing it from the list, and updating the CSV file with the modified list.
def remove_account(self, account: Account): if self.__is_account_already_exists(account) is True: accounts = self.get_all_accounts() index = find_account_index(accounts, account) accounts.pop(index) self.__write_accounts_in_csv_file(accounts)