dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def date_in_bound(self, start: datetime.date, end: datetime.date) -> bool: assert start < end return self.getStartTime() < end and self.getEndTime() >= start def getStartTime(self) -> datetime.date: self._sanity_check() if self.isPeriod(): return self.start else: ...
The function calculates the intersection of two date ranges. It returns the overlapping period as a tuple (start, end), where start is the later of the input start date and the object's start time, and end is the earlier of the input end date and the object's end time. If the input dates are outside the object's bounds...
def date_intersection(self, start: datetime.date, end: datetime.date) -> Tuple[datetime.date, datetime.date]: if not self.date_in_bound(start, end): return None, None return max(self.getStartTime(), start), min(self.getEndTime(), end)
def tensorsFromPair(pair): input_tensor = tensorFromSentence(input_lang, pair[0]) target_tensor = tensorFromSentence(output_lang, pair[1]) return (input_tensor, target_tensor) def make_batch(training_pairs): lengths1 = [] lengths2 = [] for i in training_pairs: lengths1.append(len(i[0])) ...
This function trains an encoder-decoder sequence-to-sequence model with attention mechanism using Adam optimization. It processes training data in batches, computes loss with NLLLoss, and tracks/prints loss statistics at specified intervals while visualizing training progress. The model learns to map input sequences to...
def trainIters(encoder, decoder, n_epochs, print_every=100, plot_every=100, learning_rate=3e-4, batch_size=16): plot_losses = [] print_loss_total = 0 # Reset every print_every plot_loss_total = 0 # Reset every plot_every encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate) decod...
def tensorsFromPair(pair): input_tensor = tensorFromSentence(input_lang, pair[0]) target_tensor = tensorFromSentence(output_lang, pair[1]) return (input_tensor, target_tensor) def make_batch(training_pairs): lengths1 = [] lengths2 = [] for i in training_pairs: lengths1.append(len(i[0])) ...
The function evaluates a sequence-to-sequence model (encoder-decoder) on a batch of test data starting from a specified index. It prepares input and target tensors, generates predicted outputs using the model, and converts tensor indices to human-readable words. It organizes input words, predicted outputs, and actual t...
def evaluateRandomly(encoder, decoder, starting_point): training_pairs = [tensorsFromPair(testing_pairs[i]) for i in range(starting_point, starting_point+batch_size)] pair = training_pairs input_tensor, target_tensor, lengths_input, lengths_target = make_batch(pair) input_words, ou...
def single_ingredients(ingredient_list): ingredients = re.split("\r|\n",ingredient_list) while '' in ingredients: ingredients.remove('') return ingredients def get_weight(ingredient_string:str): components = re.split(' |,',ingredient_string.strip()) weight_string = components[-1] weight_...
The main task of the code is to save a recipe's ingredients, calculate their calorie contributions, and store them in the database. It first deletes existing related records, processes each ingredient to extract weight and FDC ID, calculates calories using the FDC ID, logs contributions, handles missing ingredients, an...
def save(self, desc,origin:Recipe, *args, **kwargs): DetailedRecipeCalorieContributions.objects.filter(parent_recipe_id = origin).delete() DetailedRecipe.objects.filter(origin_id = origin).delete() logging.warning("saving recipe for origin: "+origin.__str__()) self.origin_id = origin ...
def initialize_parameters_deep(layer_dims): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (...
The function `L_layer_model` trains a multi-layer neural network for binary classification. It initializes deep learning parameters, performs forward propagation with ReLU activation for hidden layers and Sigmoid for the output, computes the cost, executes backpropagation to calculate gradients, and updates parameters ...
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False): """ Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID. Arguments: X -- data, numpy array of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (c...
def get_tweetid(self) -> int: """ :return: the unique id of a tweet """ return self.tweet_json["id"] def get_tweet(self) -> str: """Get the content of a tweet""" return self.tweet_json["text"] def get_hashtags(self) -> list: """ :return: a list of the hash...
The main task of the code is to construct and return a dictionary containing key information about a tweet, including its ID, text, hashtags, date, retweet count, user details, stock-related data, and sentiment analysis. The function aggregates these values by calling specific methods and attributes, organizing them in...
def construct_tweet_json(self): """ :return dict containing all the different information about a certain tweet """ tweet = { "id": self.get_tweetid(), "text": self.get_tweet(), "hashtags": self.get_hashtags(), "date": self.get_date...
def read_data(): f = open("C:/Users/ioana/OneDrive/Documents/Facultate/Semestrul 4/Inteligenta " "artificiala/Laborator/Artificial-Intelligence-Lab2/hard.txt", "r") n = int(f.readline()) matrix = [] # reading the matrix for i in range(n): line = f.readline() matrix.appe...
The main task of the code is to read input data containing a matrix, source, and destination nodes, compute minimal paths using a solver function, and write the updated matrix along with path details to output. The `solve` function processes the matrix to determine shortest paths, returning multiple path lists and modi...
def main(): data = read_data() n = data[0] matrix = data[1] source = data[2] destination = data[3] matrix, minimal_path_list, minimal_path, minimal_path_list_sd, minimal_path_2 = solve(matrix, source, destination) write_data(matrix, minimal_path_list, minimal_path, minimal_path_list_sd, mini...
def check_agent_pods_state(v1, agents): global agent_pod_name print("Checking for agent pods ... expected {}".format(agents)) agents_check_failed = check_pods_running(v1, AGENT_POD_LABEL_SELECTOR, agents) if not agents_check_failed: print("Wrong numbe...
(The function checks the state of Akri components in a Kubernetes namespace by verifying the existence of agents, controllers, instances, brokers, config services, and instance services, using Kubernetes API calls and helper functions to ensure all expected resources are present and in the correct state.)
def check_akri_state(agents, controllers, instances, brokers, config_svcs, instance_svcs, namespace="default"): print( "Checking for Akri state ... expected agent(s):{}, controller(s...
def _drawBox(self, stack, layer): x = self._stackX(stack) y = self._layerY(layer) color = self._getColorCode(self._yard[stack][layer]) self._drawBoxAtPosition(x,y,color) def _stackX(self, stack): return self._screenMargin + self._boxMargin + stack * self._boxSpaceWidth() + self._penWidth def _layer...
The code draws a stack of boxes by iterating through each box in the specified stack and calling _drawBox for each. It then calculates coordinates to draw a border line around the stack's base, creating a visual outline using Pygame's draw.lines method.
def _drawStack(self, stack): for l in range(len(self._yard[stack])): self._drawBox(stack,l) x = self._stackX(stack) - self._boxMargin - self._penWidth y = self._layerY(-1) + self._bottomMargin pygame.draw.lines(self._screen, self._penColor, False, [(x, y - 5), (x, y), (x + self._boxSpaceWidth(), ...
def _checkSpeed(self): speedInvalid = False if type(self.speed) is not int: speedInvalid = True if not (self.speed in range(len(self._speeds))): speedInvalid = True if speedInvalid: self.speed = 0 # reset speed to zero print('speed must be an integer between 0 and ' + str(len(sel...
This function animates the movement of an arm in a specified direction (down, left, right, or idle) by incrementally adjusting its height or X-position based on predefined speed settings. It checks for user events, updates the display, and ensures the arm reaches the target position before completing the animation. The...
def _animate(self, *args): self._checkSpeed() self._armX = self._stackX(self._stack) if (args[0] == 'down'): self._armHeight = self._armTopHeight targetLayer = len(self._yard[self._stack]) if self._color == '': targetLayer -= 1 targetHeight = self._layerY(targetLayer) el...
def _expand_inputs(inp, n, var_name): """ Handle inputs provided. For n_depth and dropouts, if input is a value, return list with length equal to number of pooling layers. For kernel sizes, if input is tuple, make a list of the same tuple, for all pooling layers. If it is a list, ensure th...
Your return The function `build_Unet_flex` constructs a customizable U-Net-like neural network for image segmentation. It defines encoder-decoder paths with configurable convolutional layers, pooling, upsampling, and activation functions. The architecture ensures input/output size consistency, supports varied filter de...
def build_Unet_flex(img_shape, n_depth = 1, n_pools = 4, activation = 'lrelu', \ batch_norm = True, kern_size = (3,3), kern_size_upconv = (2,2), pool_size = (2,2), dropout_level = 1.0,\ loss = 'binary_crossentropy', stdinput = True): """ Define your own Unet-like archit...
def _check_except(except_: Except) -> Tuple[Type[Exception], ...]: if isinstance(except_, tuple): for i, e in enumerate(except_): if not isinstance(e, type) or not issubclass(e, Exception): raise InvalidArgument( f"Expected an Exception but got except_[{i}]={e...
The code generates property-based test code for a given function, ensuring valid inputs only trigger expected exceptions. It creates test functions (in pytest or unittest style) with Hypothesis strategies, handling specified exceptions and including necessary imports. The generated test validates function behavior by r...
def fuzz(func: Callable, *, except_: Except = (), style: str = "pytest") -> str: """Write source code for a property-based test of ``func``. As for all ghostwriters, the ``except_`` argument should be an :class:`python:Exception` or tuple of exceptions, and ``style`` may be either ``"pytest"`` to write...
def get_ext(filename): ext = filename.split('.')[-1].lower() if filename.lower().endswith('.jpeg'): ext = '.jpg' return ext def get_timestamp(f, name): ext = get_ext(name) if ext == 'jpg' or ext == 'png': return get_exif_timestamp(f, name) if ext == 'mp4': return get_mp4_...
The main task of the code is to generate a new filename by combining the original file's extension, a timestamp, and a hash value. It opens the file, extracts its extension, retrieves a timestamp and hash, then formats them into a structured string with date, time, and hash components to create a unique filename.
def create_filename(filename): with open(filename, 'rb') as f: ext = get_ext(filename) ts = get_timestamp(f, filename) if ts is None: return None h = get_hash(f) return "{y:02d}{m:02d}{d:02d}_{h:02d}{M:02d}{s:02d}_{H:08x}.{e}" \ .format(y=ts.year, ...
def BuildTree(self): if self.verbose: print("Building tree...") self.tree = cKDTree(self.pos, boxsize=self.boxsize) def TreeUpdate(self): """ Computes or updates the neighbor lists, smoothing lengths, and densities of particles. """ if self.tree is None: ...
The main task of the code is to reconstruct a function defined on meshoid points at arbitrary target points using nearest-neighbor interpolation with optional linear or quadratic corrections. It computes values at target points by querying their nearest neighbors, applying gradient and second-derivative terms based on ...
def Reconstruct(self, f: np.ndarray, target_points: np.ndarray, order: int = 1): """ Gives the value of a function f colocated on the meshoid points reconstructed at an arbitrary set of points Parameters ---------- f : array_like The quantity defined on the s...
def get_class_mean_image(class_name): file_name = f'mean_image_{class_name}.png' try: mean_image = io.imread(file_name, as_gray=True) except FileNotFoundError: mean_image = create_class_mean_image(file_name, class_name) return mean_image def get_image(directory, image_name): image_pa...
This function processes images from multiple classes to extract features relative to a normal image, then organizes these features into a database structure. It iterates through each class, loads images, computes features using a normal image reference, and stores them in a dictionary with class labels. Finally, it sav...
def create_db(class_count): feature_data = dict() mean_normal_image = get_class_mean_image("normal") for i, class_name in enumerate(const.CLASS_SETS[f'Cohen-Kermani {class_count} classes']): directory = path.join(const.IMAGES_DIRECTORY, class_name) print(f'Class: {class_name}') image...
def load_database(class_count): db_file_path = get_db_file_path(class_count) df = pd.read_csv(db_file_path) return df def do_tree(df): results = list() total_time = 0 print('DECISION TREE') for i in range(const.NUMBER_OF_EXPERIMENTS): print(f'Experiment No.: {i}') X_train, X_...
The code performs hyperparameter tuning for machine learning classifiers (tree, random forest, SVM, KNN, Gaussian Naive Bayes) by testing all parameter combinations on a dataset loaded based on `class_count`. It initializes classifier-specific parameter grids, iterates through their Cartesian product, and evaluates eac...
def classify(clf_type, class_count): Result.class_set = const.CLASS_SETS[f'Cohen-Kermani {class_count} classes'] df = load_database(class_count) results = list() if clf_type == 'tree': results.append(do_tree(df)) return results if clf_type == 'random_forest': clf_class = Rand...
def display_welcome(self): print(f'Welcome Player(s) to Rock, Paper, Scissors, Lizard, Spock \n' + '\n' + 'The rules are as follows:\n' + '\n' + ' -Rock crushes Scissors\n' + ' -Scissors cuts Paper\n' + ' -Paper covers Rock\n' + ' -Rock crushes Li...
The main task of the code is to initialize and set up a game by displaying a welcome message, prompting for the number of players, adding blank lines for formatting, and presenting a random fact. The method orchestrates initial game setup steps before proceeding to gameplay logic.
def run_game(self): self.display_welcome() self.number_of_players() print() print() self.random_fact()
def __assign_individual(self, model:keras.models.Sequential, description:str, adaptation_type:AdaptationType, parent:Individual = None) -> Individual: ''' Assigns the provided model to an instance of the Individual object ''' individual = Individual(self.dynamic_parameters.individual_id_...
This function initializes the first individual in a genetic algorithm by assigning a base model, performing pretraining via warm-up epochs, and conducting security checks. It returns a list containing the initialized individual, or None if the input model is invalid.
def __perform_initialization_steps(self, initial_model:keras.models.Sequential) -> list[Individual]: ''' Initializes the first individual, performs pretraining and security checks. Initializes the parent generation ''' starting_individual = self.__assign_individual(initial_model,...
def __produce_offspring_population(self, parent:Individual) -> list[Individual]: ''' Produce all potential offspring for the given parent Reject degenerates and provide recuperative training to remaining children. ''' surgeon = ECToNAS(self.dynamic_parameters) child_popul...
The code generates offspring from a parent generation through mutation, applies recuperative training to the children, removes degenerate offspring, and returns the refined child generation.
def __run_mutation_phase(self, parent_generation:list[Individual]) -> list[Individual]: ''' Produces offspring from parent generation. Children receive recuperative training. Degenerate children are discarded. ''' child_generation = [] for parent in parent_generation: ...
def __perform_initialization_steps(self, initial_model:keras.models.Sequential) -> list[Individual]: ''' Initializes the first individual, performs pretraining and security checks. Initializes the parent generation ''' starting_individual = self.__assign_individual(initial_model,...
The code implements an evolutionary algorithm to optimize a neural network model. It iteratively evolves the model through mutation, competition (two phases), and evolution steps, selecting the fittest individuals. The process continues until termination criteria are met, ultimately returning the optimized model and it...
def __run(self, initial_model:keras.models.Sequential) -> tuple[keras.models.Sequential, Individual]: ''' Main algorithm ''' parent_generation = self.__perform_initialization_steps(initial_model) if parent_generation is None: self.__print('Initialization could not be ...
def to2d(x): '''Remove 3d coordinate info from a rdkit mol for display purposes.''' return Chem.MolFromSmiles(Chem.MolToSmiles(x, isomericSmiles=False)) def prep_output(output): ''' Filtering the output from smina. ''' output = output.decode('utf-8').split('\n') output = [x for x in output if ...
The main task of the code is to iteratively reconstruct a ligand by replacing its fragments with predicted alternatives, using a deep learning model to generate candidate fragments. It evaluates each new ligand variant with smina scoring, retaining the best-performing structure until all fragments are tested, ultimatel...
def interactive_ligand_reconstruction(pdb_id, lig_id, spec_model, save_path): ''' Ligand reconstruction by adding the top predicted fragment to the parent and comparing wether it scores higher than the original ligand on application of smina. If it does the predicted fragment is kept, otherwise t...
def iterative_ligand_reconstruction(pdb_id, resname, spec_model): ''' Ligand reconstruction by applying the predicted top fragment to the parent. This process is repeated until the predicted top fragments do not differ from the 'original' fragment. ''' model = LeadoptModel.load(spec_model, de...
The function `draw_iterative` reconstructs a ligand using a specified model, saves it as an SDF file, calculates its docking score with `smina.static`, generates a 2D molecular structure image, and returns the computed score. It processes input PDB and ligand IDs, handles file I/O, and integrates molecular visualizatio...
def draw_iterative(pdb_id, lig_id, spec_model, save_path): ''' Using the reconstruction function to save the new ligand as sdf file and a drawing of its structure. ''' x = iterative_ligand_reconstruction(pdb_id, lig_id, spec_model) out = tosdf(x) print(out, file=open(path % pdb_id + lig_id...
def interactive_ligand_reconstruction(pdb_id, lig_id, spec_model, save_path): ''' Ligand reconstruction by adding the top predicted fragment to the parent and comparing wether it scores higher than the original ligand on application of smina. If it does the predicted fragment is kept, otherwise t...
The function `draw_interactive` reconstructs a ligand structure from given PDB and ligand IDs using a specified model, saves the reconstructed ligand as an SDF file, computes its binding score with smina, generates a 2D molecular structure image, and returns the computed score. It combines ligand reconstruction, scorin...
def draw_interactive(pdb_id, lig_id, spec_model, save_path): ''' Using the reconstruction function to save the new ligand as sdf file and a drawing of its structure. ''' x = interactive_ligand_reconstruction(pdb_id, lig_id, spec_model, save_path) out = tosdf(x) print(out, file=open(path % ...
def prep_liglist(pdb_id, lig_id, spec_model, k): '''Helper function, prepares a list containing data about the ligand and its top predicted fragments. This function is used to calculate the correlation of the smina scores of the top predicted fragments.''' model = LeadoptModel.load(spec_model, devi...
This function aims to reconstruct a ligand by selecting top-scoring fragments from a set of top-k candidates. It evaluates fragment compatibility with a protein using a scoring model, identifies optimal fragment combinations, and attempts to assemble them into a complete ligand via molecular common substructure (MCS) m...
def topk_ligand_reconstruction(prot, lig, spec_model, k): ''' Not yet functional. This method was meant to choose the top scoring fragment out of a given range of top-k fragments and build a new ligand with these. ''' lig_list = [] data_list = [] for kk in range(int(k)): ...
def topk_ligand_reconstruction(prot, lig, spec_model, k): ''' Not yet functional. This method was meant to choose the top scoring fragment out of a given range of top-k fragments and build a new ligand with these. ''' lig_list = [] data_list = [] for kk in range(int(k)): ...
The function `draw_topk` reconstructs top-k ligand candidates from a protein-ligand complex using a specified model, saves the reconstructed ligand as an SDF file, computes its binding score with `smina`, generates a 2D structure image, and returns the score. It processes the ligand reconstruction, writes outputs to di...
def draw_topk(pdb_id, lig_id, spec_model, save_path): ''' Using the reconstruction function to save the new ligand as sdf file and a drawing of its structure. ''' x = topk_ligand_reconstruction(pdb_id, lig_id, spec_model, k=5) out = tosdf(x) print(out, file=open(path % pdb_id + lig_id ...
def initialize(self): self.test_perf = [] self.observations = [] self.runtime = 0 self.conflicts = [] self.log_conflict = False def check(self): nb_none = 0 if self.processes is None: nb_none += 1 if self.is_stochastic is None: nb_n...
This code trains a matrix factorization model for collaborative filtering by initializing user and movie latent factors, iterating through training steps, periodically evaluating performance, logging conflicts, and calculating cumulative conflicts and runtime while excluding evaluation time.
def train(self): self.initialize() self.check() eval_time = 0 start = time.time() self.U, self.V = initialize_uv(u_rows=self.nb_users, u_cols=self.k, v_cols=self.nb_movies, with_lock=self.with_lock) for it in tqdm(range(1, self.max...
def shiftLeft(L): # Gets empty list first emptyList = createEmpty2DList() rows, cols = len(emptyList), len(emptyList[0]) # Copies over necessary values for i in range(rows): for j in range(cols - 1): emptyList[i][j] = L[i][j + 1] result = emptyList return result def ge...
This code generates a new rightmost column for a game world by shifting the existing level left, extracting the previous rightmost column, creating new blocks based on it, replacing the last column of the shifted level with these new blocks, updating the game map, and reloading the world with the modified layout.
def generateRightCol(app): L = app.mapAs2DList # Shifts old level to the left newLevel = shiftLeft(L) cols = len(newLevel[0]) # Gets previous column (which is the furthest right col in level) prevCol = getColAsList(newLevel, cols - 2) # Gets new, random column newBlocks = getBlocks(prevC...
def shiftRight(L): # Gets empty list first emptyList = createEmpty2DList() rows, cols = len(emptyList), len(emptyList[0]) # Copies over necessary values for i in range(rows): for j in range(cols): if (j == 0): continue emptyList[i][j] = L[i][j - 1] result = empt...
This code generates a new left column for a 2D grid by shifting the existing level right, creating a new column from the previous leftmost column, updating the grid with the new column, and reloading the world with the modified layout.
def generateLeftCol(app): L = app.mapAs2DList # Shifts old level to the right newLevel = shiftRight(L) # Gets previous column (which is the furthest left col in level) prevCol = getColAsList(newLevel, 1) # Gets new, random column newBlocks = getBlocks(prevCol) # Adds this new column into...
def edges_get(self): edges = [ self.cube[self.white][self.edge_u], #0 self.cube[self.white][self.edge_r], #1 self.cube[self.white][self.edge_d], #2 self.cube[self.white][self.edge_l], #3 self.cube[self.green][self.edge_l], #4 self.cube[sel...
The code processes edges and reversed edges to identify positions with 'w' and cross them based on matching colors in the 'downs' list. It iterates through edge indices, checks for 'w' in edges or reversed edges, and triggers a cross action if the corresponding reversed or edge color is in 'downs'. Matches are then rem...
def cross(self): downs = ['g','o','b','r'] for i in range(1, 5): edges = self.edges_get() edges_reversed = self.edges_get_reversed() for i1 in range(0,12): if edges[i1]=='w': if edges_reversed[i1] in downs: s...
def get_data_path(name): return os.path.join(os.getcwd(), 'data', name) def check_hash(name, data): expected_md5 = FILE_HASHES[name] md5 = hashlib.md5(data).hexdigest() if md5 == expected_md5: return True print('Invalid MD5 for {}, expected {}, found {}.'.format( name, expected_md5...
The main task of the code is to check if files corresponding to known hashes exist and match, download missing/mismatched files using credentials if needed, and validate downloaded files against their hashes before saving them locally.
def download_dependencies(email=None, password=None): names = list(FILE_HASHES.keys()) download_names = [] for name in names: path = get_data_path(name) try: with open(path, 'rb') as fp: data = fp.read() if check_hash(name, data): cont...
def PressKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode)) user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x)) time.sleep(0.003) def ReleaseKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode, ...
The code executes a sequence of key presses and delays to perform a left dash action after initiating a downward menu press, simulating a movement or game control task with timed inputs and randomization.
def jumpLeftDown(): PressKey(VK_DOWN) PressKey(VK_MENU) time.sleep(0.1) ReleaseKey(VK_MENU) ReleaseKey(VK_DOWN) time.sleep(0.3) dash(VK_LEFT) randomDelay(0.75, 0.85)
def ClickKey(hexKeyCode): PressKey(hexKeyCode) ReleaseKey(hexKeyCode) def PressKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode)) user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x)) time.sleep(0.003) def ReleaseKey(hexKeyCode): x = INPUT(type=INPUT_KE...
The code simulates a sequence of keyboard inputs and delays to perform a "brandish" action, likely for gaming or automation. It presses/left, up, control keys, releases them with timed pauses, executes a downward dash, triggers a control click, waits randomly, then logs the current time as the 'brandish' timestamp for ...
def brandish(): ClickKey(VK_LEFT) PressKey(VK_LEFT) time.sleep(0.18) PressKey(VK_UP) PressKey(VK_CONTROL) ReleaseKey(VK_LEFT) ReleaseKey(VK_CONTROL) ReleaseKey(VK_UP) randomDelay(0.2, 0.3) dash(VK_DOWN) randomDelay(0.2, 0.3) ClickKey(VK_CONTROL) randomDelay(0.75, 0.85...
def PressKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode)) user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x)) time.sleep(0.003) def ReleaseKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode, ...
The code simulates a sequence of key presses (UP, DOWN, MENU, LEFT) followed by releases, then invokes 'finalBlow()', 'beyond(1)', and a random delay. Its main task is to execute a timed key combination for a game/action script, likely to trigger a specific in-game maneuver or action sequence, followed by additional fu...
def jumpDown(): PressKey(VK_UP) PressKey(VK_DOWN) PressKey(VK_MENU) PressKey(VK_LEFT) time.sleep(0.1) ReleaseKey(VK_LEFT) ReleaseKey(VK_UP) ReleaseKey(VK_MENU) ReleaseKey(VK_DOWN) time.sleep(0.1) finalBlow() beyond(1) randomDelay(0.8, 0.85)
def ClickKey(hexKeyCode): PressKey(hexKeyCode) ReleaseKey(hexKeyCode) def PressKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode)) user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x)) time.sleep(0.003) def ReleaseKey(hexKeyCode): x = INPUT(type=INPUT_KE...
The code defines a function `goLeft()` that simulates key presses and releases for game automation, including left, up, and control keys, followed by delays and additional actions like `finalBlow()` and `beyond(1)`, likely to execute a sequence of in-game movements and attacks with randomized timing to avoid detection.
def goLeft(): ClickKey(VK_LEFT) PressKey(VK_LEFT) time.sleep(0.18) PressKey(VK_UP) PressKey(VK_CONTROL) ReleaseKey(VK_LEFT) ReleaseKey(VK_CONTROL) ReleaseKey(VK_UP) randomDelay(0.23, 0.25) finalBlow() beyond(1) randomDelay(0.73, 0.74)
def PressKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ki=KEYBDINPUT(wVk=hexKeyCode)) user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x)) time.sleep(0.003) def randomDelay(min, max): time.sleep(random.uniform(min, max)) def ReleaseKey(hexKeyCode): x = INPUT(type=INPUT_KEYBOARD, ...
The code defines a function `goRight()` that simulates a sequence of key presses and delays, likely for game automation. It presses the right arrow key, releases it, then repeatedly presses the 'S' key with random delays, interspersed with calls to `jumpRightUp()`. The task involves controlled movement and timed action...
def goRight(): PressKey(VK_RIGHT) randomDelay(0.1, 0.2) ReleaseKey(VK_RIGHT) ClickKey(VK_S) randomDelay(0.7, 0.8) ClickKey(VK_S) randomDelay(0.8, 0.9) jumpRightUp() for i in range(3): ClickKey(VK_S) randomDelay(0.7, 0.8) jumpRightUp() for i in range(3): ...
def jumpLeftDown(): PressKey(VK_DOWN) PressKey(VK_MENU) time.sleep(0.1) ReleaseKey(VK_MENU) ReleaseKey(VK_DOWN) time.sleep(0.3) dash(VK_LEFT) randomDelay(0.75, 0.85) def ClickKey(hexKeyCode): PressKey(hexKeyCode) ReleaseKey(hexKeyCode) def randomDelay(min, max): time.sleep(ra...
The function `maha()` executes a sequence of actions: moves left/down, presses the 'E' key, waits randomly, dashes upward, presses the 'Control' key, waits again, and records the current timestamp under the key 'maha'. The main task is to perform a timed in-game maneuver involving movement, key presses, and timestamp l...
def maha(): jumpLeftDown() ClickKey(VK_E) randomDelay(0.2, 0.3) dash(VK_UP) randomDelay(0.1, 0.2) ClickKey(VK_CONTROL) randomDelay(0.2, 0.3) TimeStamp['maha'] = time.time()
def jumpLeftDown(): PressKey(VK_DOWN) PressKey(VK_MENU) time.sleep(0.1) ReleaseKey(VK_MENU) ReleaseKey(VK_DOWN) time.sleep(0.3) dash(VK_LEFT) randomDelay(0.75, 0.85) def ClickKey(hexKeyCode): PressKey(hexKeyCode) ReleaseKey(hexKeyCode) def randomDelay(min, max): time.sleep(ra...
The code's main task is to execute a sequence of actions: perform a "jumpLeftDown" movement, simulate pressing the 'X' key, introduce a random delay between 0.2-0.3 seconds, and record the current timestamp in a dictionary under the 'spider' key for tracking purposes.
def spider(): jumpLeftDown() ClickKey(VK_X) randomDelay(0.2, 0.3) TimeStamp['spider'] = time.time()
def jumpDown(): PressKey(VK_UP) PressKey(VK_DOWN) PressKey(VK_MENU) PressKey(VK_LEFT) time.sleep(0.1) ReleaseKey(VK_LEFT) ReleaseKey(VK_UP) ReleaseKey(VK_MENU) ReleaseKey(VK_DOWN) time.sleep(0.1) finalBlow() beyond(1) randomDelay(0.8, 0.85) def goLeft(): ClickKey(...
The main task of the code is to execute a sequence of movements: first jumping down, then moving left four times in a loop, followed by introducing a random delay between 0.4 and 0.5 seconds to introduce variability in timing.
def case0(): jumpDown() for i in range(4): goLeft() randomDelay(0.4, 0.5)
def jumpDown(): PressKey(VK_UP) PressKey(VK_DOWN) PressKey(VK_MENU) PressKey(VK_LEFT) time.sleep(0.1) ReleaseKey(VK_LEFT) ReleaseKey(VK_UP) ReleaseKey(VK_MENU) ReleaseKey(VK_DOWN) time.sleep(0.1) finalBlow() beyond(1) randomDelay(0.8, 0.85) def goLeft(): ClickKey(...
The code defines a function `case1()` that executes a sequence of actions: jumping down, moving left three times, brandishing an item, and introducing a random delay between 0.3 and 0.5 seconds. The primary task is to perform these predefined movements and actions in a specific order, likely simulating a character's be...
def case1(): jumpDown() goLeft() goLeft() brandish() goLeft() randomDelay(0.3, 0.5)
def jumpDown(): PressKey(VK_UP) PressKey(VK_DOWN) PressKey(VK_MENU) PressKey(VK_LEFT) time.sleep(0.1) ReleaseKey(VK_LEFT) ReleaseKey(VK_UP) ReleaseKey(VK_MENU) ReleaseKey(VK_DOWN) time.sleep(0.1) finalBlow() beyond(1) randomDelay(0.8, 0.85) def goLeft(): ClickKey(...
The code defines a function `getMeso()` that performs a sequence of directional movements: it starts by jumping down, moves left three times, jumps left and up, then moves right. The primary task is to navigate through a grid or environment using predefined movement commands to reach a target location or complete a spe...
def getMeso(): jumpDown() for i in range(3): goLeft() jumpLeftUp() goRight()
def maha(): jumpLeftDown() ClickKey(VK_E) randomDelay(0.2, 0.3) dash(VK_UP) randomDelay(0.1, 0.2) ClickKey(VK_CONTROL) randomDelay(0.2, 0.3) TimeStamp['maha'] = time.time() def goLeft(): ClickKey(VK_LEFT) PressKey(VK_LEFT) time.sleep(0.18) PressKey(VK_UP) PressKey(VK_...
The function `case2()` executes a sequence of actions: it first calls the `maha()` function, then repeatedly calls `goLeft()` four times in a loop, and finally introduces a random delay between 0.3 and 0.5 seconds. The primary task is to perform a directional movement routine followed by a variable pause.
def case2(): maha() for i in range(4): goLeft() randomDelay(0.3, 0.5)
def spider(): jumpLeftDown() ClickKey(VK_X) randomDelay(0.2, 0.3) TimeStamp['spider'] = time.time() def goLeft(): ClickKey(VK_LEFT) PressKey(VK_LEFT) time.sleep(0.18) PressKey(VK_UP) PressKey(VK_CONTROL) ReleaseKey(VK_LEFT) ReleaseKey(VK_CONTROL) ReleaseKey(VK_UP) ran...
The main task of the code is to execute the `spider()` function, move left four times using `goLeft()`, and then introduce a random delay between 0.3 to 0.5 seconds. This sequence likely simulates a specific action or movement pattern in a robotic or game context.
def case3(): spider() for i in range(4): goLeft() randomDelay(0.3, 0.5)
def ClickKey(hexKeyCode): PressKey(hexKeyCode) ReleaseKey(hexKeyCode) def randomDelay(min, max): time.sleep(random.uniform(min, max)) def case0(): jumpDown() for i in range(4): goLeft() randomDelay(0.4, 0.5)
The main task of the code is to simulate pressing the "5" key, introduce a random delay between 0.5–0.6 seconds, and then invoke the `case0()` function. This appears to be part of an automated script, likely for GUI or game interaction, where key presses and timing are critical. The use of `randomDelay` suggests attemp...
def case4(): ClickKey(VK_5) randomDelay(0.5, 0.6) case0()
def ClickKey(hexKeyCode): PressKey(hexKeyCode) ReleaseKey(hexKeyCode) def randomDelay(min, max): time.sleep(random.uniform(min, max)) def case4(): ClickKey(VK_5) randomDelay(0.5, 0.6) case0() def getMeso(): jumpDown() for i in range(3): goLeft() jumpLeftUp() goRight()...
The code automates timed actions in a loop, checking cooldown periods for various tasks (e.g., 'sim', 'meso', 'spider', 'maha', 'brandish'). When cooldowns expire, it triggers corresponding functions (case0-case4), executes key clicks, and updates timestamps. The loop runs indefinitely, managing task execution based on...
def run(running_time=0): startTime = time.time() mahaOn = False while True: now = time.time() if now - TimeStamp['sim'] > coolTime['sim']: ClickKey(VK_3) randomDelay(0.6, 0.7) if mahaOn: case4() mahaOn = False elif now - TimeSta...
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(eve...
The code runs a game loop that continuously checks for events, updates game elements (helo, tank, bullets, rounds) when the game is active, handles collisions, and renders the screen to maintain gameplay and visuals.
def run_game(self): while True: self.check_events() if self.stats.game_active: self.Clock() self.helo.update() self.tank.update() self._update_bullets() self._update_rounds() self._check_helo_...
def _progression_edge(self, person_a, person_b): '''Make disease progress as far as given social graph edge is concerned. Only event is transmission, which requires one contagious individual and one uninfected individual.''' outcome = False if person_a.is_contagious() and (not person_b....
This function advances a disease simulation by one day. It increments the day counter, synchronizes the world, facilitates disease transmission between interacting individuals, updates each person's disease state, removes deceased individuals from the social graph (if configured), and enacts quarantine policies to mode...
def progress_one_more_day(self, world): '''Make disease progress one more day in the world''' self.day_counter += 1 world.synchronize(self.day_counter) # Transmit disease between people for pp_interaction in world.social_graph.edges: person_a = pp_interaction[0] ...
def init_buttons(self): '''# print debug print_debug_btn = QPushButton("Print debug data", self) print_debug_btn.move(0,150) print_debug_btn.clicked.connect(self.debugger_function) # spawn enemy spawn_enemy_btn = QPushButton("Spawn Enemy",self) spawn_enem...
This code initializes a tower defense game by setting up the game window, loading configuration values from an external file, creating initial game elements like towers, enemies, and the castle, and starting the game loop. It configures player resources, enemy behavior, tower attributes, and initializes the game scene ...
def __init__(self): super().__init__() self.title = "Linnapuolustus Buttons" self.left = 200 # buttonwindow x-location in screen self.top = 758 # buttonwindow y-location in screen self.width = 820 # buttonwindow width self.height = 200 # buttonwindow height ...
def clean_lists(self): # delete useless instances from game world and memory deletables_towers = [] deletables_enemies = [] if (self.step_count % 5 == 0): self.lasers_list = [] self.splash_list = [] for i in range(0, len(self.towers_class...
This function manages periodic game updates every 100ms. It cleans data, updates game state, and if the game is active (play=1), moves enemies, damages the castle, attacks enemies, and spawns new enemies at randomized intervals. The step_count increments to track elapsed steps for timing logic.
def step_timer(self): # step: happens every 100ms self.clean_lists() self.update_all() if (self.play == 1): self.move_enemies() self.damage_castle() self.attack_enemies() if (self.step_count % (5 + randint(-2,2)) == 0): ...
def make_hash2_f1(name,number,game): name = name.upper().replace(' ','') ln = len(name) r31 = int_to_bits(number) r3 = BitArray(32) r3 = addi(r3,-100) r0 = char_to_bits(name[12%ln]) r25 = char_to_bits(game[0]) # E r3 = r3 ^ r0 r0 = char_to_bits(name[15%ln]) r3 = addi(r3,-61) r4 = rotate_mask_and...
The code generates a 64-bit hash value by combining input parameters (name, number, game) through two functions (f1 and f2), then finalizes the hash by clearing unused bits, adding a timestamp, and validating it. The result is a structured, time-stamped hash representation.
def get_hash2(name,number,game): hash2 = BitArray(64) f1 = make_hash2_f1(name,number,game) f2 = make_hash2_f2(name,number,game) hash2 = set_hash2_f1(hash2,f1) hash2 = set_hash2_f2(hash2,f2) hash2 = clear_hash2_unused(hash2) hash2 = set_hash2_time(hash2,get_current_timestamp()) hash2 = make_hash2_valid...
def load_model(model): """ Load model """ emiss = defaultdict(dict) trans = defaultdict(dict) context = defaultdict(dict) for line in model: if line.startswith("C"): type_, tag, count = line.split() context[tag] = int(count) continue typ...
The main task of the code is to decode sequences using a model and vocabulary by constructing transition (A) and emission (B) matrices from loaded model parameters, then applying a tagging function that leverages these matrices to infer sequences.
def decode_seq(model, vocab): """ Decode sequences """ emiss, trans, context = load_model(model) tags = sorted(context.keys()) # Transition matrix A = construct_A(trans, context, tags) # Emission matrix B = construct_B(emiss, context, tags, vocab) tag(tags, vocab, A, B)
def generate_vocab(min_cnt=2, train_fp=settings.TRAIN): """ Generate vocabulary """ vocab = defaultdict(int) with open(train_fp, "r") as train: for line in train: # Ignore empty lines if not line.split(): continue tok, tag = line.split("...
The main task of the code is to process either the "dev" or "test" data split by generating/loading a vocabulary and model, then decoding the specified split. It validates the split input, checks for required files, trains or loads the model, and executes decoding. The code ensures proper error handling for invalid spl...
def main(): """ main() """ global split split = "dev" if split not in ["dev", "test"]: print('Error: split options are "dev" or "test"') sys.exit(1) if not os.path.isfile(settings.VOCAB): print("Generating vocabulary...") vocab = generate_vocab() else: ...
def get_motion_data(motion_api_url): response = requests.get(motion_api_url) return json.loads(response.text) def capture_picture(picam2, picture_name, log_string): picam2.capture_file(picture_name) timestamp = datetime.datetime.now().strftime("%Y-%m-%d|%H:%M:%S") with open("logs.txt", "a") as file:...
This function handles traffic light scenarios by detecting motion collisions. If a collision occurs or the light is red with motion detected, it captures evidence and reports law violations. Otherwise, it signs motion data without an image, ensuring compliance with traffic regulations.
def handle_light(picam2, client, private_key, light): response_data = get_motion_data(f"http://localhost:5080/MotionCollision?token={client.token.decode('utf-8')}") if response_data['detection']['type'] == 'collision' and response_data['detection']['value']: capture_picture(picam2, "traffic_photo.jpg", ...
def __rectify_normals(view_rays, normals): ''' view_rays [no_points, 3] normals [no_points, 3] force view_rays and normals to have negative product, if not flip normals change normals in place ''' return pass flip_mask = (view_rays*normals).sum(-1)...
This function optimizes red depth and normal estimates by minimizing a photometric loss combined with shape and depth constraints. It gathers black depth/normal data via nearest neighbors, computes 3D positions using rays and optical centers, applies normal transformations, and selects optimal red depths/normals by min...
def __pm_red_pass(red_depths, red_normals, red_rays, red_urays, red_nnf, black_depths, black_normals, optical_centre, red_hat_depth, red_hat_xyz, red_hat_xyz_n): ''' GPU only red_depths [no_reds], xyzs+normals red_normals [no_reds, 3], xyzs+normals red_rays [no_reds, 3], vectors ...
def __rectify_normals(view_rays, normals): ''' view_rays [no_points, 3] normals [no_points, 3] force view_rays and normals to have negative product, if not flip normals change normals in place ''' return pass flip_mask = (view_rays*normals).sum(-1)...
The code generates randomized depth and normal candidates by perturbing input values, computes photometric and shape losses for each candidate, selects the optimal candidate with minimal loss, and returns the optimized depths, normals, validity mask, loss mean, and view selection mask for depth-normal estimation in a n...
def __pm_randomise(depths, normals, rays, urays, theta_d_dev, len_dev, no_candidates, optical_centre, _d, _n, hat_depth, hat_xyz, hat_xyz_n): # generate random shifts no_points = depths.shape[0] no_points_idx = immutable_tensor(range(no_points)).cuda() angular_shift = sample_unit_vector...
def draw(win, grid, rows, width): win.fill(white) for row in grid: for spot in row: spot.draw(win) draw_grid(win, rows, width) pygame.display.update() def h(p1, p2): x1, y1 = p1 x2, y2 = p2 return abs (x1 - x2) + abs(y1 - y2) def rec_path(came_from, end, draw): while...
This code implements the A* pathfinding algorithm 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, calculates tentative scores (g_score, f_score), and updates the path (came_from) when a better route is found. The algorithm visualizes the path b...
def algorithm(draw, grid, start, end): draw() count = 0 open_set = PriorityQueue() open_set.put((0, count, start)) came_from = {} g_score = {spot: float("inf") for row in grid for spot in row} g_score[start] = 0 f_score = {spot: float("inf") for row in grid for spot in row} f_score[start] = h(start.ge...
def make_grid(rows, width): grid = [] gap = width // rows #MAKE GRID 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) fo...
This code creates a pathfinding visualization using Pygame. It initializes a grid, allows users to set start/end points and barriers via mouse clicks, and runs a pathfinding algorithm (e.g., A*) when the spacebar is pressed. The algorithm uses the grid's neighbor relationships to compute paths, updating the display dyn...
def main(win, width): ROWS = 50 grid = make_grid(ROWS, width) start = None end = None run = True started = False while run: draw(win, grid, ROWS, width) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if started: continue ...
def enough_credits(courses, cursor): credit_sum = 0 for c in courses: if c != "": num_credits = cursor.execute("SELECT credits FROM courses WHERE course_id=?", c.split(" ")[0]).fetchone() if num_credits: num_credits = num_credits[0] else: ...
The main task of the code is to validate a course schedule by checking academic requirements. It processes input courses (flattening nested lists if needed), filters out empty entries, and evaluates criteria like credit sufficiency, lower-level math/CS courses, upper-level concentration, general track, and gen-ed fulfi...
def valid_schedule(c, cursor): if(isinstance(c[0], list)): # Flatten courses = [item for sublist in c for item in sublist] else: # Don't flatten courses = c courses = list(filter(lambda a: a != '', courses)) print (courses) ret_val = { "enough_credits": ...
def check_filter_params( ftype=None, cutoff_hz=None, sfreq=None, width_hz=None, ripple_db=None, window=None, allow_defaults=False, ): r"""type check FIR filter parameters and optionally provide defaults Values for `ftype`, `cutoff_hz`, and `sfreq` are obligatory. If `allow_defa...
The function `filters_effect` generates visualizations demonstrating how different filters (lowpass, highpass, bandpass, bandstop) affect pure sine wave signals. It creates input-output plots by designing filters with specified parameters (cutoff frequency, transition width, ripple, window type), applying them to test ...
def filters_effect( ftype=None, cutoff_hz=None, sfreq=None, width_hz=None, ripple_db=None, window=None, ): """ Generate example filter input-output plots for pure sinewave data. Parameters ---------- key=val see :ref:`check_filter params() Parameters <filter_parameters_label>` R...
def check_filter_params( ftype=None, cutoff_hz=None, sfreq=None, width_hz=None, ripple_db=None, window=None, allow_defaults=False, ): r"""type check FIR filter parameters and optionally provide defaults Values for `ftype`, `cutoff_hz`, and `sfreq` are obligatory. If `allow_defa...
The function `show_filter` generates text summaries and visualizations of digital filter characteristics, including transfer functions, coefficients, and input-output performance. It calculates edge distortion metrics, plots frequency/phase responses, impulse/step responses, and highlights distorted regions in input-ou...
def show_filter( ftype=None, cutoff_hz=None, sfreq=None, width_hz=None, ripple_db=None, window=None, show_output=True, ): """Text summary and graphic display of filter attributes for the specified parameters. Figures are plotted for the transfer function, coefficients, and inpu...
def _prepare_prompt( self, seq_group_metadata_list: List[SequenceGroupMetadata], ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata]: assert len(seq_group_metadata_list) > 0 input_tokens: List[List[int]] = [] input_positions: List[List[int]] = [] slot_mapping: List[...
The code executes a machine learning model for sequence generation, handling both prompt and decode phases. It prepares input tensors based on sequence metadata, runs the model with KV caches for efficiency, and samples the next token using hidden states and sampling metadata, returning the generated output.
def execute_model( self, seq_group_metadata_list: List[SequenceGroupMetadata], kv_caches: List[Tuple[torch.Tensor, torch.Tensor]], cache_events: Optional[List[torch.cuda.Event]] = None, ) -> SamplerOutput: # NOTE: We assume that all sequences in the group are all prompts or ...
def load_data(filename): return pd.read_csv(filename) def filterDisasterData(disasterData): disasterData['Location'] = disasterData['Location'].str.upper() disasterData['Location'] = disasterData['Location'].fillna('') disasterData = disasterData.assign(State = lambda x: get_states(x['Location'])) disasterData...
The main task of the code is to load, process, and merge multiple food production datasets (crops, dairy, poultry, livestock) with disaster data, save the processed datasets individually and as a combined dataset, and calculate the percentage of entries affected by disasters.
def combineDatasets(): print ("Loading data from file..") disasterData = load_data("datasets/disaster_data/disasterData.csv") disasterData = filterDisasterData(disasterData) print ("Processing crop production..") cropsData = process_production_data("datasets/food_data/crops_production.csv", "Crop", disasterData...
def _population(self, in_parametersets): # Selects populations of N parameters sets each. Fitness is calculated based on these populations, the pop with highest fitness is chosen for mutation. self.population.clear() # So that values from previous iterations are cleared for ou in range(0, self.maxSet//...
The code implements a genetic algorithm loop for fault detection. It iterates up to maxIterations, evaluating population fitness, performing crossover, and dynamically halving the mutation rate each iteration. It tracks cumulative failure sums in sumFailVec, updates parametersets, and adjusts the mutation rate to refin...
def _loop(self): # Loops the genetic algorithm in order to detect faults within the tested system self.sumFailVec = [] limit = 5 for iterations in range(0, self.maxIterations): self._population(self.newParametersets) self._tester() self._calculate_fitness...
def _initialise(self, filename, i): # Starts by reading the TC data (tables_x.txt), create a population of parameter sets for file in filename: self.i = i self.tables.append(read_data.main(file,i)) i += 1 def _generate_parameter_sets(self, tables, maxSet): # Gener...
This code executes a genetic algorithm to evolve parameter sets by either initializing new populations or loading existing ones, evaluating their fitness through testing, applying selection, crossover, and mutation to generate new populations, logging failed parameter sets, and plotting fitness changes before and after...
def _run(self): if os.path.isfile('./init_popSize_' + str(self.popSize) + '_pops_' + str(self.amountPops) + '.txt') == False: self._initialise(self.filename, self.i) # Converts the parameters from the inputted stripped TC into arrays named self.tables self._generate_parameter_sets(sel...
def _Logger(): return logging.getLogger( __name__ ) def _GlobalYcmExtraConfFileLocation(): return os.path.expanduser( user_options_store.Value( 'global_ycm_extra_conf' ) ) def Load( module_file, force = False ): """Load and return the module contained in a file. Using force = True the module will be loaded ...
This function dynamically invokes a specified method from a global YCM extra configuration module if it exists. It first checks if the configuration file exists, loads the module, verifies the method's presence, logs details, then executes the method. Error handling includes logging when the file isn't found, the modul...
def _CallGlobalExtraConfMethod( function_name ): logger = _Logger() global_ycm_extra_conf = _GlobalYcmExtraConfFileLocation() if not ( global_ycm_extra_conf and os.path.exists( global_ycm_extra_conf ) ): logger.debug( 'No global extra conf, not calling method ' + function_name ) return modul...
def drawSpiral(self): i = 1 self.send("G0 X100 Y100") time.sleep(3) while i < 5 or self.__trigger == True: time.sleep(1) self.send("G2 X100 Y100 I"+str(i * 10)) i += 1 if i == 5: i = i * -1 def send(self, message): ...
The main task of the code is to enable manual control of a device via a serial port by accepting user input commands. It continuously prompts the user for commands, executes corresponding functions (e.g., drawing shapes, sending G-code), and sends the commands through the serial connection while printing responses from...
def manual_command(self): try: if self.__ser.isOpen(): print("{} connected".format(self.__ser.port)) time.sleep(1) while True: message = input("Enter command: ") if(message == "test"): ...
def random_exchange_matrix(): mu = -3.0 sig = 1.0/np.sqrt(2) # generate non-symmetrical matrix following requested distribution J_non_symm = normal(mu, sig, (20, 20)) # use the fact that the sum of two normally distributed random numbers is normally distributed # with mu = mu_1 + mu_2 and sig^2 ...
The code simulates the evolution of a self-avoiding protein using Monte Carlo methods. It generates an initial protein configuration, performs MC steps to update its structure, tracks total energy per site over time, and plots initial/final states and energy profiles. A random exchange matrix governs interactions, and ...
def evolve_protein_plot_energy(length, mc_steps, T, path): grid, coord_vec = randomwalk.self_avoiding_walk_protein(length, length) while coord_vec[-1].x == 0: # discard the protein and re-generate if it doesn't have full length grid, coord_vec = randomwalk.self_avoiding_walk_protein(length, length) ...
def random_exchange_matrix(): mu = -3.0 sig = 1.0/np.sqrt(2) # generate non-symmetrical matrix following requested distribution J_non_symm = normal(mu, sig, (20, 20)) # use the fact that the sum of two normally distributed random numbers is normally distributed # with mu = mu_1 + mu_2 and sig^2 ...
The code simulates the evolution of a self-avoiding protein using Monte Carlo steps with a given exchange matrix J, tracking energy changes over time. It generates initial/final protein configurations, plots energy per site, and saves results to specified paths. The main task is to model protein conformational changes ...
def evolve_protein_plot_energy_given_J(length, mc_steps, T, J, path): grid, coord_vec = randomwalk.self_avoiding_walk_protein(length, length) while coord_vec[-1].x == 0: # discard the protein and re-generate if it doesn't have full length grid, coord_vec = randomwalk.self_avoiding_walk_protein(length, l...
def random_exchange_matrix(): mu = -3.0 sig = 1.0/np.sqrt(2) # generate non-symmetrical matrix following requested distribution J_non_symm = normal(mu, sig, (20, 20)) # use the fact that the sum of two normally distributed random numbers is normally distributed # with mu = mu_1 + mu_2 and sig^2 ...
This function performs a Monte Carlo simulation of a self-avoiding polymer, tracking its conformations and energy over time. It generates an animation visualizing the polymer's structural changes and energy evolution, saving the result as a GIF. Key steps include initializing the polymer, executing MC steps with temper...
def animated_monte_carlo(length, mc_steps, T, frame_interval, fps, path): num_frames = int(mc_steps/frame_interval) grid, coord_vec = randomwalk.self_avoiding_walk_protein(length, length) while coord_vec[-1].x == 0: # discard the protein and re-generate if it doesn't have full length grid, coord_vec...
def _display_signal_graphs() -> None: """Displays the 9 components that make up a single data point: * (x, y, z) representing the total acceleration signal from the smartphone accelerometer. * (x, y, z) representing the body acceleration signal obtained by subtracting the gravity from the total acce...
The main task of the code is to display multiple visualizations of signal data, including time-domain signals, frequency spectra via FFT, spectrograms showing frequency over time, and scaleograms representing wavelet-based time-frequency analysis. The function orchestrates the sequential rendering of these four distinc...
def main() -> None: _display_signal_graphs() _display_fft_graphs() _display_spectrogram_graphs() _display_scaleogram_graphs()
def lengthCombinations(nodes, noOfSalesman): tempNodes = nodes string = "" for i in tempNodes: string = string + str(i) #add to List temp =[] for k in combinations(string, noOfSalesman): temp.append(k) #tuples to lists temp2 = [] for i in temp: temp2.append(list(i)) #strings to ints for j...
The code generates all permutations of input nodes to calculate path weights for a salesman problem, filters the minimum weight paths, processes their lengths, and identifies the optimal route by comparing against a predefined optimal path length list.
def calc(nodes): for i in list(permutations(nodes)): lengthCombinations(list(i), noOfSalesman) for i in totalWeightAndPathList: if(i[0] == min(totalPathWeightList)): finalList.append(i) pathLengthsList = [] for i in finalList: temp = [] for j in i[1]: temp.append(pathWeight(j)) i.append(temp) ...
def __parse_locus_version_6(self, handle): """ Helper function to parse version 6 locus entry Args: handle (file): File handle at start of locus entry record Returns: None Raises: Exception: Manifest format error """ self.ilmn_i...
This function parses a locus entry from a file handle by reading its version and delegating to version-specific parsing methods (version 6, 7, or 8). If the version is unrecognized, it raises an exception. It serves as a helper to initialize the object with data from the file.
def __parse_file(self, handle): """ Helper function to initialize this object from a file handle Args: handle (file handle): File handle at start of locus entry record Returns: None """ version = read_int(handle) if version == 6: ...
def pause(): paused = True while paused: for event in pygame.event.get(): if event.type == pygame.QUIT: quit_experiment() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: paused = False elif eve...
This function runs an experiment block to evaluate an optimal policy in a predator-prey simulation. It initializes hunter/prey positions, executes episodes using the optimal Q-policy, tracks metrics like wrong steps and reward loss, and optionally visualizes results. It handles both new experiments (generating data) an...
def experiment_block(env, map_sim, hunter, prey, num_episodes, save_data, new_exp, data_folder, name, error, dt=None, fixed_dt=True, visual=True): """ This function runs a single block in the experiment. """ # Loading optimal policy Q_optimal = np.loadtxt...
def getParents(sort, start, tree): try: op, m0, m1 = next((op, m0, m1) for s, _, m0, m1, op in sort if s == start) except StopIteration: return replaceInTree(tree, start, op, m0, m1) getParents(sort, m0, tree) getParents(sort, m1, tree) def isIn(tree, start): if isinstance(tree,...
The code processes a list of monkey operations to solve for the value of the "humn" monkey. It parses input data, builds a dependency tree, and evaluates expressions until reaching "humn". It constructs an expression tree by reversing operations (e.g., changing subtraction to addition) to isolate "humn"’s value, then e...
def solve_b(data): monkeys = {} togo = [] for line in data.splitlines(): sline = line.split() name = sline[0][:-1] try: monkeys[name] = int(sline[1]) except Exception: togo.append((name, sline[2], sline[1], sline[3])) # name, op-lambda, firstVar,...
def create_input_prototxt(input_dir: str, input_files: Sequence[str] = None, out_dir: str = os.path.curdir, out_filename: str = 'input.txt', start_frame: int = 0, stride: int = 16, ...
The function `prepare_C3D_features` extracts C3D features from videos using a pre-trained model and converts them into a format compatible with MIL (Multiple Instance Learning) input requirements. It reads video file lists, generates configuration files for feature extraction, runs the C3D extractor, and splits extract...
def prepare_C3D_features(args): """Extract C3D features from videos and convert these features into desired number of new features to match MIL input data format. Args: args: namespace or dictionary-like object with arguments (see main function for argument description) """ if...
def split_features_from_dir(c3d_out_dir, out_mil, n_seg: int = 32) -> None: """Split all C3D features in c3d_out_dir into n_seg segments.""" logger.info("Converting extracted features to MIL data format.") feat_dirs = [f.path for f in os.scandir(c3d_out_dir) if f.is_dir()] feat_dirs = sorted(feat_dirs) ...
The code extracts C3D features from videos and converts them into a format compatible with MIL input data. It offers two modes: full pipeline (extracting C3D features and segmenting them) or segment-only mode (using pre-extracted C3D features). Key parameters include the number of segments, video directory, input file,...
def main(): """Extract C3D features from videos and convert these features into desired number of new features to match MIL input data format. If you have already extracted C3D features and only want to create features for MIL, run with --segment_only flag and pass --out_c3d. Before running make s...
def down_layer(input_tensor, filters, dropout=0.): connection = convolution_layer(input_tensor=input_tensor, filters=filters, dropout=dropout) output = MaxPooling2D(pool_size=(2, 2), strides=2)(connection) return output, connection def convolution_layer(input_tensor, filters, dropout=0., padding='same'): ...
This code implements a dual-branch neural network model for semantic segmentation. It constructs two parallel paths: Branch1 processes input through downsampling, a bridge, and upsampling layers to produce output_1. Branch2 processes the bridge and merges with Branch1's output to generate output_2. The model uses GPU d...
def ynet(input_tensor, params): dropout = params['dropout'] classes = params['classes'] if params['distribution']: device_1 = device_2 = nullcontext() else: device_1 = tf.device('/GPU:0') device_2 = tf.device('/GPU:1') with variable_scope('Model'): with device_1: ...
def scene_one(self): clip = VideoFileClip('resources/video/sc_1/sc_1.mp4') clip.preview() clip.close() self.scene_done = True return print("done") def start_scene(self, scene): # self.scene will always be set to the scene that is passed here ...
This code manages scene transitions in a game loop. It checks if Scene 1 is complete, advances to Scene 2 if so, then enters an infinite loop updating the current scene, checking for scene changes, rendering updates, and maintaining a fixed frame rate through clock.tick(). The core task is handling sequential scene pro...
def Start(self): current_scene = self.scene if self.scene == 1: self.scene_one() if self.scene_done: self.scene = 2 return self.Start() while 1: self.start_scene(self.scene) if self.scene > current_sc...
def generate_image_mid_journey(self, description): # return "1449174024354196", self.get_image_from_task_id("1449174024354196") url = "https://api.midjourneyapi.io/v2/imagine" headers = { "Authorization": self.MID_JOURNEY_API_KEY, "Content-Type": "application/x-www-form-u...
The function creates folders for logos by generating images via MidJourney, saving them to a database, and organizing them into structured directories. It processes each logo's metadata, handles errors for empty task/images, and uses a progress bar. Folders are named with the logo title and generated image ID, ensuring...
def create_logo_folders(self, logos, parent_folder): os.makedirs(parent_folder, exist_ok=True) logo_counter = 0 with tqdm(total=len(logos), desc="Creating Logo Folders") as pbar: for logo in logos: title = logo["title"] tags = logo["tags"] ...
def authenticate_google_drive(self): gauth = GoogleAuth() gauth.LoadCredentialsFile("googleCreds.txt") if gauth.credentials is None: gauth.LocalWebserverAuth() elif gauth.access_token_expired: gauth.Refresh() else: gauth.Authorize() gau...
The main task of the code is to upload generated logo folders to Google Drive. It authenticates with Google Drive, creates a time-stamped parent folder, organizes logos into subfolders, uploads them, and sends a push notification if uploads succeed. The process confirms creation and download of logo folders, text files...
def upload_logos(self): self.authenticate_google_drive() parent_folder = f'generated_images/logo_folders_{self.current_time}' self.create_logo_folders(self.logos, parent_folder) uploaded_folders_count = self.upload_folder_to_drive(parent_folder) if uploaded_folders_count != 0:...
def read_income_file(fp): '''Read the income file and build a dictionary''' # Skip first 5 lines for i in range(6): fp.readline() # Loop variables reader = csv.reader(fp) master_dict = {} region = "" state = "" income = 0 # Extract region name, state name, and income f...
The main task of the code is to read and process economic data (income, GDP, population) from CSV files into a structured dictionary, enabling users to query region-specific data interactively. It allows users to display statistical information for selected regions and generate visual plots if requested. The program co...
def main(): # Call the open_file() with the appropriate string # fp = open_file() # Read to create dictionary, key is state, value is list of region, income master_dict = read_income_file(open("income.csv", "r")) # fp = open_file("GDP") # Read file to add GDP to dictionary master_dict = re...
def filterName(soup): # It finds the title of the html page result = soup.find("title").string.lstrip().rstrip() return result def span_analysis(soup): # It returns all the searched elements that are inside a span tag animeType = "" animeNumEpisode = "" aired = "" animeNumMembers = -1 ...
The code parses a webpage (given a URL) using BeautifulSoup, extracts anime-related data (title, span elements, users, synopsis, related anime, characters, voices, staff, URL) in a specific order, and returns them as a list for structured output like a TSV file.
def parse(url): # It computes the parsing of the searched elements soup = BeautifulSoup(open(url), features="lxml") # Calling the function that parse the anime title animeTitle = filterName(soup) # Initialize the vector in wich results of the parsing will be placed ret_values = [animeTitle] ...
def delete_dispatcher(request) -> Union[dict, None]: DELETE_RESOURCES = ["meetings", "labels", "participants"] resource = request.route_params.get("resources", None) resource_id = request.route_params.get("id", None) if resource not in DELETE_RESOURCES or not resource_id: return func.HttpRespons...
The main task of the code is to handle HTTP requests by first authenticating and authorizing the user via a token, then verifying permissions, and finally dispatching the request to the appropriate handler based on the HTTP method (DELETE, GET, PATCH, POST), returning JSON responses for errors or delegated processing.
def main(request: func.HttpRequest) -> func.HttpResponse: # Authentication and Authorization. token, token_err = get_token_from_auth_header(request) if token_err: return func.HttpResponse( dumps({"message": token_err.message}), status_code=token_err.status_code, m...
def install_packages(self, list_path: str, extra: Optional[str]): print("Installing packages from {}...".format(list_path)) with open(list_path, 'r') as file: packages = [line.strip() for line in file] if extra is not None: packages += extra.split(',') self.inst...
The main task of the code is to install or reinstall TinyTeX, handling package installations, directory setup, archive extraction, and post-installation tasks like symlink regeneration and package index updates. It checks for existing installations, removes them if needed, downloads and extracts the specified TinyTeX v...
def install(self, args): if args.packages_only: self.install_packages(args.package_list, args.extra_packages) return reinstall = args.reinstall target = self.profile.target ext = self.profile.os.ext() tinytex_dir = self....
def vecinos_disponibles(self, pos): vecinos_validos = [] vecinos = get_neighbors(tuple(pos)) for n in vecinos: if self.esta_libre(n) and self.manzana.pos != n: vecinos_validos.append(tuple(n)) return vecinos_validos def serpiente_virtual(self): serpi...
The main task of the code is to generate a safe movement path for the snake's head by simulating movement with a virtual snake. It randomly selects a neighbor, checks if the virtual snake's tail path is valid, and returns the chosen path if safe; otherwise, it defaults to the actual tail path to avoid collisions.
def movimiento_seguro(self): vecinos = self.vecinos_disponibles(self.cabeza.pos) path = [] if vecinos: path.append(vecinos[randrange(len(vecinos))]) serpiente_v = self.serpiente_virtual() for mover in path: serpiente_v.dirigirse(mover) ...
def serpiente_virtual(self): serpiente_v = Snake(self.surface) for i in range(len(self.cuadros) - len(serpiente_v.cuadros)): serpiente_v.agregar_casilla() for i, sqr in enumerate(serpiente_v.cuadros): sqr.pos = deepcopy(self.cuadros[i].pos) sqr.dir = deepco...
The main task of the code is to generate a path for the snake to move toward the apple using BFS with a virtual snake. It checks conditions like score, apple position, and movement safety, returning the optimal path from the virtual snake's BFS, a long tail path, or a safe movement strategy if applicable.
def crear_camino(self): if self.score == SNAKE_MAX_LENGTH - 1 and self.manzana.pos in get_neighbors(self.cabeza.pos): mejor_camino = [tuple(self.manzana.pos)] return mejor_camino serpiente_v = self.serpiente_virtual() path_1 = serpiente_v.bfs(tuple(ser...
def handle_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() def crear_camino(self): if self.score == SNAKE_MAX_LENGTH - 1 and self.manzana.pos in get_neighbors(self.cabeza.pos): mejor_camino = [tuple(self.manzana....
This code updates the game state by handling events, generating a path, moving the snake, checking collisions, and determining win/loss conditions. It draws the game, increments movement counters, resets on failure (collision or starvation), and checks for victory when all cells are filled.
def update(self): self.handle_events() self.path = self.crear_camino() if self.path: self.dirigirse(self.path[0]) self.draw() self.mover() if self.score == ROWS * ROWS - INITIAL_SNAKE_LENGTH: self.won_game = True print("Gano el ju...
def tail_peak(data): #assumes the data is already smoothed #check if the last 4 values are decreasing for i in range(4): if data[-1] < data[-i-1]: return 0 return 1 def holiday_peak(date, country,weeks): #get the holidays for the country holidays = get_holidays(country) #...
The function forecasts future values using a Gaussian mixture model by adjusting parameters based on peak detection and holidays, extending the forecast for specified steps while incorporating dynamic parameter updates.
def forecast_gaussian( data, params, steps, start_date,end_date, country,model): bias = np.min(data) norm_I = data - bias T = len(norm_I) #print(params) if tail_peak(data) or holiday_peak(end_date, country,steps): next_params = get_next_params(start_date, params, country,model) if n...
def linear_regression(): x,y = get_x_y() #fits the input data to a fifth degree polynomial poly = PolynomialFeatures(degree =5) x = poly.fit_transform(x) #shuffle the x and y data p = np.random.permutation(len(x)) x = x[p] y = y[p] #splits the data into training and tes...
The code evaluates a Gaussian forecasting model's accuracy across multiple countries by calculating MAPE (Mean Absolute Percentage Error) for 1–4-step-ahead forecasts. It iterates over 30 model runs per country, using historical data (start_date to end_date) and validating against extended data (end_date2). Results are...
def main(): path = "./Data/" # start_date = '3/30/20' # end_date = '1/30/21' # end_date2 = '3/30/21' # # start_date = '2020-02-27' # # end_date = '2021-08-05' # country = 'Italy' start_date = '7/30/20' end_date = '4/20/21' end_date2 = '5/20/21' countries = ["Brazil","Colombia...
def linear_regression(): x,y = get_x_y() #fits the input data to a fifth degree polynomial poly = PolynomialFeatures(degree =5) x = poly.fit_transform(x) #shuffle the x and y data p = np.random.permutation(len(x)) x = x[p] y = y[p] #splits the data into training and tes...
The main task of the code is to forecast infection trends in China using Gaussian models with different assumptions (linear regression vs. baseline) and compare the results to actual data. It reads dataset(s) for specified dates, calculates Gaussian parameters, generates forecasts, and visualizes the actual data (green...
def main2(): path = "./Data/" # start_date = '3/30/20' # end_date = '1/30/21' # end_date2 = '3/30/21' # # start_date = '2020-02-27' # # end_date = '2021-08-05' # country = 'Italy' start_date = '7/30/20' end_date = '5/10/21' end_date2 = '6/10/21' country = "China" ...
def set_current_song(self, song: PlaylistItem) -> None: if self.player.current_song is None: # this runs when first song since launching the app is picked by user to be played self.player.init_queue() else: self.player.add_to_history(self.player.current_song) ...
The code runs a GUI application that handles user interactions (events) for a media player. It updates the UI with current song playtime, manages playlist navigation, processes menu commands (e.g., adding songs, showing queue/history), controls playback (play/pause/next/restart), and handles keyboard shortcuts. It cont...
def run(self) -> None: while True: event, values = self.window.read(timeout=WINDOW_TIMEOUT) # type: ignore if event != "__TIMEOUT__": print(f"{event=} {values=}") # There is current song set and is not paused if self.player.current_song and not s...
def _set_up_venv(self) -> int: """ Set up a Python virtual environment :return: Return code :rtype: int """ venv = join(self.srcdir, "venv") self.logger.info(f"Setting up virtual environment: {venv}") self.py = join(venv, PYEXE) create( ...
The main task of the code is to execute a build process by setting up a virtual environment, building the project, and optionally cleaning build directories. It returns 0 on success or 1 if any step fails. Logs are used to track progress and outcomes.
def main(self) -> int: """ Build :return: Return code :rtype: int """ result = self._set_up_venv() if result: return 1 result = self._build() if result: return 1 if not self.args.NO_CLEAN: self.logger.de...
def file2discourse(readlinesList): discourse = [] for i in readlinesList: if i[0] == '"': list = [] elif i[0] == "(": list.append(i) else: discourse.append(list) discourse.append(list) return discourse def storeDictBack(readlinesList): data...
The code resolves coreferences in a text by identifying noun entities and linking them to their antecedents using syntactic and semantic filters. It processes input lines into structured data, filters potential references, and constructs a result list of coreference pairs. If no valid antecedent is found, it triggers a...
def referenceResolution(inputFile): resultList = [] # # open files, store each line as an element with open(inputFile) as f: lines = f.readlines() # print(lines) # discourseList[][]: [] -> one sentence [] -> one entities(word) in this sentence discourseList = file2discourse(lines) # ...
def random_sequence(distance_matrix: np.ndarray, start_node: int = 0) -> List[int]: n = distance_matrix.shape[0] num_selected = n // 2 if n % 2 == 0 else (n // 2) + 1 path = random.sample(list(range(distance_matrix.shape[0])), num_selected) return np.array(path) def evaluate(distance_matrix: np.ndarray,...
The main task of the code is to evaluate a solution for an optimization problem (e.g., TSP) by comparing the initial path's score with an improved path obtained via local search. It generates a random initial path if none is provided, computes scores using a distance matrix and costs, performs local search with candida...
def evaluate_solution(filename, initial, costs, distance_matrix, no_candidates=10): if initial is None: initial = random_sequence(distance_matrix) start = time.time() initial_score = evaluate(distance_matrix, initial, costs) path = local_search_candidates(initial, costs, distance_matrix, no_cand...
def embed(data): qml.AmplitudeEmbedding(features=data, wires=range(2 * N_a + N_dim + 1, 2 * (N_a + N_dim) + 1), normalize=True) def deep_layer(start, end, repeat, w): # print('deep_layer: ', w) hadamard_column(start, end) for i in range(repeat): layer(start, end, w[NUM_LAYER_WEIGHTS * i:NUM_LAYE...
Your return The code trains a quantum generative adversarial network (GAN) by embedding noise into a quantum state, constructing deep layers for the discriminator and generator using provided weights, performing a swap test to evaluate generated data, and returning the expectation value of Pauli-Z on qubit 0, indicat...
def train_on_fake(disc_weights, gen_weights, noise): embed(noise) deep_layer(1, N_a + N_dim, DEPTH, disc_weights) deep_layer(N_a + N_dim + 1, 2 * (N_a + N_dim), DEPTH, gen_weights) swap_test() return qml.expval(qml.PauliZ(0))
def embed(data): qml.AmplitudeEmbedding(features=data, wires=range(2 * N_a + N_dim + 1, 2 * (N_a + N_dim) + 1), normalize=True) def deep_layer(start, end, repeat, w): # print('deep_layer: ', w) hadamard_column(start, end) for i in range(repeat): layer(start, end, w[NUM_LAYER_WEIGHTS * i:NUM_LAYE...
The code trains a quantum model using embedded data and a deep quantum layer. It applies a swap test to evaluate quantum state similarity, then returns the expectation value of Pauli-Z on the first qubit as the model's output. The function integrates quantum embedding, neural network construction, and measurement to pe...
def train_on_real(disc_weights, data): embed(data) deep_layer(1, N_a + N_dim, DEPTH, disc_weights) swap_test() return qml.expval(qml.PauliZ(0))
def read_binary_image(image, width_factor, height_factor): bits = numpy.where(image <= 128, 0, 1).astype(numpy.float32) simple_bits = simplify_image(bits, width_factor, height_factor) bits = numpy.where(simple_bits <= 0.5, 0, 1).astype(numpy.uint8) binary = bits.flatten() binary = fix_image_binary_l...
This code decodes a hidden file from a video by extracting a QR code from the first frame, which specifies parameters for reconstructing the file. It processes subsequent frames to extract binary data, writes it to a file, and outputs the recovered file with a modified name. The process includes progress tracking and t...
def decode(filename, output_dir=None): binary = bytearray() if not output_dir: output_dir = os.path.dirname(filename) cap = cv2.VideoCapture(filename) num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) ret, first_frame = cap.read() if not ret: return "", binary decoded ...
def _make_params_b(mat: np.ndarray, eta_n: int, preint: Union[Literal[False], int], rows: Optional[List] = None, parts: Optional[int] = None) -> Tuple[torch.Tensor, torch.Tensor, int, int, bool]: # Generate `eta_n` $eta$ values for each row in `rows` # convert to a torc...
The function `get_controls` computes synthetic controls for rows in a matrix `orig_mat` using parameters $ \eta $ and $ \mu $, optimizing them per row. It returns tensors of synthetic controls and denoised data. Key steps include preparing data, estimating weights via batch processing, minimizing loss, and unbinding re...
def get_controls(orig_mat, rows: Optional[List] = None, eta_n=10, mu_n=DEFAULT_DENOISE, cuda=False, parts=DEFAULT_PART, preint=False, train: float = 1., double: bool = False): """ Given the matrix of values 'orig_mat', computes synthetic controls for all rows in `rows`. If `rows` is None, ...
def _make_params( mat: np.ndarray, eta_n: int, preint: Union[Literal[False], int], treated_i: Optional[int] = None, parts: Optional[int] = None) -> Tuple[List, torch.Tensor, int, int, bool]: """ Prepares hyperparameters for the `get_control()` and `get_all_controls()...
The code computes synthetic controls for a treated unit in a matrix by optimizing parameters $ \eta $ and $ \mu $, using a combination of training data, parameter tuning, and loss minimization. It returns the best synthetic control data ($ Y0_o $), denoised original data ($ Y1_o $), and weights ($ v $) for the treated ...
def get_control(orig_mat: torch.Tensor, treated_i: int, eta_n: Optional[int] = 10, mu_n: Optional[Union[int, Literal[False]]] = DEFAULT_DENOISE, cuda: Optional[bool] = False, parts: Optional[Union[int, Literal[False]]] = DEFAULT_PART, ...
def homeAway(): gameDateVal=None gameNumVal=None homeAway=None n=data['focusedDateCount'] for i in range(0,n): if(data['gamesByDate'][i]['date']==today): gameDateVal=i; x=len(data['gamesByDate'][gameDateVal]['games']) for i in range(0,x): if(data['gamesByDate'][ga...
This function determines and displays the current game status or time on a screen. It checks the game's state (FINAL/OFF) and period to show "FOT", "FSO", or "F" for final periods, and "END" with the period number if the time is "00:00". If the time isn't "00:00", it displays the current time.
def pTime(): gameNumVal=homeAway()[2] gameDateVal=homeAway()[1] if(data['gamesByDate'][gameDateVal]['games'][gameNumVal]['gameState']=="FINAL" or data['gamesByDate'][gameDateVal]['games'][gameNumVal]['gameState']=="OFF"): if(period()==4): display1.print(" FOT") elif(period()==5):...
def _get_navigation_options(self): """Gathers and returns navigation options from the root node.""" options = {} self._add_options_from_node(options, self.root_node) return options def _get_full_path(self, node): path = [] if node == self.root_node: return sel...
The `start` method initiates a navigation loop, displaying available options at each node. It processes user input to either submit, give up, or navigate to the next node, repeating until the user submits or gives up. The loop retrieves options, validates input, and transitions between nodes accordingly, handling inval...
def start(self): """Begins the navigation process until user submits or gives up.""" while True: options = self._get_navigation_options() print( f"Current node: [{self._get_full_path(self.current_node)}]\n" f"Available options: {', '.join(f'\'{opti...