dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_tetromino(piece: int, rotations: int) -> tuple[np.array, tuple[int, ...]]: return tetrominos[piece][rotations % len(tetrominos[piece])] def carve(self, piece: int, rotations: int, location: int, allow_partial: bool) -> bool: # Unpack information tetromino, reverse_tetromino_topography = get_...
This function generates an initial Tetris-like board configuration by randomly placing tetromino pieces while managing checkpoints to backtrack when placements fail. It uses a loop to attempt piece insertion, adding checkpoints when regeneration occurs, and restores previous states if placement fails. The process conti...
def _generate_initial_config(self) -> None: # Add the number of lines to clear as full lines onto the board self.board[-self.L:, :] = True # Create the checkpoint manager instance checkpoint_manager = CheckpointManager() # While a piece sequence hasn't been found and the last l...
def servo(self, angle): """Moves the servo to the given angle""" print("Servo moving to: {} ".format(angle)) self.set_servo(self.SERVO_1, angle) time.sleep(.05) def read_distance(self): """Returns the GoPiGo3's distance sensor in MM over IC2""" d = self.distance_sensor.re...
The code's main task is to maintain a heading by scanning angles with a servo, checking proximity via a distance sensor. If an object is within 250 units, it triggers an "excited" response. The loop continuously adjusts the servo angle in steps, pausing briefly between each adjustment to monitor the environment.
def follow(self): """Responds to a close reading on the distance sensor by attempting to maintain heading""" while True: for ang in range(self.MIDPOINT-400, self.MIDPOINT+401, 100): self.servo(ang) time.sleep(.1) if self.read_distance() < 250: ...
def _scale_points(self,points,h,w): """ Expects list of tuples OR single tuple [(x,y),(x,y)] OR (x,y) """ h = float(h) w = float(w) if isinstance(points,list): return [self._scale_points(point,h,w) for point in points] return (points[0]/w,point...
This code adds a point to the output dictionary after scaling if required, draws the point, skips existing names in the output, and updates the display.
def _add_point(self,point): if self.scaled: point = self._scale_points(point,self.h,self.w) self.output[self.names[self.i]] = {'x':point[0],'y':point[1]} self._draw_point(point) while (self.i < len(self.names)) and (self.names[self.i] in self.output.keys()): ...
def _add_point(self,point): if self.scaled: point = self._scale_points(point,self.h,self.w) self.output.append({'x':point[0],'y':point[1]}) self._draw_point(point) def _remove_point(self): if len(self.output) > 0: self.output.pop(-1) def _redraw(self): ...
This code defines a mouse click handler that adds a point to a plot on left-click, closes the plot on middle-click, removes the last point on right-click, and redraws the plot after each action.
def _onclick(self,event): if event.inaxes: #Left Click if event.button==1: point = (event.xdata,event.ydata) self._add_point(point) #Mid Click elif event.button==2: ...
def _add_point(self,point): if self.scaled: point = self._scale_points(point,self.h,self.w) self.output[self.names[self.i]] = {'x':point[0],'y':point[1]} self._draw_point(point) while (self.i < len(self.names)) and (self.names[self.i] in self.output.keys()): ...
This code handles mouse click events in a matplotlib plot. It adds a point on left-click, closes the plot on middle-click, removes a point on right-click, and triggers a redraw to update the visualization.
def _onclick(self,event): if event.inaxes: #Left Click if event.button==1: point = (event.xdata,event.ydata) self._add_point(point) #Mid Click elif event.button==2: ...
def scale(data, min_screen, max_screen, min_data, max_data): """ get the scaled data with proportions min_data, max_data relative to min and max screen dimentions """ return ((data - min_data) / (max_data - min_data)) * (max_screen - min_screen) + min_screen def _get_x_y(self, src: tuple, dest: tupl...
Your return The code initializes a Pygame window to render a graph-based game, displaying nodes, edges, Pokémon, and agents. It handles user input, updates game state via a controller, draws background, game elements, and UI metrics (grade, moves, time). A "Stop" button terminates the game. The loop continuously upda...
def __init__(self): control = Controller() graph = control.get_graph() pg.init() self.screen = display.set_mode((WIDTH, HEIGHT), depth=32, flags=RESIZABLE) clock = pg.time.Clock() pg.font.init() FONT = pg.font.SysFont('Century', 20, bold=False) FONT2 = pg....
def encode(self, x : torch.Tensor): ''' Encodes input data See Also: :class:`onlinehd.Encoder` for more information. ''' return self.encoder(x) def _one_pass_fit(self, h, y, lr, bootstrap): # initialize class hypervectors from a single datapoint if b...
The main task of the code is to train a model using input data `x` and labels `y` via a learning process. It optionally encodes inputs, initializes class hypervectors with a bootstrap sample, and performs either a one-pass fit or iterative training over specified epochs with configurable batch sizes. The method returns...
def fit(self, x : torch.Tensor, y : torch.Tensor, encoded : bool = False, lr : float = 0.035, epochs : int = 120, batch_size : Union[int, None, float] = 1024, one_pass_fit : bool = True, bootstrap : Union[float, str] = 0.01)...
def random_integer(min_int=0, max_int=sys.maxsize): return random.randint(min_int, max_int) def random_string(length=10): chars = string.digits + string.ascii_letters return ''.join(random.choice(chars) for i in range(length)) def random_basic_value(): return random.choice([random_string(), random_integ...
The function `random_dict` generates a dictionary with a random number of key-value pairs (1 to `max_keys`). Each key is a random string, and each value is a random basic type (e.g., int, float, str). It returns the constructed dictionary.
def random_dict(max_keys=100): the_dict = {} for count in range(random_integer(1, max_keys)): the_dict[random_string()] = random_basic_value() return the_dict
def random_basic_value(): return random.choice([random_string(), random_integer(), ramdom_float(), random_builtin_value()]) def random_list(max_size=100): the_list = [] for count in range(random_integer(1, max_size)): the_list.append(random_basic_value) return the_list def random_dict(max_keys=1...
The code defines a function `random_value()` that randomly selects and returns a value generated by one of three functions: `random_basic_value()`, `random_list()`, or `random_dict()`, effectively producing a random basic value, list, or dictionary.
def random_value(): return random.choice([random_basic_value(), random_list(), random_dict()])
def forward_backward(self, batch_embed, batch_dict): zero_grad(self.model_params) for i in range(0, len(batch_embed), self.microbatch): _micro_embed = batch_embed[i : i + self.microbatch].to(dist_util.dev()) _micro_dict = { k: v[i : i + self.microbatch].to(dist_ut...
The code implements a training loop for a machine learning model, iterating over data batches to perform forward and backward passes. It includes logging, validation checks, checkpoint saving, and progress tracking using a progress bar. The loop continues until the specified learning steps are completed, with periodic ...
def run_loop(self): progress_bar = tqdm(desc="training run_loop", total=self.learning_steps) while ( not self.learning_steps or self.step + self.resume_step < self.learning_steps ): batch_embed, batch_dict = next(self.data) self.forward_backward(ba...
def main(): loadTerminal() loadUser() def setupDB(): if not path.isfile('Usage.db'): conn = sqlite3.connect('Usage.db') conn.execute('''CREATE TABLE Usage (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, User TEXT NOT NULL, ...
The code's main task is to execute the `main()` function, initialize the database with `setupDB()`, and render the main webpage using `renderMainPage("")` with an empty string parameter. This sequence prepares the application's core logic, database setup, and user interface rendering for the main page.
def index(): main() setupDB() return renderMainPage("")
def renderMainPage(err): return render_template("index.jinja", err=err, busyTerminals=getBusyTerminals(), users=USERS, terminals=TERMINALS, countBusyTerminal=countBusyTerminal(), countFreeTermianl=countFreeTermianl()) def insertToDb(user, termianl): conn = sqlite3.connect('Usage.db') cur = conn.cursor() ...
This function handles terminal allocation and return via HTTP form actions. If "action" is "taken", it validates user/terminal existence, inserts data into the database, and redirects on success or shows errors. If "action" is "return", it processes terminal return and redirects. Otherwise, it renders the index page wi...
def takenTerminal(): if (request.form.get("action") == "taken"): if (len(request.form.get("user")) != 0 or len(request.form.get("terminal")) != 0): if(request.form.get("terminal") not in TERMINALS): return renderMainPage("Terminal not found.") if(request.form.get("use...
def getCheckpointListFromInput(self, checkpoints_text: str, clean: bool = True) -> List[str]: """Get a list of checkpoints from the input string Args: checkpoints_text (str): the input string with all checkpoints clean (bool): remove the index and hash from the string Re...
The function removes elements at specified indices from both checkpoints and prompts strings, ensuring synchronized removal. It splits inputs into lists, validates indices, and reconstructs strings with remaining elements, returning updated lists. If indices are invalid or lengths mismatch, original strings are returne...
def remove_element_at_index(self, checkpoints: str, prompts: str, index: List[int]) -> List[str]: """Remove the element at the given index from the string Args: checkpoints (str): the input string with all checkpoints prompts (str): the input string with all prompts ...
def __hash_full_left(self): left_tups = self.__pull_input_tups(self.left_inputs) while left_tups is not None: _ = self.__hash(left_tups, self.left_dict, is_right=False) left_tups = self.__pull_input_tups(self.left_inputs) def __pull_input_tups(self, inputs): tups = [] ...
The main task of the code is to perform a hash join operation by first ensuring the left table is fully hashed, then probing the right table's tuples against the left's hash table to produce joined tuples. If no right tuples remain, it returns None.
def get_next(self): # YOUR CODE HERE if not self.left_hashed: # Block while hashing all of left table self.__hash_full_left() # Unblock after left table is in memory self.left_hashed = True # Probe with right right_tups = self.__pull_inpu...
def lemmatise_query(query): doc = nlp(query) lemmatized_tokens = [token.lemma_ for token in doc] query_lemm = ' '.join(lemmatized_tokens) return query_lemm def invalid_term(query, terms): # output words in the query that are not in the vocab invalids = [] for t in query.lower().split(): ...
This code processes a search query by handling multiple search modes (relevance, lemmatization, wildcard, boolean), filters invalid terms, accumulates matching indices, generates a bar chart visualization for results, and renders a template with query results, search mode, and exhibition data.
def search(): query = request.args.get('query') # get query from URL variable num_matches = 0 idx_matches = [] search_mode = "Relevance Search + Lemmatization" # default search mode naming_query = '' # for the naming of generated bar chart query_lemm...
def read_json_file(json_file): with open(json_file, 'r') as f: data = json.load(f) return data def set_avg_prices(gpu, json_file=json_today): data = read_json_file(json_file) price_list = get_price_list_for_gpu(gpu) avg_price = round(sum(price_list) / len(price_list)) # just checks if av...
This function updates the 'avg_price' and 'price_per_performance' metrics for each GPU in a JSON file. It checks if these values are zero and, if so, recalculates and sets them using helper functions. The goal is to ensure accurate pricing and performance data for GPUs by replacing placeholder zeros with computed value...
def update_avg_price_and_price_per_performance(json_file=json_today): file = read_json_file(json_file) for gpu in file: if file[gpu]['avg_price'] == 0.0: set_avg_prices(gpu, json_file) if file[gpu]['price_per_performance'] == 0.0: set_price_per_performance(gpu, json_file)
def getChannels (self, *patterns): patterns = ['*'] if not len(patterns) else patterns channels = [] for pat in patterns: p = channel(pat) if type(pat) == str else pat channels += [c for c in self.channels if re.search(p, channel(c))] r...
The code reads multiple files matching given patterns, processes their data into a dictionary of fluxes, and returns the result in specified formats (JSON, torch tensor, or dictionary). It filters out invalid channels and handles different output formats accordingly.
def readAll (self, *patterns, fields=['debit'], fmt='torch'): files = self.getChannels(*patterns) fluxes = {} for f in files: key = channel(f) flux = self.read(f, fields, fmt) if len(flux) > 0 and dataset.CHANNELS[key] != 'x': fluxes[key] = ...
def cleanTitle(t): title = t.replace(" ", "") if "[" in title: title = re.sub(r'\[[^]]*\]', '', title).strip() if "{" in title: title = re.sub(r'\{[^]}*\]', '', title).strip() for s in separationCharacters: if s in title: title = title.replace(s, "_").strip() titl...
The function downloads a playlist's videos or audio based on the option, organizes files into specified folders (videoPath/audioPath), cleans titles, and triggers playback for audio playlists. It uses `downloadContent` for individual items and `playPlaylist` if the option is audio.
def downloadPlaylist(option,url): playlist = Playlist(url) playlistTitle = cleanTitle(playlist.title) if option=="-p": downloadFolder = getDownloadFolder(name=playlistTitle,path=videoPath) contentOpt="-v" else: downloadFolder = getDownloadFolder(name=playlistTitle,path=audioPath...
def fill_common(self): """Fill in common data into the profile from SSO. """ for response_key, data_key in { 'first_name': 'name', 'email': 'email', 'mobile': 'contact_no', 'roll_number': 'roll_no', 'username': 'ldap_id' ...
The code's main task is to populate an object's attributes by calling methods like `fill_common`, `fill_name`, and `fill_profile_pic`, which likely set properties such as name, email, contact info, and profile picture. It also handles program details and institutional address, ultimately returning the modified object i...
def fill(self): self.fill_common() self.fill_name() self.oset('email') self.fill_contact() self.fill_profile_pic() self.fill_program() self.fill_insti_address() return self
def generate_str(total, name): for num in range(total): string = f"{name}-{num}" yield string def generate_num(total): pages_low = 100 pages_high = 500 for num in np.random.randint(pages_low, pages_high, total): yield int(num) def generate_votes(low, high, total): for num in ...
This function generates a sequence of book entries with randomized attributes like titles, authors, page counts, user ratings, and dates. It uses helper functions to create varying data and yields each generated book as a dictionary. The 'total' parameter determines the number of books, while 'months' influences the da...
def generate_books(total, months): votes_low = 0 votes_high = 6 title = generate_str(total, "title") author = generate_str(total, "author") pages = generate_num(total) user = generate_str(total, "user") votes = generate_votes(votes_low, votes_high, total) date = generate_dates(total...
def sample_coarse(key, n_points): points = jnp.arange(n_points) + jax.random.uniform(key, (n_points,)) points = points / n_points return points def render_single_ray(ray, ts, nerf, key, train=False): locations = eqx.filter_vmap(ray)(ts) direction = ray.direction / jnp.linalg.norm(ray.direction) ...
This function performs hierarchical ray rendering by first generating coarse samples, rendering them with a coarse neural network, calculating weights, then sampling fine points based on those weights. It renders the fine samples with a fine neural network and returns coarse and fine colors along with a weighted time s...
def hierarchical_render_single_ray(key, ray, nerfs, train, renderer_settings): coarse_reg_key, fine_reg_key, key = jax.random.split(key, 3) coarse_key, fine_key = jax.random.split(key, 2) coarse_ts = sample_coarse(coarse_key, renderer_settings["num_coarse_samples"]) if renderer_settings["t_sampling"] ==...
def batch_iterable(iterable, n=1): l = len(iterable) for ndx in range(0, l, n): yield iterable[ndx:min(ndx + n, l)] def get_topological_loss(model, tokenizer, batches, device='cuda:1', use_labels=False): nat_attentions = [] for batch in batches: input_ids, attention_mask, labels = batch ...
This function trains a model with topological loss by iterating over batches, calculating standard loss, and periodically computing topological loss for attention distributions. It logs training/validation losses, saves attention distribution plots, and returns the trained model.
def train_model_with_toploss( model, tokenizer, train_dataloader, val_dataloader=None, epochs=30, logging="logs/jokes/with_toploss", optimizer=None, use_labels=False, device="cuda:1" ): """ Train model with topological loss. ...
def showStartScreen(): titlefont = pygame.font.Font('freesansbold.ttf', 100) titleText = titlefont.render('SNAKE FUN', True, DARKGREEN) while True: SCREEN.fill(BGCOLOR) titleTextRect = titleText.get_rect() titleTextRect.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2) SCREEN.blit(titleText, titleTextRect) dra...
The main task of the code is to initialize a Snake game using Pygame, set up display and audio elements, and manage the game loop. It starts with a welcome screen, runs the game with background music, and transitions to a game-over screen upon losing. The loop restarts the game after each session, maintaining audio and...
def main(): global CLOCK, SCREEN, FONT pygame.init() CLOCK = pygame.time.Clock() SCREEN = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) FONT = pygame.font.Font('freesansbold.ttf', 18) pygame.display.set_caption('Snake Game') showStartScreen() while True: pygame.mixer.music.play(-1,0.0) runGame() ...
def hit(self, hand): card = self.get_card() hand.append(card) def get_sum(self, hand): rsum = 0 for card in hand: rsum += card return rsum def stay(self): # Ends players turn {TERMINAL STATE} # Dealer takes their turn # Reward is returned base...
The function `step` processes a player's action (hit or stay) in a game, determining if the game terminates or continues. If "hit," it draws a card and checks if the player busts (sum >21 or ≤0), returning termination and reward (-1). If "stay," the dealer plays, and the game ends with the result of the stay action. Th...
def step(self, action): # Given action {0: hit, 1: stay} # returns True/False depending on if the game has (T) Terminated or (F) Continues # If hit will pull card and return reward depending on if player busted or not # If stay will have dealer go then return reward if action == ...
def open_browser() -> webdriver: brow = webdriver.Chrome(cfg.CHROME_PATH) brow.set_window_size(1200, 850) time.sleep(3) return brow def find_all_matches(brow: webdriver, league_name: str) -> [webdriver]: matches_path = './/div[@class="block-event event-description"]' try: wait_clickable(brow, matches_path) e...
The function scrapes match data and associated quotes from a sports league website using a webdriver. It navigates to the league page, extracts match details, checks date ranges, inserts data into a database, and iterates through a specified number of matches. It handles browser operations, error checking, and data ins...
def scrape_league_quotes(brow: webdriver, league_name: str) -> webdriver: if not brow: brow = open_browser() brow.get(utl.get_league_url(league_name)) brow.refresh() time.sleep(5) for i in range(cfg.MATCHES_TO_SCRAPE): matches = find_all_matches(brow=brow, league_name=league_name) # Select the match or co...
def make_examples_list(): global examples_list with open('examples.txt', 'r', encoding='utf8') as tpairs: examples_list = tpairs.read() examples_list = ast.literal_eval(examples_list) print(type(examples_list)) def example_select_phrases(sentence): # Example input list of dictionaries input_list = exam...
The code translates Malayalam legal texts to English using GPT-4, leveraging example pairs for context. It constructs a prompt with examples, instructions, and input text, then runs the LLM chain to generate translations, ensuring precise legal terminology conversion.
def chatGPT_Trans(text): global examples_list make_examples_list() example_prompt = PromptTemplate(input_variables=["malayalam_sent", "translation"], template="Translate to English : {malayalam_sent}\n{translation}") llm = ChatOpenAI(model = 'gpt-4', temperature=0) phrases = "" ph = example_select_phrases...
def make_examples_list(): global examples_list with open('examples.txt', 'r', encoding='utf8') as tpairs: examples_list = tpairs.read() examples_list = ast.literal_eval(examples_list) print(type(examples_list)) def example_select_phrases(sentence): # Example input list of dictionaries input_list = exam...
The main task of the code is to translate Malayalam text to English using a fine-tuned GPT-3.5 model. It leverages few-shot learning by incorporating example translations, ensuring accurate legal document translation by relying on provided examples and avoiding hallucinations. The function constructs a prompt with cont...
def chatGPT_Trans_ft(text): llm = ChatOpenAI(model = 'ft:gpt-3.5-turbo-0613:personal::86bad9JC', temperature=0) # template = '''Return all the named Entities and their english transliteration as python lists. Return two lists one for named entities and the other for # english transliteration. # Context:" {text...
def num_AO(): global content_AO AO_line = content_AO[0] AO_line = [line for line in AO_line.split(" ") if line.isdigit()] numbers_AO = int(AO_line[0]) return numbers_AO def Overlap_Matrix(AO): global content glob...
This function calculates electronic coupling values between molecular orbitals (MOs) by analyzing fragment contributions, overlap matrices, and energy differences. It identifies relevant MOs around the LUMO, computes fragment-specific weights, and evaluates couplings based on charge replacement, energy criteria, and us...
def FCD_auto(Inv_MO,FD,FA,FC,FB,number_inter,contri_crit,wFMO,len_weight,energy_crit,Charge_crit,print_crit): global content_AO AO=num_AO() #Dictionary of couplings properties ECs={"Coupling_Name":[],"Coupling":[],"A_MO":[],"D_MO":[],"Contribution_D":[],"Contribution_A":[],"Weigh...
def isNegation(predA, predB): return predA.name == predB.name and predA.isNegated != predB.isNegated def unify(a, b, subst=None): if subst is None: subst = {} if a == b: return subst elif isinstance(a, Variable): # if a is a variable return unifyHelper(a, b, subst) elif isins...
This function checks if two clauses contain negated predicates that can be unified. If so, it substitutes arguments, combines remaining predicates, and checks for contradictions. If a contradiction (empty clause) is found, it returns the empty clause and True; otherwise, returns the combined clause and False. If no neg...
def isSatHelper(clauseA, clauseB): for predA in clauseA.predicates: for predB in clauseB.predicates: if isNegation(predA, predB): # if they are negations of each other subst = unify(predA.args, predB.args) # attempt to unify if subst is not None: ...
def mostCommonLabel(self, labels, weights): """ find most common label """ labelCount = np.unique(labels) weightedLabels = np.zeros(len(labelCount)) for label in labelCount: idx = np.where(labelCount == label)[0][0] weightedLabels[idx] = weights[la...
This code recursively builds a decision tree by selecting the feature with maximum information gain to split the data, creating left and right subtrees for each split. It terminates when maximum depth is reached or all labels in a node are identical, returning a leaf node with the most common label. The tree nodes stor...
def buildTree(self, features, labels, depth, weights): """ build the tree """ numFeatures = features.shape[1] if depth >= self.maxDepth or np.unique(labels).size == 1: leafVal = self.mostCommonLabel(labels, weights) return TreeNode(val=leafVal) to...
def common_block(self, _pair_sen, spacy_nlp): """common block for data preprocessing""" label_idx = int(_pair_sen[0]) - 1 if len(_pair_sen) == 3: src_tokens = self.input_preprocess(src_text1=_pair_sen[1], src_text2=_pair_sen[2], ...
This code loads and preprocesses training and test data from CSV files, applying tokenization, padding, and optional feature hashing. It organizes data into dictionaries grouped by sequence length for model input, handling varying test data formats and ensuring uniform sequence lengths via padding with 'PAD' tokens.
def load(self): """data preprocess loader""" train_dataset_list = [] test_dataset_list = [] spacy_nlp = spacy.load('en_core_web_lg', disable=['parser', 'tagger', 'ner']) spacy_nlp.add_pipe('sentencizer') with open(self.train_path, 'r', newline='', encoding='utf-8') as sr...
def try_existing_placeholders(circular_path, types, placeholder_names): for addr in circular_path: _type = types[addr] if _type.meta_type not in ptr_tags: continue pointed_type = types[_type.type] if get_symbol_name(pointed_type) in placeholder_names: _type.ty...
The function breaks circular dependencies in a type system by identifying pointers to named types, sorting them, and replacing the first pointer's target with a placeholder to prevent infinite recursion, ensuring the pointed type isn't a placeholder and has a known name.
def break_circular_path(circular_path, types, placeholder_names): if try_existing_placeholders(circular_path, types, placeholder_names): return # 1. Create a list of pointer types pointing to a type having a name. ptrs = [] for addr in circular_path: _type = types[addr] if _type....
def get_symbol_name(symbol): if symbol.linkage_name: return symbol.linkage_name return symbol.name def break_circular_path(circular_path, types, placeholder_names): if try_existing_placeholders(circular_path, types, placeholder_names): return # 1. Create a list of pointer types pointing ...
The code detects and breaks circular references in a type hierarchy by identifying cycles during traversal, replacing circular pointers with placeholder types to prevent infinite recursion. It tracks visited types, processes each type's members and dependencies, and introduces placeholders for resolved cycles, ensuring...
def break_circular_reference(subprograms, types, context): placeholder_names = set() context['placeholder_names'] = placeholder_names if len(types) == 0: return for _type in types.values(): _type.visited = -1 if _type.meta_type == MT_placeholder: placeholder_names.ad...
def run_zero_dim_hom(points): parameters = np.array([[i / 20 * np.pi, 2] for i in range(20)]) for scale in np.linspace(2.0, 2.0, 0): new_parameters = np.array([[i / 10 * np.pi, scale] for i in range(10)]) parameters = np.concatenate((parameters, new_parameters), axis=0) BCs, BC_list = Comput...
The function `get_maxs` computes topological features of input data (`cars`) using zero-dimensional homology, calculates death shifts and weighted values for each barcode component, and optionally generates a density diagram. It returns maximum values from these computations, leveraging persistent homology analysis for...
def get_maxs(cars, diagram = False, name = "density_diagram"): BCs, BC_list, parameters = run_zero_dim_hom(cars) BC_weights = [] for Y in BC_list: #print("hi") X = BCs Z,shift_dest = Compute_death_shifts_zero_dim(X,Y) weights = shift_dest*relative_positions(shift_dest)**2 ...
def Compute_Scaled_Deaths(all_spheres, new=False, plain=False, verbose=False): rotation = rotation_matrix(np.pi / 4) all_spheresx = all_spheres @ np.diag([2, 1]) all_spheresy = all_spheres @ np.diag([1, 2]) all_spheres_xy = all_spheres @ rotation @ np.diag([1, 2]) @ rotation.T all_spheres_anti_xy = ...
This function generates random points on spheres with parameters dependent on input `phi`, computes topological features (BCs, maxima), and returns the optimal angle fit derived from these maxima, using a variance-aware model with exponent 4. The core task is to determine the best angular alignment for a given `phi` th...
def run_best_angle_fit(phi): # print(phi) prob_rad = 2 prob_angle = 0.1 points = make_random_angle_spheres( 100, prob_angle, prob_rad=prob_rad, seed=int(phi * 1000), scaling_center=3000, phi=phi, rectangles=rectangles, ) BCs, BCxs, BCys, BC...
def deploy(self, dest: int, troops: int, player: int) -> bool: troops = self._preprocess_action([0, 0, 0, troops], player) self.state[dest] += troops self.players[player]["troops"] -= troops return False def attack(self, src: int, dest: int, player: int) -> bool: srcTroops = self...
The `take_action` method processes a game action for a specified player by dispatching it to corresponding sub-functions based on the action type. It handles deployment, attack, movement, assistance, or donation of troops, returning `True` if successful and `False` otherwise. The action parameters include type, source,...
def take_action(self, action, player: int) -> bool: action_type, src, dest, troops = action if action_type == 0: return self.deploy(dest, troops, player) elif action_type == 1: return self.attack(src, dest, player) elif action_type == 2: return self.m...
def get_keyword_list(text): # text = """ The couple took their seven pheras on Thursday afternoon, a source told ANI. The wedding, being held at Six Senses, Fort Barwara in Sawai Madhopur, Rajasthan, has been something of a state secret with guests subjected to a no-phone and no-photos rule. No inside pictures or ...
The main task of the code is to predict whether a given URL is likely to contain links by analyzing its content. It extracts keywords from the webpage content, checks each keyword's link status, aggregates results, and returns a final prediction on the URL's link potential.
def predict_link_score(url): # url = "https://www.dnaindia.com/education/report-cbse-class-10-12-board-exam-2022-term-1-cancellation-latest-updates-news-exam-centre-datesheetonline-petition-2917207" # url = "https://www.bbc.com/sport/football/59572726" content = get_content(url) # print(content) ...
def set_speed(self, throttle_val): if gs.emergency_stop: self.pwm.set_pwm(cf.THROTTLE_CHANNEL, 0, cf.THROTTLE_NEUTRAL) usleep(187500) return # Filter too low throttle to protect motors if abs(throttle_val) < cf.MIN_ACTIVE_SPEED: throttle_val = 0 ...
The code continuously controls a motor's speed and steering based on global variables until an exit signal is received. Upon exiting the loop, it stops the car and prints an exit message.
def run(self): while not gs.exit_signal: self.set_speed(gs.speed) self.set_steer(gs.steer) self.stop_car_on_exit(None, None) print("Exiting from MotorController")
def get_form_eval(): filename = PROJECT_PATH + "/data/eval.csv" with open(filename, "r") as f: csv_reader = csv.reader(f) for line in csv_reader: netid = line[1] form_eval.add(netid) def grab_final_grades(students): filename = PROJECT_PATH + "/data/indiv.csv" with...
The main task of the code is to aggregate student grades from PrairieLearn, combine them with Kahoot attendance data, calculate final scores including homework grades, and push the updated grades. It retrieves initial grades, merges attendance records, adjusts grades based on attendance, computes homework scores, and f...
def main(): get_form_eval() students = prairielearn.grab_grades() attendance = kahoot.get_all_attendance() students = grab_final_grades(students) #print(students["nikilr2"]["final"]) students, attendance = combine_kahoot_and_prairielearn(students, attendance) #print(students["nikilr2"]["fina...
def read_index(): """Read git index file and return list of IndexEntry objects.""" try: repo_root_path = get_repo_root_path() data = read_file(os.path.join(repo_root_path, '.git', 'index')) except FileNotFoundError: return [] except NoRepositoryError as nre: raise NoRepos...
The main task of the code is to generate a Git tree object from the current index entries by recursively organizing files and directories into a hierarchical structure, converting each entry into a tree entry with mode, path, and SHA-1 hash, and finally hashing the combined tree data to produce a tree object.
def write_tree(): """Write a tree object from the current index entries.""" tree_entries = [] tree_to_process = {'.': []} indexEntries = read_index() for entry in indexEntries: # we are going to create a dict, where the repo hierarchy is shown and used # to create the git objects ...
def get_status(): """ Get status of working copy, return tuple of (changed_paths, new_paths, deleted_paths). """ paths = set() for root, dirs, files in os.walk('.'): dirs[:] = [d for d in dirs if d != '.git'] for file in files: path = os.path.join(root, file) ...
The main task of the code is to display the differences between the index (staged files) and working directory (current files) for each changed file. It retrieves file contents from the index and working copy, uses `difflib.unified_diff` to generate diffs, and prints them with separators between files.
def diff(): """Show diff of files changed (between index and working copy).""" changed, _, _ = get_status() entries_by_path = {e.path: e for e in read_index()} for i, path in enumerate(changed): sha1 = entries_by_path[path].sha1.hex() obj_type, data = read_object(sha1) assert obj...
def get_factory_contract(): w3 = get_web3_provider() return w3.eth.contract(address=GIT_FACTORY_ADDRESS, abi=FACTORY_ABI) def get_repository_contract(address): w3 = get_web3_provider() return w3.eth.contract(address=address, abi=REPOSITORY_ABI) def init(repo): """ Create .git directory for repos...
The code clones a remote repository by verifying its existence via a blockchain contract, retrieves commit history, initializes the local repo, unpacks files from commits, sets the master branch reference, and updates the index with tracked files.
def clone(repo_name): """ Cloning a remote repository on the local machine. repo_name: Repository to be cloned """ # 0x0539E6a1093a359C5720d053DB5e3D277F1762B6/mumbaiTestRepo user_address, repo_name = repo_name.split('/') git_factory = get_factory_contract() user_key = git_factory.func...
def write_tree(): """Write a tree object from the current index entries.""" tree_entries = [] tree_to_process = {'.': []} indexEntries = read_index() for entry in indexEntries: # we are going to create a dict, where the repo hierarchy is shown and used # to create the git objects ...
The code creates a commit object by writing the current index tree, specifying parent commits (including merge handling), author/committer metadata, and the commit message. It generates a SHA-1 hash for the commit, updates the 'master' reference in the repository, and cleans up merge-related files if applicable. The fu...
def commit(message, author=None, parent1=None, parent2=None): """Commit the current state of the index to master with given message. Return hash of commit object. """ # we are working on write tree tree = write_tree() if parent1 == None: parent = get_local_master_hash() else: ...
def read_tree(sha1=None, data=None): """Read tree object with given SHA-1 (hex string) or data, and return list of (mode, path, sha1) tuples. """ if sha1 is not None: obj_type, data = read_object(sha1) assert obj_type == 'tree' elif data is None: raise TypeError('must specify...
This function recursively pushes Git tree and blob objects to IPFS, converting them into IPFS CIDs while preserving directory structure. It processes each tree entry, uploads blobs to IPFS, handles nested trees recursively, and constructs a corresponding IPFS tree object with metadata. The function returns the CID of t...
def __push_tree(tree_hash, folder_name): entries = read_tree(tree_hash) tree_entries = [] for entry in entries: if entry[0] == GIT_NORMAL_FILE_MODE: obj_type, blob = read_object(entry[2]) assert obj_type == 'blob' blob_to_push = { 'type': 'blob', ...
def read_tree(sha1=None, data=None): """Read tree object with given SHA-1 (hex string) or data, and return list of (mode, path, sha1) tuples. """ if sha1 is not None: obj_type, data = read_object(sha1) assert obj_type == 'tree' elif data is None: raise TypeError('must specify...
This function unpacks Git tree objects by recursively extracting blob contents into the specified directory. It decompresses objects, parses their headers, and writes file data while handling nested tree objects through recursive calls.
def __unpack_object(object_hash, repo_path, path_to_write): """ Takes an tress sha1 hash and read the local object. It iterates over the entries and writes the content of blobs to the repository. In case it comes across another tree object, it makes a recursive call. """ #TODO: have to make it more ...
def get_status(): """ Get status of working copy, return tuple of (changed_paths, new_paths, deleted_paths). """ paths = set() for root, dirs, files in os.walk('.'): dirs[:] = [d for d in dirs if d != '.git'] for file in files: path = os.path.join(root, file) ...
The main task of the code is to perform a Git-like pull operation in a blockchain-based repository system. It checks for local changes, validates repository existence, compares local/remote commit histories via SHA1 hashes, and identifies missing commits to synchronize the local repository with the remote. If no change...
def pull(): print('Pulling') changed, _, _ = get_status() # we are checking if there a changed files in the working copy or files staged which have not been committed. # if one case is true, pull won't be executed if len(changed) > 0 or not is_stage_empty: print("You have local changes. Add ...
def get_factory_contract(): w3 = get_web3_provider() return w3.eth.contract(address=GIT_FACTORY_ADDRESS, abi=FACTORY_ABI) def read_repo_name(): """Read the repoName file and return the name""" repo_root_path = get_repo_root_path() try: data = read_file(os.path.join(repo_root_path, '.git', 'n...
The main task of the code is to create a new blockchain repository using a factory contract. It retrieves user credentials, constructs a transaction to call the `createRepository` function, signs and sends it via Web3.py, then checks the transaction result. The function handles gas pricing, nonce management, and output...
def create(): git_factory = get_factory_contract() repo_name = read_repo_name() w3 = get_web3_provider() if repo_name == '': print('There is no repository name.') return #TODO: before creating tx and so on, check if this kind of repo exits already :) user_address = __get_use...
def read_repo_name(): """Read the repoName file and return the name""" repo_root_path = get_repo_root_path() try: data = read_file(os.path.join(repo_root_path, '.git', 'name')) except FileNotFoundError: return "" return data.rstrip().decode('ascii') def get_web3_provider(): """ ...
This function checks if a repository is already registered in the gitFactory blockchain contract by hashing the user's repository name and querying the contract's repository list. It returns True if the repository exists, False otherwise after establishing a web3 connection and retrieving the user's DLT address.
def check_if_repo_created(): """ Checks if the repository has been already registered in the gitFactory contract If it hasn't, False is returned, otherwise True """ repo_name = read_repo_name() w3 = get_web3_provider() if not w3.isConnected(): #TODO: Throw an exception print(...
def get_factory_contract(): w3 = get_web3_provider() return w3.eth.contract(address=GIT_FACTORY_ADDRESS, abi=FACTORY_ABI) def read_repo_name(): """Read the repoName file and return the name""" repo_root_path = get_repo_root_path() try: data = read_file(os.path.join(repo_root_path, '.git', 'n...
The function retrieves the commit hash (CID) of the remote 'main' branch from a blockchain-based Git repository. It interacts with smart contracts to obtain the repository address, checks the 'main' branch's status, and returns its head CID if active, otherwise returns None.
def get_remote_master_hash(): """ Get commit hash of remote master branch, return CID or None if no remote commits. """ git_factory = get_factory_contract() repo_name = read_repo_name() user_address = __get_user_dlt_address() user_key = git_factory.functions.getUserRepoNameHash(user_address...
def get_factory_contract(): w3 = get_web3_provider() return w3.eth.contract(address=GIT_FACTORY_ADDRESS, abi=FACTORY_ABI) def read_repo_name(): """Read the repoName file and return the name""" repo_root_path = get_repo_root_path() try: data = read_file(os.path.join(repo_root_path, '.git', 'n...
The code fetches remote commits from a blockchain-based Git repository, compares them with local commits, and updates the local repository with new commits from the remote 'main' branch. It retrieves repository details, checks for existence, extracts SHA1 hashes, synchronizes differences, and updates local files like F...
def fetch(): """ Downloads commits and objects from the remote repository """ git_factory = get_factory_contract() repo_name = read_repo_name() user_address = __get_user_dlt_address() user_key = git_factory.functions.getUserRepoNameHash(user_address, repo_name).call() user_key = '0x{}'....
def read_object(sha1_prefix): """Read object with given SHA-1 prefix and return tuple of (object_type, data_bytes), or raise ValueError if not found. """ path = find_object(sha1_prefix) full_data = zlib.decompress(read_file(path)) nul_index = full_data.index(b'\x00') header = full_data[:nul_...
The function recursively collects all SHA-1 hashes of objects related to a given commit, including the commit itself, its tree, and all parent commits, by traversing and aggregating their respective object hashes into a set.
def find_commit_objects(commit_sha1): """Return set of SHA-1 hashes of all objects in this commit (recursively), its tree, its parents, and the hash of the commit itself. """ objects = {commit_sha1} obj_type, commit = read_object(commit_sha1) assert obj_type == 'commit' lines = commit.decode...
def read_object(sha1_prefix): """Read object with given SHA-1 prefix and return tuple of (object_type, data_bytes), or raise ValueError if not found. """ path = find_object(sha1_prefix) full_data = zlib.decompress(read_file(path)) nul_index = full_data.index(b'\x00') header = full_data[:nul_...
This function pushes a Git commit and its dependencies (tree, blobs) to IPFS, avoiding redundant uploads by comparing local/remote commit hashes. It parses commit metadata, recursively pushes parent commits and referenced trees, and returns the IPFS CID of the stored commit object.
def __push_commit(commit_hash, remote_commit_hash, remote_commit_cid): """ Used to push a commit, the tree it references and the blobs to ipfs. commit_hash - The sha1 hash of the local commit object remote_commit_hash - The sha1 hash of the remote commit object. With this we know that we don't have to...
def get_local_master_hash(): """Get current commit hash (SHA-1 string) of local master branch.""" repo_root_path = get_repo_root_path() master_path = os.path.join(repo_root_path, '.git', 'refs', 'heads', 'master') try: return read_file(master_path).decode().strip() except FileNotFoundError: ...
This function checks if the staging area (index) matches the committed entries from the last commit. It compares each index entry's path and SHA-1 hash with the committed tree entries. If any mismatch is found, it returns False (stage is not empty); otherwise, returns True (stage is empty).
def is_stage_empty(): """ Comapres the entries from the last commit object with the ones in the index file. If there is a difference, the stage is not empty. If there is a difference, the stage is not empty """ local_sha1 = get_local_master_hash() obj_type, data = read_object(local_sha1) as...
def forward_propagate(self, input_value): """ Run the input through our neural network and return the inputs of the last layer """ # Save the initial input for the backward_propagate self.params['Activation'][-1] = input_value # input layer activations becomes sampl...
The code trains a neural network using backpropagation over multiple epochs, updating parameters with each training example. It validates performance after each epoch using a separate validation dataset, printing the epoch number, elapsed time, and accuracy. The process iteratively improves the network's ability to pre...
def train(self, x_train, y_train, x_val, y_val): """ Train the network based on x_train and expected values y_train Validate learning with test values (x_val/y_val) """ print("[*] Starting training") start_time = time.time() for iteration in range(self.epo...
def load_google_mobility(remove_foreign=True): csv_path, date = _get_file(raw_dir, 'google_mobility_report') mobility = pd.read_csv(raw_dir / csv_path, parse_dates = True) if remove_foreign: mobility = mobility[mobility.loc[:,'country_region_code'] == 'US'] mobility.drop(labels=['countr...
The function generates a dataframe combining static county data, mobility metrics, and cumulative/death time series for counties with confirmed outbreaks. It filters counties based on outbreak onset thresholds, ensures sufficient post-onset data, and merges mobility trends (baseline, pre/post-onset) with hospital capac...
def get_cum_deaths_dataframe(n_days, onset_threshold=3, time_series=False): """ Returns a dataframe of static variables, mobility statistics, and deaths (cumulative) ndays out. Parameters ---------- n_days : int Number of days out to record deaths onset_threshold : int ...
def get_text(self) -> str: return self.text_var.get() def hide_edit_box(self, event, window: str, value=None): self.control_canvas.itemconfigure(window, state="hidden") self.text_var.set(event.widget.get() if not value else value) event.widget.destroy() self.show_control() def hi...
This code creates and displays an editable text box (Entry widget) on a canvas at a specified position, initializes it with existing text, centers the text, binds the Enter key to hide the box, and calls a method to hide another control element.
def show_edit_box(self, event): box = tkinter.Entry() box.insert(0, self.get_text()) box.config(justify="center") width, height = parse.parse_geometry(self.control_data["display"]) window = self.control_canvas.create_window( parse.parse_coordinates(self.control_data["...
def open_drawer(robot_name, drawer_name, drawer_handle_name): #robot = get_robot(robot_name) #sname = get_surface_name(drawer_name) surface = get_surface('indigo_drawer_top') current_conf = utils.open_the_drawer(world,surface, items_on_surface=item_in_itemholder[drawer_name]) is_open[drawer_name] = ...
The code defines a function `perform_action` that routes input parameters to specific functions based on the `name` argument. It checks if `name` matches actions like 'open-drawer', 'navigate', 'pick-up', 'place', or 'close-drawer', then calls corresponding functions with the provided parameters. The main task is to di...
def perform_action (name, params): a = name if a == 'open-drawer': open_drawer(params[0],params[1],params[2]) if a == 'navigate': navigate(params[0],params[1],params[2], method="traj_opt") if a == 'pick-up': pick_up(params[0],params[1],params[2]) if a == 'place': plac...
def applicable(self, state, positive, negative): return set(positive).issubset(set(state)) and set(negative).isdisjoint(set(state)) def ordered_actions(self, state, action_plan_relaxed): actions_ordered = [] possible_actions = self.possible_actions(state) # Find helpful actions ...
This code implements a planning algorithm that combines hill climbing with a relaxed heuristic and BFS to find a sequence of actions to reach a goal state. It iteratively selects actions that reduce the heuristic value, handles dead ends by attempting BFS, and constructs a solution plan by appending actions. The main t...
def solve(self): # Initialise solution state = set(self.s_0) h_curr = float('inf') action_plan = [] action_plan_relaxed = [] # Continue performing actions while not in the goal state while not self.applicable(state, self.s_goal_pos, self.s_goal_neg): ...
def log_in(self): try: log_in_path = '//p[@class="izU2O"]/a' log_in_button = self.driver.find_element_by_xpath(log_in_path) log_in_button.click() time.sleep(2) # It does not work without sleep here, retarded like ahk try: x_user_name_i...
This code automates downloading Instagram posts from a target user's profile. It initializes login credentials, navigates to Instagram, logs in, accesses the target profile, scrolls to load posts, creates a directory if needed, and downloads images to the specified path using Selenium.
def __init__(self, username=c.instagram_user_name, password=c.instagram_password, target_username='fruskac', path='C:\est\photos'): self.username = username self.password = password self.target_username = target_username self.path = path self.driver = webdriver.C...
def nunlm_from_acoefs(nunl0, l, a1=0, a2=0, a3=0,a4=0,a5=0,a6=0): nu_nlm=[] for m in range(-l, l+1): val=nunl0 + a1*Pslm(1,l,m) + a2*Pslm(2,l,m) if l>=2: val=val + a3*Pslm(3,l,m) + a4*Pslm(4,l,m) if l>=3: val=val + a5*Pslm(5,l,m) + a6*Pslm(6,l,m) nu_nlm.append(val) return nu_nlm def Tnlm(nu_nlm, l): ...
This function tests if input a-coefficients can be accurately retrieved by comparing original values with those obtained from measured symmetric (Tnlm) and asymmetric (Snlm) splittings. It calculates Tnlm/Snlm from nu_nlm derived from input a-coefficients, then uses eval_acoefs() to reconstruct a-coefficients from nu_n...
def test_acoef(l=1, a1=1, a2=0, a3=0, a4=0, a5=0, a6=0, nu_nl=1000.): ''' With this function you can see whether by putting some input a-coefficients, you do retrieve them after you measure directly the symetrical splittings (Tnlm) and asymetrical splitting (Snlm) ''' nu_nlm=nunlm_from_acoefs(nu_nl, l, a1=a1, ...
def w(energy): return (energy+m_e)/m_e def t(energy): Beta = beta(energy) return 1/Beta * 0.5 * math.log((1+Beta)/(1-Beta)) - 1 def beta(energy): return math.sqrt(1.-1./gamma(energy)/gamma(energy))
The code computes a radiative correction factor based on energy levels and parameters V_f and E_0. It evaluates functions w(), t(), and beta() dependent on energy, calculates W_0 from E_0-V_f, and returns 0 if W_0 ≤ W. Otherwise, it computes a complex formula involving exponents, logarithms, and terms with T, Beta, and...
def radiative_correction(energy, V_f, E_0): W = w(energy) T = t(energy) Beta = beta(energy) W_0 = w(E_0-V_f) if W_0<=W: return 0 value = math.pow(W_0-W, 2*alpha/pi * T) * (1 + 2. * alpha /pi * ( \ T * (math.log(2.) - 1.5 + (W_0-W)/W) + 0.25 * (T+1.) * (2.*(1.+Beta*Beta) + 2.*math...
def epsilon(energy, V_f, E_0): return E_0 - energy - V_f def radiative_correction(energy, V_f, E_0): W = w(energy) T = t(energy) Beta = beta(energy) W_0 = w(E_0-V_f) if W_0<=W: return 0 value = math.pow(W_0-W, 2*alpha/pi * T) * (1 + 2. * alpha /pi * ( \ T * (math.log(2.) - 1....
The function computes a weighted sum of contributions from final states, where each term involves an energy-dependent variable (Epsilon), a square root factor, and a radiative correction. The sum is multiplied by Fermi function, momentum, and a mass term, with conditions filtering out invalid states based on Epsilon an...
def shape_fcn(x, ms, E_0): return_value = 0 for i in range(len(final_state_energy)): Epsilon = epsilon(x, final_state_energy[i], E_0) if Epsilon<=0 or Epsilon**2<=ms: continue return_value += final_state_prob[i] * Epsilon * math.sqrt(Epsilon**2 - ms) * \ radiative...
def update_cells(self): """Updates the graphical representation of cells. Counts the number of correctly filled in cells Returns: int: number of correctly filled in cells """ self.num_pos = { 0: set(), 1: set(), 2: set(), ...
The main task of the code is to update the Sudoku GUI by clearing the screen, refreshing grid elements, numbers, and peripherals, then redrawing everything to reflect the current game state. It fills the background, updates cells, draws grid lines, numbers, selection highlights, and additional UI components before call...
def update_gui(self): """Updates Sudoku GUI """ # background of GUI should be white self.display.fill(WHITE) total = self.update_cells() self.draw_select_fill() self.draw_grid_lines() self.draw_numbers() self.draw_peripherals(total) pyga...
def select_cell(self, pos): """Get selected cell from mouse position and highlight it Args: pos (tup of 2 ints): pos[0] is the x-position of mouse, pos[1] is the y-position of mouse """ if self.input_area.collidepoint(pos): # if play clicks inside...
This function processes Pygame events in the main game loop, handling window closure, mouse clicks for cell selection, keyboard inputs for mode toggling, number entry, arrow key navigation, Sudoku solving, board clearing, undo operations, and note updates. It maintains game state history and triggers actions like solvi...
def check_events(self): """Check pygame events during main game loop """ for event in pygame.event.get(): num = None delete = False state_changed = False # enable closing of display if event.type == pygame.QUIT: self.run...
def get_package(self, package_name='requests'): url = 'https://libraries.io/api/search?q={}'.format(package_name) response = self.get_response(url) results = response.json() filtered_results = list(filter(lambda obj: obj['name'].lower() == package_name.lower() and obj['stars'] > 0, resul...
This function retrieves and processes package information, including dependencies and repository details, caching the result for future use. It fetches a package, calculates its dependency graph and count, integrates repository metadata, and stores the processed data in a cache to avoid redundant processing.
def get_processed_package(self, package_name='requests'): if package_name not in self.package_cache: package = self.get_package(package_name) package['dependencies'] = self.get_dependencies(package)['dependencies'] package['dependency_graph'] = self.preorder_label_parent(pac...
def validate(block,peer): # Get balances of all peers till the previous block ID balances = get_balance(peer,block.prev_blk_id).copy() # For each transaction, we update the balances of the peers dump(block) print(balances) for transaction in block.transactions: if(tran...
The function `add_cache` processes cached blocks in a peer's network, validating and propagating blocks to neighbors. It checks if a cached block extends the current block chain, updates depths, and broadcasts valid blocks. For honest nodes, it shares blocks with neighbors; for attackers, it manages secret chains, sele...
def add_cache(task_list,peer_list,peer,block,rho,current_time): check=0 rem_task=None # Iterating over all tasks that have been cached for nexttask in peer.cacheBlock: rem_task=nexttask if nexttask[4].prev_blk_id != block.blk_id: # On not finding a block that comes ...
def near_vertices(self, n): # find the neighbors of the new node that is within B = [1,1,1] of the new node, where B specify helf length of the box neighbors = [] for node in self.nodes: if abs(node.pos[0] - n.pos[0]) <= self.B[0] and abs(node.pos[1] - n.pos[1]) <= self.B[1] and abs(...
This function identifies the optimal path to a goal by selecting the closest node with the minimum cost, then backtracking through parent pointers to reconstruct the path. It first locates nodes near the goal, evaluates their costs, and retrieves the lowest-cost node. The path is built by traversing parent links from t...
def find_path(self): # get all the nodes that are close to the goal # close_nodes = [] # for node in self.nodes: # if self.close(node, self.goal): # close_nodes.append(node) close_nodes = self.near_vertices(self.goal) print("Goal node: ", self.goal)...
def nearest(self, state): distances = [self.distance(state.pos, n.pos) for n in self.nodes] nearest_idx = np.argmin(distances) return self.nodes[nearest_idx] def steer(self, s1, s2): # get tranformation from s1 to s2 T_1 = coordinate_to_matrix(s1.pos[0], s1.pos[1], s1.pos[2]) ...
This code implements a path planning algorithm that iteratively samples random states, extends a tree structure toward these states, checks feasibility within the configuration space, and rewires the tree to optimize path costs. The goal is to generate a valid path from the start to the goal state by dynamically adjust...
def plan(self): print("Planning start! ") for i in range(self.max_iterations): # sample a random state # self.goal_rate of sample the goal state if random.random() < self.goal_rate: rand = self.goal.pos else: rand = [random....
def _ipVersionToLen(version): """Return number of bits in address for a certain IP version. >>> _ipVersionToLen(4) 32 >>> _ipVersionToLen(6) 128 >>> _ipVersionToLen(5) Traceback (most recent call last): File "<stdin>", line 1, in ? File "IPy.py", line 1076, in _ipVersionToLen ...
The main task of the code is to convert an IP address into its binary string representation, ensuring proper bit-length formatting and prefix handling. It calculates the required bit-length based on the IP version, pads the binary string with leading zeros to match this length, and appends a prefix (if specified) to fo...
def strBin(self, wantprefixlen = None): """Return a string representation as a binary value. >>> print(IP('127.0.0.1').strBin()) 01111111000000000000000000000001 >>> print(IP('fc00:db20:35b:7399::5').strBin()) 001000000000000100000110010110000000001000101010110010101111111000000...
def int(self): """Return the first / base / network addess as an (long) integer. The same as IP[0]. >>> "%X" % IP('10.0.0.0/8').int() 'A000000' """ return self.ip def prefixlen(self): """Returns Network Prefixlen. >>> IP('10.0.0.0/8').prefixlen() ...
This code defines the __add__ method to combine two adjacent IP networks of the same version and prefix length into a larger network with a reduced prefix length, ensuring compatibility and adjacency before creating a new IP object with the merged network.
def __add__(self, other): """Emulate numeric objects through network aggregation""" if self._ipversion != other._ipversion: raise ValueError("Only networks with the same IP version can be added.") if self._prefixlen != other._prefixlen: raise ValueError("Only networks wit...
def strFullsize(self, wantprefixlen = None): """Return a string representation in the non-mangled format. >>> print(IP('127.0.0.1').strFullsize()) 127.0.0.1 >>> print(IP('fc00:db20:35b:7399::5').strFullsize()) fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b """ if self....
The main task of the code is to generate a compressed string representation of an IPv6 address using '::' notation by identifying and replacing the longest sequence of consecutive zeros with '::', while handling special cases like IPv4-mapped addresses and optional prefix lengths. It ensures proper formatting for both ...
def strCompressed(self, wantprefixlen = None): """Return a string representation in compressed format using '::' Notation. >>> IP('127.0.0.1').strCompressed() '127.0.0.1' >>> IP('fc00:db20:35b:7399::5').strCompressed() 'fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b' >>> IP('ff...
def calculate_h_score(containers, state, target): # if the target has been reached, h_score will be 0 if target in state: return 0 # Find the reject indies (Some containers are too small to fill the target): inds_reject = np.where(containers < target) # Find the nearest value to the target...
The code constructs a graph to solve a container arrangement problem, aiming to find the minimal steps to reach a target state. It initializes a graph with a starting state (all containers unselected) and calculates an initial heuristic score. The graph is iteratively expanded by exploring valid states, updating nodes ...
def construct_graph(containers, target): select_list = [] start_state = np.zeros(shape=len(containers)) select_list.append(start_state.tolist()) start_h_score = calculate_h_score(containers, start_state, target) g = ig.Graph() # Create the empty graph firstly # Create the starting node g.a...
def calculate_h_score(containers, state, target): # if the target has been reached, h_score will be 0 if target in state: return 0 # Find the reject indies (Some containers are too small to fill the target): inds_reject = np.where(containers < target) # Find the nearest value to the targe...
This code constructs a graph for pathfinding by iteratively expanding nodes from an initial state. It starts with a node representing zero containers, calculates heuristic scores, and expands the graph using an expansion function until a termination condition is met. The graph tracks states, scores, and goal status, ai...
def construct_graph(containers, target): select_list = [] start_state = np.zeros(shape=len(containers)) start_h_score = calculate_h_score(containers, start_state, target) g = ig.Graph() # Create the empty graph firstly # Create the starting node g.add_vertex(name = 'start', ...
def get_pA1(self, dataset): """ This function is used to calculate p for each dataset. p is the probability that Y = 1 in the dataset. Parameters ----------- dataset: pandas dataframe Dataframe from parent node Returns -------- pA1: ...
The code initializes a node for a classification tree, determining the best split using an impurity function. It checks dataset purity, sets node predictions, and recursively creates left/right children by splitting data based on optimal variables/values. The node tracks splits, manages data subsets, and propagates spl...
def __init__(self, dataset, respond_variable,impurity_function, whole_data_length = 0, prev_split = []): """ Build classification trees by recursively initailize and split each node. Parameters ----------- dataset: pandas dataframe The dataset used for buildi...
def parse_args(args=None): """Parse commandline arguments.""" parser = argparse.ArgumentParser("Message writer", description="Write message into a json file for wms") parser.add_argument("config_file", help="The configuration file to run on.") ...
The main task of the code is to parse command-line arguments, load a configuration file, determine geographic areas either from a TROLLFLOW2 config or the current config, and then subscribe to and ingest data using the specified configuration and areas.
def main(args=None): """Main script.""" parsed_args = parse_args(args=args) config = read_config(parsed_args.config_file) try: # read from trollflow2 config file areas = read_trollflow2_config(config['trollflow2_config_file']) except: # or use config in this config file ...
def previous_xorshift( seed: numba.uint32, shift1: numba.uint32, shift2: numba.uint32, shift3: numba.uint32 ): seed = reverse_xor_rshift(seed, shift3) # print(seed) seed = reverse_xor_lshift(seed, shift2) # print(seed) seed = reverse_xor_rshift(seed, shift1) return numba.uint32(seed) def get...
This function identifies seed ranges in a game's random number generator that produce specific item combinations (trinket, card, pill) by iterating through seeds, checking item types, and validating conditions using XORshift operations. It returns a list of seeds meeting the criteria for the requested items.
def jit_reverser( active: int = 0, passive: int = 0, card: int = 0, trinket: int = 0, pill_effect: int = 0, start_seed: int = 0, end_seed: int = 0xFFFFFFFF, ): collectibles_number = 0x2DA trinket_number = 0xBE card_number = 0x16 potential_drop_seed: numba.uint32 = 0 pot...
def set_minimum_start_time(self, node): # If any node needed by this one has not been scheduled, this node cannot start for req in node.requirements: if req.scheduled_time == -1: return -1 # the minimum time possible for this node is the maximum time (scheduled + runtime) obtained from all its dependencies...
The main task of the code is to schedule computational nodes (tasks) on CPU and GPU resources, considering dependencies, deadlines, and resource availability. It dynamically selects the next node to execute based on earliest available time, prioritizes tasks to meet deadlines, and optimizes scheduling by checking for p...
def create_schedule(self): # For each CPU and GPU creates a list of nodes execution_elements_cpu = [[] for i in range(0, self.n_cpu)] execution_elements_gpu = [[] for i in range(0, self.n_gpu)] # Creates the same lists to save times (at what time is the computation) for each processor times_cpu = [[(0.0,0.0)]...
def set_minimum_start_time(self, node): # If any node needed by this one has not been scheduled, this node cannot start for req in node.requirements: if req.scheduled_time == -1: return -1 # the minimum time possible for this node is the maximum time (scheduled + runtime) obtained from all its dependencies...
The main task of the code is to schedule tasks using the HEFT (Heterogeneous Execution Framework) algorithm on a heterogeneous system with CPU and GPU resources. It processes available nodes, assigns them to the earliest-available CPU/GPU based on execution times, manages dependencies, minimizes delays by prioritizing ...
def create_schedule_HEFT(self): execution_elements_cpu = [[] for i in range(0, self.n_cpu)] execution_elements_gpu = [[] for i in range(0, self.n_gpu)] times_cpu = [[(0.0,0.0)] for i in range(0, self.n_cpu)] times_gpu = [[(0.0,0.0)] for i in range(0, self.n_gpu)] # While there are still frames to proc...
def import_graph(): # This dict will contain all nodes with the following key = ['node name', level, frame number] node_list = {} # The data is read and put into this variable split into rows to be able to run through it multiple times file_data = None with open(GRAPH_FILE) as graph: file_data = graph.read() fi...
The code simulates task scheduling algorithms (HEFT, EDD, G-FL, XEFT) on a dependency graph, evaluating performance metrics like makespan, average/max lateness, and frame times. It processes nodes across frames, categorizes them into CPU/GPU queues, sorts by priority/deadlines, and generates schedules. Results include ...
def simulation(UNIQUE_RUN_ID = None): node_list = import_graph() if (not HEFT): for key in node_list: node_list[key].check_copy() end_points = calculate_end_points(node_list) start_points = calculate_start_points(node_list) add_cross_dependencies_between_frames(node_list, start_points, end_points) create_de...
def create_schedule_HEFT(self): execution_elements_cpu = [[] for i in range(0, self.n_cpu)] execution_elements_gpu = [[] for i in range(0, self.n_gpu)] times_cpu = [[(0.0,0.0)] for i in range(0, self.n_cpu)] times_gpu = [[(0.0,0.0)] for i in range(0, self.n_gpu)] # While there are still frames to proc...
The main task of the code is to schedule nodes using HEFT, reset processor-specific node lists, recalibrate deadlines and priority points, sort nodes by priority/deadline, rebuild ready queues, and initiate a new scheduling process. It prepares the system for subsequent scheduling by clearing HEFT flags, adjusting node...
def create_schedule_GFL_C(self): global HEFT, PIPELINING # Firstly we schedule the nodes using HEFT, this is is a necessary step to create the mapping old_pipe = PIPELINING PIPELINING = False self.create_schedule_HEFT() PIPELINING = old_pipe # We also reset the CPU/GPU node lists self.node_list_cpu = []...
def extract_libs_from_apk(apk_file: str, out_dir: str): with zipfile.ZipFile(apk_file, "r") as zf: try: app_info = zf.getinfo('lib/arm64-v8a/libapp.so') flutter_info = zf.getinfo('lib/arm64-v8a/libflutter.so') except: sys.exit("Cannot find libapp.so or libflutter....
The main task is to process an input directory (or APK file) by extracting 'libapp' and 'libflutter' files, then pass them to `main2()` along with parameters like rebuild flag, Visual Studio solution creation, and analysis skipping. If input is an APK, it uses a temporary directory for extraction.
def main(indir: str, outdir: str, rebuild_blutter: bool, create_vs_sln: bool, no_analysis: bool): if indir.endswith(".apk"): with tempfile.TemporaryDirectory() as tmp_dir: libapp_file, libflutter_file = extract_libs_from_apk(indir, tmp_dir) main2(libapp_file, libflutter_file, outdir,...
def convert_doccano_to_spacy(json_file_path): """ Converts the JSON resulted from doccano tagging to spacy format :param json_file_path: Path to the JSON document with text and labels :return: A list containing the text(CV content) and dictionary with labels """ try: training_data = [] ...
The main task of the code is to train a custom spaCy NLP model using Doccano-labeled JSON data. It converts training and test data into spaCy format, trains the model with 30 iterations on the English "en_core_web_sm" pipeline, saves the trained model, and returns the model file path.
def main_train(): train_data = convert_doccano_to_spacy("train.json") test_data = convert_doccano_to_spacy("test.json") trained_nlp = train_spacy(train_data, test_data, "en_core_web_sm", 30) model_file = save_model(trained_nlp) return model_file
def SetupNewChain(): subprocess.getstatusoutput("rm -rf ~/.comdex") print("deleted previos state") print("rebuilding binaries.....") response = subprocess.getstatusoutput(f"make install --directory={COMDEX_DIR_PATH}") print(response[1]) print("binary re-build done ✔️") subprocess.getstatusou...
The code validates directory paths for a blockchain setup, initializes a new chain, starts it in a separate thread, sets up chain indicators and state, and provides a Ctrl+C prompt to stop the chain.
def main(): if not os.path.exists(HOME_DIR): exit(f"Error - root dir not found {HOME_DIR}") if not os.path.exists(COMDEX_DIR_PATH): exit(f"Error - invalid comdex repo path {COMDEX_DIR_PATH}") SetupNewChain() thr = threading.Thread(target=StartChain, args=(), kwargs={}) thr.start() ...
def add_padding(data_to_pad): max_length = -1 for sentence in data_to_pad: if len(sentence.split(' ')) > max_length: max_length = len(sentence.split(' ')) for i in range(len(data_to_pad)): pad_to_add = (max_length - len(data_to_pad[i].split(' ')))*' _PAD' data_to_pad[i] +...
The code trains a neural network model using a dataset of pairs, processing them in batches. It prepares input tensors with padding, calculates loss via CrossEntropyLoss, and updates the model using Adam optimizer. After each epoch, it computes average loss and saves the trained model.
def train(model, source, target, pairs, epochs=15): model.train() pad_idx = source.word2index['_PAD'] criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.01) total_loss_iterations = 0 # training_pairs = np.array([tensorsFromPair(source, target, pair) for pair in pai...
def load_data(filename, train=True): """Loads the data from the JSON files. You are welcome to create your own class storing the data in it; e.g., you could create AlchemyWorldStates for each example in your data and store it. Inputs: filename (str): Filename of a JSON encoded file containing...
The code trains and evaluates a sequence-to-sequence model for instruction-based tasks. It supports training (with data loading, model construction, and training loop) or prediction (using a saved model on test/dev data). The model processes instructions, states, and actions, employing encoders for instructions and wor...
def main(): # A few command line arguments parser = ArgumentParser() parser.add_argument("--train", type=bool, default=False) parser.add_argument("--predict", type=bool, default=False) parser.add_argument("--mode", default='instruction') parser.add_argument("--saved_model", type=str, default="")...
def mover_esquina(): giro_esq() mover() giro_esq() def mover_lado_interior(): for i in range(6): mover() def mover_esquina_interior(): girar_direita() mover() girar_direita()
The main task of the code is to execute a sequence of movements that alternate between corners and inner edges, creating a zig-zag path. The function calls `mover_esquina` (move to a corner), `mover_lado_interior` (move along an inner side), `mover_esquina_interior` (move to an inner corner), and repeats the inner side...
def zig_zag(): mover_esquina() mover_lado_interior() mover_esquina_interior() mover_lado_interior()
def mover_lado(): while front_is_clear(): mover() def giro_esq(): turn_left() global mov mov = mov +1 def zig_zag(): mover_esquina() mover_lado_interior() mover_esquina_interior() mover_lado_interior() def mover_esquina(): giro_esq() mover() giro_esq()
The code defines a function `varredura()` that orchestrates a sequence of movements for a robotic system, including lateral movements, left turns, zig-zag patterns, and corner navigation. Its main task is to guide the robot through a structured path involving repeated directional changes and precise positioning, likely...
def varredura(): mover_lado() giro_esq() mover_lado() zig_zag() zig_zag() zig_zag() mover_esquina() mover_lado() giro_esq()
def isType(self, ty): t = self.token() return t != None and t.type == ty def match(self, ty): t = self.lexer.next() if t == None or t.type != ty: raise Exception("Error: unexpected token type!") return t def tryMatch(self, ty): if self.isType(ty): ...
This code parses RISC-V assembly directives and operations by processing tokens from a lexer. It identifies labels, directives (e.g., .data), and instructions, validates operand types, and yields corresponding RISC-V operation objects with parsed parameters. The parser handles various instruction formats, ensuring corr...
def parse_(self): while self.lexer.peek(): if self.isType(TokenClass.DOT): self.match(TokenClass.DOT) name = self.match(TokenClass.SYMBOL).value if self.tryMatch(TokenClass.NEWLINE): yield riscv.DirectiveOp.get(name) ...
def read_input(input_path: str) -> tuple[list[list[str]], list[list[int]]]: with open(input_path, 'r') as input_file: input = input_file.read() input = input.split('\n\n') stack_items_list = parse_stack_information(input[0]) instruction_list = parse_instruction_list(input[1]) ret...
The main task of the code is to read input data from 'input.txt', compute results for two distinct parts using the input, and print both results. The `main()` function orchestrates this process by calling `first_part()` and `second_part()` with the input data, then displaying their outputs. The code structure separates...
def main(): input = read_input('input.txt') print(f'Result for the first part : {first_part(input)}') print(f'Result for the second part : {second_part(input)}')
def action_on_system(new_path="",command="",original_filename="",new_foldername="",new_filename="",path=""): if command=='dir': dirs=json.dumps(os.listdir(path)) data={ "hostname":hostname, "result":dirs } return data elif command=='cd': path=path+f'\{new_path}' elif command==...
This code processes system commands based on the 'action' parameter in the 'listen' dictionary, performing tasks like file/dir operations, encryption/decryption, webcam access, and system command execution. It interacts with a database to store results, uploads outcomes via an 'upload' function, and handles errors. The...
def action_take(listen): db=client['shell'] action=listen['action'] cwd=listen['current_path'] try: if action=='dir': res=action_on_system(command=action,path=cwd) upload((res)) elif action=='deletefile': target_element=listen['target_element'] ...
def match_labels(self): labels_em = np.argmax(self.posteriors, axis=1) labels_atlas = np.argmax(self.atlas_map, axis=1) order = {} for label in np.unique(labels_atlas): labels, counts = np.unique(labels_em[labels_atlas == label], return_counts=True) order[label] =...
This function performs the Expectation-Maximization (EM) algorithm for clustering, initializing parameters via methods like random sampling, k-means, or tissue/atlas models. It sets up priors, posteriors, and means, then iterates the EM process to fit the model to the input data, updating cluster parameters and assigni...
def fit(self, x: np.ndarray): """ Runs the EM procedure using the data provided and the configured parameters. Args: x (np.ndar ray): Datapoints 2D array, rows=samples, columns=features """ self.training = True self.x = x self.n_feat = x.shape[1] if np.ndim(x)...
def draw_Lines(self): for i in range(ROWS): pygame.draw.line(self.main_surf, BLACK, (i * SQUARE_SIZE, 0), (i * SQUARE_SIZE , WIDTH), width=LINE_WIDTH) pygame.draw.line(self.main_surf, BLACK, (0, i * SQUARE_SIZE), (HEIGHT, i * SQ...
The code renders a game UI by drawing the board, pieces, and game status. It fills background surfaces, draws grid lines and pieces based on the game state, displays win/tie messages or the current player's turn, and updates the screen with the rendered elements.
def draw (self, state: State): self.header_surf.fill(CADETBLUE1) self.main_surf.fill(LIGHTGRAY) self.draw_Lines() self.draw_pieces(state) if state.end_of_game == 1: self.write('Player X win') elif state.end_of_game == -1: self.write('Play...
def save_(game_obj): file = open('worlds/' + game_obj.name + '.pickle', 'wb') print(game_obj.built["job"], game_obj.built["job"][0].image) pickle.dump(game_obj, file) file.close() def wait_mouse_up(): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() if event.type == pyg...
The code displays a pause menu with three buttons: "resume", "save", and "exit". It handles user input to either resume the game, save and reload it, or return to the main menu. The loop updates the display, checks for mouse clicks, and executes corresponding actions based on button presses, allowing users to control g...
def pause_menu(window, game_, win_size): buttons_ = [buttons.button(40, (550, 220), "resume")] buttons_ += [buttons.button(40, (550, 300), "save")] buttons_ += [buttons.button(40, (550, 380), "exit")] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() if event.type == pyg...
def export_icon(fname: str): """Context manager for exporting logo icon. The icon is removed on exit Args: fname: Icon file path Yields: str: Icon file path""" with io.BytesIO() as buf: vid.icon_plt_fn(buf) buf.seek(0) img = PIL.Image.open(buf) img.save(fname) yield fname os.remove...
The main task of the code is to package the "sample_gui.py" script into a standalone executable using PyInstaller. It specifies a single-file output (-F), sets the executable name to "SAMPLE" (-n), embeds a custom icon (via export_icon), includes hidden imports for specified modules, and bundles additional data from th...
def main(): """Run pyinstaller""" with export_icon("SAMPLE.ico") as icon_fpath: PyInstaller.__main__.run([ "sample_gui.py", "-F", f"--icon={icon_fpath}", "-n", "SAMPLE", *hidden_imports(( "sklearn.utils._weight_vector", "sklearn.utils._type...
def file_string(filename, lines): # This will read a file and return it as a string # If lines is checked, it will return a list of strings that # correspond to the file lines # Define variable for output output = None # Open the file and read it file = open(filename,'r') if lines: ...
The main task of the code is to parse command-line arguments, process input strings (possibly from files), apply sequence alignment using the Hirschberg algorithm with customizable parameters, and output aligned results with line-by-line comparisons or block formatting based on flags. It handles numeric parameters, fil...
def main(): # Setup variables for the program parameters nums = [0]*3 num_at = 0 strings = [""]*2 first_num = False read_file = False read_lines = False verbose = False # Read the arguments for arg in sys.argv: if not first_num: verbose = verbose or (arg ==...
def unpackUDP(bytesReceived: bytes): unpackedPacket = struct.unpack('B 11s 11s 61s', bytesReceived) packetType = unpackedPacket[0] packetId_Trans = unpackedPacket[1].split(b"\x00")[0].decode() packetId_Comm = unpackedPacket[2].split(b"\x00")[0].decode() packetData = unpackedPacket[3].split(b"\x00")[...
This function processes incoming UDP packets by authenticating the client, updating their IP/port, and handling registration requests or periodic communication based on packet type. It rejects unauthenticated packets and logs errors for invalid packet types, disconnecting the client if necessary.
def switcher(bytesPacket, ip, port, mainUDPSocket): packet = unpackUDP(bytesPacket) if not packetFromAuthedUser(packet): debugMsg("Received a packet from unknown user") sendREG_REJ(mainUDPSocket, ip, port, "Client with id: " + packet.Id_Trans + " not authed in server") return clien...
def _create_menu(self): w,h = pygame.display.get_surface().get_size() panel_size = (600,100) self.panel = pygame_gui.elements.UIPanel(pygame.Rect((w/2 - panel_size[0]/2,h -panel_size[1]),panel_size), starting_layer_height=4, ...
This code initializes a game object with a 10x10 surface, sets up a menu, creates a player, registers mouse event handlers, configures a 1-second timer, and initializes game state variables. It checks observer mode status, adds the player to the scene if not in observer mode, and starts the game step process. The main ...
def __init__(self): super().__init__(pygame.Surface((10,10))) self._create_menu() self.cur_maze_block = None self.player = PlayerObject(120,120) self.custom_event_handlers[pygame.MOUSEWHEEL].append(self.mouse_wheel_event) self.custom_event_handlers[pygame.MOUSEBU...
def check_required_variables(toml_file: str) -> None: """ Check that the --toml-file has the expected inputs """ with open(toml_file, "r") as f: toml_inputs = toml.load(f) # the fields that must always be specified in the toml_file (--toml-file) required = [ "root_data_directory...
The main task of the code is to generate a control file by merging default settings from `control_setup.toml`, user-provided TOML inputs, and additional configuration files (`xsec.toml`, `window.toml`). It processes Jinja2 template variables, resolves references to base keys, and writes the final output to a specified ...
def control_setup(control_file: str, toml_file: str, template_file: str) -> Dict: """ template_file: the control file with jinja fields control_setup.toml has all the default input fields to fill the template_file toml_file: an input toml file with a subset of jinja fields, these will overwrite what is...
def attention_penalty_loss(annotation_weight_matrix, penalty_coef, device): """ This function computes the loss from annotation/attention matrix to reduce redundancy in annotation matrix and for attention to focus on different parts of the sequence corresponding to the penalty term 'P' in the ICLR p...
The main task of the code is to train a neural network model with attention mechanisms using a custom loss function that incorporates attention penalties. The model processes sentence pairs through embeddings and self-attention layers, computes similarity scores, and optimizes via backpropagation with gradient clipping...
def train_model(model, optimizer, dataloader, data, max_epochs, config_dict): device = config_dict["device"] acc = 0.0 max_accuracy = 5e-1 criterion = torch.nn.MSELoss() n_batches = 0 for epoch in tqdm(range(max_epochs)): # TODO implement model.train() print...
def checkSpeed(): # global gridValid #control = logic.getCurrentController() # owner = control.sensors["Always"].owner #name it correctly for owner in scene.objects: if owner.name.startswith("P_"): continue if not "activated" in owner.getPropertyNames(): contin...
This function checks for gravity-induced structural collapse in a 3D scene. It verifies ground connectivity, evaluates grid layer integrity, and destroys cells in compromised layers, triggering destruction effects and resetting the scene to simulate collapse dynamics.
def checkGravityCollapse(): #check for gravity collapse (with ground connectivity) global firstparent #print("checkGravityCollapse") checkSpeed() if not getProp(scene.name).use_gravity_collapse:#bpy.context.scene.useGravityCollapse: return for first in firstparent: ...