dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def check_all_constraints(csp) : """Return False if the problem's assigned values violate some constraint, otherwise True""" if not csp.constraints or not csp.assignments: return True for constraint in csp.constraints: a = csp.get_assignment(constraint.var1) b = csp.get_assignmen...
This code solves a constraint satisfaction problem (CSP) using depth-first search with forward checking and domain propagation. It explores assignments by iteratively selecting unassigned variables, applying domain reductions, and checking constraints. If a valid assignment is found (all constraints satisfied and no em...
def solve_constraint_propagate_reduced_domains(problem) : """ Solves the problem using depth-first search with forward checking and propagation through all reduced domains. Same return type as solve_constraint_dfs. """ csp_stack = [problem] ext = 0 while csp_stack: cur_prob = c...
def check_all_constraints(csp) : """Return False if the problem's assigned values violate some constraint, otherwise True""" if not csp.constraints or not csp.assignments: return True for constraint in csp.constraints: a = csp.get_assignment(constraint.var1) b = csp.get_assignmen...
This function solves a constraint satisfaction problem (CSP) using backtracking with optional propagation. It explores assignments recursively, checking constraints and domains. If enqueue_condition is provided, propagation is applied to new assignments. Returns solution assignments and extension count if solved, else ...
def solve_constraint_generic(problem, enqueue_condition=None) : """ Solves the problem, calling propagate with the specified enqueue condition (a function). If enqueue_condition is None, uses DFS only. Same return type as solve_constraint_dfs. """ csp_stack = [problem] ext = 0 while csp_...
def get_active_config(self): with open(self.config_path) as f: configs = json.load(f) active_config_ls = list(filter(lambda config: config['active'] == True, configs)) if len(active_config_ls) == 0: self.set_active_config('default') return self.get_active_conf...
The code initializes by locating a configuration file, checks for an active configuration, defaults to 'default' if none is found, applies the configuration settings, and outputs the active configuration name.
def __init__(self): self.config_path = PurePath.joinpath(Path(__file__).parent, '.bloggen/config.json') self.active_config = self.get_active_config() if not self.active_config: print("No config selected. Using default.") print("Create a new configuration with --config opt...
def check_for_item(location, player, collected_items, all_stats): if location in list(ITEMS_MEANING.keys()): item = ITEMS_MEANING[location] if item not in HEALTH_ITEMS: if item in collected_items: collected_items[item] += 1 else: collected_item...
The function checks for collisions at the player's current position on the board, handling item collection, entity interactions, board transitions (if the player steps on a wall or special tile), and initiating a boss battle if on board 3, then returns the updated board and current board index.
def check_for_collision( board, player, collected_items, boards, current_board, all_stats ): check_for_item(board[player["x"]][player["y"]], player, collected_items, all_stats) check_for_entity(board[player["x"]][player["y"]],player,all_stats) if board[player["x"]][player["y"]] in ["\u2588", "\u2591"]: ...
def isEmpty(self): return self.stack_list == [] def clean(self): self.stack_list.clear() def push(self, item): self.stack_list.append(item) def peek(self): if not self.isEmpty(): return self.stack_list[len(self.stack_list) - 1] else: return None def pop(se...
The code checks if a string of brackets is balanced by using a stack. It pushes opening brackets onto the stack and matches closing brackets with the top of the stack. If mismatches occur or the stack isn't empty at the end, it returns 'unbalanced'; otherwise, 'balanced'.
def is_balanced(self, sample: str): sample_list = list(sample) if not self.isEmpty(): self.clean() if len(self.stack_list) % 2 != 0: return 'unbalanced' for item in sample_list: if item in self.balanced_dic.keys(): self.push(item) ...
def check_for_game_over(self): if self.game_is_lost() or self.game_is_won(): return True return False def determine_chosen_square(self, mouse_x, mouse_y): '''Method to determine the indices of the clicked square''' chosen_x = 0 chosen_y = 0 for i in range(self...
This method updates the game board by drawing all squares, checks for game over conditions, and processes user input to reveal or flag a selected square based on mouse coordinates, resetting the selection flag afterward.
def update(self, mouse_x, mouse_y): '''Method to update the board''' self.board.draw() for row in self.board.board_representation: for sqr in row: sqr.draw() self.game_over = self.check_for_game_over() if not self.game_over and self.new_sqr_chosen: ...
def get_validated_input(prompt, valid_options): """ Get input from the user and validate it against a set of valid options. Args: prompt (str): The prompt to display to the user. valid_options (list): A list of valid input operations. Returns: str: The validated user input. """ use...
The main task of the code is to display a main menu with options for user login, registration, or exiting the system. It validates user input (1-3) and routes to corresponding functions: `login()`, `register_new_user()`, or exits with a farewell message. The `Bank` object is used to perform banking-related operations b...
def main_menu(bank): """ Display the main menu options and handle user selection. Args: bank (Bank): The Bank object to perform operations. """ user_input = get_validated_input("""\nPlease select from one of the following options: 1 - Login 2 - Register 3 - Exit : """, ['1', '2', '3']) ...
def get_relevant_data(self): data1, data2 = self.get_data_from_file() to_go = len(data1) for word, url in data1.items(): print(f"{to_go} left") to_go-=1 if [word] in data2: self.data[word] = url def alphabatical_threading_data(self): ...
The code's main task is to retrieve relevant data, process it using alphabetical threading, and save the resulting data as a JSON file at the specified path.
def process(self): self.get_relevant_data() self.alphabatical_threading_data() self.save_json_file(self.save_data_path)
def setup_qr_generation_cli(): parser = argparse.ArgumentParser(description='Generate QR codes from JSON data.') parser.add_argument('-i', '--input', required=True, help='Input JSON file path') parser.add_argument('-o', '--output', default='qr_codes', help='Output directory for QR codes') parser.add_arg...
The main task of the code is to generate QR codes from JSON input data using command-line arguments. It loads JSON data, determines QR version and compression settings based on flags, and creates QR codes which are saved to a specified output directory. The process confirms successful generation with a printed message.
def main_generate(): args = setup_qr_generation_cli() json_data = load_json_file(args.input) qr_version = args.qr_version compress = not args.no_compress # Determine whether to compress based on the --no-compress flag generate_qr_codes_from_json(json_data, args.output, qr_version, compress) pri...
def score_tree(tree_json, label, data): classes = df[label].unique() h = predict_tree(tree_json, label, data) report = classification_report(data[label], h, output_dict=True) report['weighted avg']['accuracy'] = report['accuracy'] report['macro avg']['accuracy'] = sum([accuracy_score(data[label] == ...
The function performs post-pruning on a decision tree by recursively evaluating whether replacing subtrees with a single-class prediction (based on majority class in validation data) improves the F1 score. It compares the original tree's performance against the pruned version, retaining the simpler structure if it achi...
def post_pruning(tree_json, label, valid_df): if type(tree_json) == dict or len(valid_df) == 0: return tree_json tree_json = deepcopy(tree_json) base_score = score_tree(tree_json, label, valid_df)['micro avg']['f1-score'] pruned_subtree = {f'{label}': valid_df...
def make_decision_tree(data: pd.DataFrame, label='label', classes=None, return_prob=True, purity_function=gini_index, min_sample_split=0, max_depth=np.inf): available_features = ...
The main task of the code is to evaluate a decision tree model's performance using cross-validation. It runs multiple training-validation splits, builds decision trees with specified parameters, optionally applies post-pruning, and computes average precision, recall, F1-score, and accuracy for both training and validat...
def evaluate_model(data, purity_function=gini_index, min_sample_split=0, max_depth=np.inf, num_runs=10, postpruning=False): classes = data['target'].unique() total_report = {'macro avg': {'precision': {'train': 0, 'va...
def purity_function_experiment(self): report_gini = evaluate_model(self.train_df, purity_function=gini_index) report_entropy = evaluate_model(self.train_df, purity_function=entropy) print(report_gini) print(report_entropy) print('----------------------------------') pl...
The code conducts experiments to optimize decision tree parameters (purity function, max depth, min samples split) and evaluates pruning effectiveness. It trains a tree with selected parameters, optionally prunes it using validation data, and assesses performance on test data, comparing results with a sklearn baseline.
def run_experiments(self): purity_function = self.purity_function_experiment() max_depth = self.max_depth_experiment(purity_function) min_sample_split = self.min_samples_split_experiment(purity_function, max_depth) postpruning = self.post_pruning_experiment(purity_function, max_depth, mi...
def parse_node(node): from config_utils.config_utils import wrap_parser, base_parser, sweep_parser, make_config_parser node_keys = node.keys() # if '_wrap_' in node => infinite loop # parse _base_ recursively node = make_config_parser([base_parser("_base_")])(node) # if '_base_' in node_keys: ...
The function `instantiate_node` converts OmegaConf configuration nodes into Python objects, handling recursive instantiation, conversion modes, and special keys like `_target_` and `_out_`. It processes lists and dicts, resolving interpolations, applying caching, and validating boolean flags. The main task is to dynami...
def instantiate_node( node: Any, *args: Any, convert: Union[str, ConvertMode] = ConvertMode.NONE, recursive: bool = True, partial: bool = False, ) -> Any: # Return None if config is None if node is None or (OmegaConf.is_config(node) and node._is_none()): return None if not Omega...
def _prepare_input_dict_or_list(d: Union[Dict[Any, Any], List[Any]]) -> Any: res: Any if isinstance(d, dict): res = {} for k, v in d.items(): if k == "_target_": v = _convert_target_to_string(d["_target_"]) elif isinstance(v, (dict, list)): ...
The main task of the code is to instantiate an object or execute a callable based on a configuration dictionary. It processes the config, which specifies a target class/function and parameters, handling nested objects, conversion strategies, and recursion. The function merges config with provided kwargs, prepares input...
def instantiate(config: Any, *args: Any, **kwargs: Any) -> Any: """ :param config: An config object describing what to call and what params to use. In addition to the parameters, the config must contain: _target_ : target class or callable name (str) And ...
def flatten_parsers(rule, stack, curr_combinator): if curr_combinator: return COMBINATOR_MAP[curr_combinator](*stack) elif len(stack) == 1: return stack[0] else: raise AssertionError('TODO') def make_parser_from_terminal(rule, terminal, _cache={}): # this is the only time I can c...
(dispatch) processes tokens to construct a parser based on grammar rules. It iterates through tokens, appending terminal parsers to a stack or recursively handling EBNF symbols via combinator/group mappings. It manages nested structures by resolving groups, applying combinators, and flattening parsers when sub-rules ma...
def dispatch(parser_table, rule, token_itr, sub_rule=None, comb_map=COMBINATOR_MAP, group_map=GROUP_MAP, group_comp=GROUP_COMPANIONS): stack = [] curr_combinator = None while True: try: got = next(token_itr) except StopIteration: return flatt...
def heston_put(S, K, tau, v, vbar, lambd, eta, rho, r=0, divYield=0): dampFac = 3 k = np.log(K / S) - r * tau + divYield * tau integral = heston_phi_put(k, tau, v, vbar, lambd, eta, rho, dampFac) return np.exp(-divYield * tau) * S * np.exp(dampFac * k) * integral / np.pi def heston_call(S, K, tau, v, vbar, lamb...
This function constructs an observation matrix for each asset, incorporating correlations, market data (basket return, time remaining, spot/forward prices), strike prices, and implied volatilities derived from Heston model pricing. It aggregates these into a structured state vector for reinforcement learning environmen...
def _next_observation(self): # matrix of size (n, ) where is n is the number of assets # row i corresponds to asset i # columns 0,..,n-1: correlations to other assets # columns n,..,n+3: basketReturn so far, number of remaining time step, spot of the asset, forward of asset over next period # column...
def import_data(test_X_file_path): test_X = np.genfromtxt(test_X_file_path, delimiter = ',', dtype = np.float64, skip_header = 1) return test_X def predict_target_values(test_X): train_X = np.genfromtxt("train_X_knn.csv", delimiter = ',', dtype = np.float64, skip_header = 1) train_Y = np.genfromtxt("tra...
The code's main task is to predict target values from a test dataset using a model, then save the predictions to a CSV file named "predicted_test_Y_knn.csv". It loads test data from the provided file path, applies the prediction model, and exports results in a structured format for further analysis or submission.
def predict(test_X_file_path): test_X = import_data(test_X_file_path) pred_Y = predict_target_values(test_X) write_to_csv_file(pred_Y, "predicted_test_Y_knn.csv")
def any_image_on_screen( paths_array: list[str], precision=0.8, screenshot=None, gray_scale=True ) -> Tuple[bool, Optional[Tuple[int, int]], Optional[float], Optional[str]]: best_max_val = None best_max_loc = None best_image = None if screenshot is None: screenshot = pyautogui.screenshot() ...
The function `find_image_and_click` searches for images specified by `filepaths` on the screen, using template matching with configurable precision and grayscale. If a match is found within `retries` attempts, it clicks the detected image's position. If no match is found, it logs an error using the provided `error_file...
def find_image_and_click( filepaths: list[str], msg=None, precision=0.8, screenshot=None, gray_scale=True, retries=RETRIES_TO_LOAD, error_filename=None, ): for _ in range(retries): on_screen, position, _, best_match_filepath = any_image_on_screen( filepaths, precision...
def modifier(self, message: mido.Message) -> Union[mido.Message, List[mido.Message]]: """ Change something about a message before sending it to an output. Override this method in subclasses of MidiBox as desired! """ return message def on_note(self, message: mido.Message): ...
This method processes incoming MIDI messages by applying a modifier, then dispatching events to `on_note` for note-related messages or `on_clock` for clock messages, handling both single messages and lists of modified notes.
def on_message(self, message: mido.Message): """ Accept incoming MIDI `Messages`, and dispatch event handlers. """ if message.type != 'clock': modified = self.modifier(message) if isinstance(modified, list): for note in modified: ...
def make_noise(self, batch_size): if self.zs is None: return make_noise(batch_size, self.G.dim_z).to(self.z_noise.device) else: indices = torch.randint(0, len(self.zs), [batch_size], dtype=torch.long) z = self.zs[indices].to(self.z_noise.device) if self.z_...
This code generates images and references by iteratively sampling and filtering until the desired batch size is achieved. It uses noise vectors (z) to synthesize samples, applies area and maxes count filters to validate outputs, and accumulates valid batches. If retries exceed the limit, it raises an error. The functio...
def forward(self, max_retries=100, z=None, return_steps=False): img, ref = None, None step = 0 while img is None or img.shape[0] < self.p.batch_size: step += 1 if step > max_retries: raise Exception('generator was disable to synthesize mask') ...
def load_GBlock(self, name_pth, name_tf): self.load_convs(name_pth, name_tf) self.load_HyperBNs(name_pth, name_tf) def load_attention(self, name_pth, name_tf): self.load_snconv(name_pth + 'theta', os.path.join(name_tf, 'theta'), bias=False) self.load_snconv(name_pth + 'phi', os.path.joi...
The main task of the code is to load a generator model's components from disk by iterating through predefined blocks, attention layers, linear layers, and normalization modules, mapping each to specific file paths within a directory structure. It systematically loads weights for GBlocks, attention mechanisms, linear tr...
def load_generator(self): GENERATOR_ROOT = os.path.join(self.TF_ROOT, 'Generator') for i in range(self.NUM_GBLOCK[self.resolution]): name_tf = os.path.join(GENERATOR_ROOT, 'GBlock') name_tf += '_{}'.format(i) if i != 0 else '' self.load_GBlock('GBlock.{}.'.format(i),...
def set_optimizer(self) -> None: optimizer = torch.optim.Adam( self.model.parameters(), lr=self.config.optim.lr, weight_decay=self.config.optim.weight_decay ) self.warmup = self.config.optim.linear_warmup self.grad_clip_norm = self.config.optim.grad_cl...
The code trains a neural network model using a diffusion process, handling multi-GPU setups with DataParallel. It initializes optimizers, data generators, and logs metrics via WandB. The training loop computes losses, updates parameters, and periodically validates, snapshots, and checkpoints the model. It employs Expon...
def train( self, project_name: str = 'upsampling_sde', experiment_name: str = 'ho-improved' ) -> None: if torch.cuda.device_count() > 1: self.model = torch.nn.DataParallel(self.model) self.set_optimizer() self.set_data_generator() t...
def marginal_std(self, t: torch.LongTensor) -> torch.Tensor: return _extract_tensor_with_time(self.sqrt_1m_alphas_cumprod, t) def _extract_tensor_with_time(arr_t, t: torch.LongTensor): vals = arr_t[t] vals = vals[:, None, None, None].to(t.device) return vals def calc_score(self, model, x_t, t: torch...
The function predicts the initial state $ x_0 $ from a noisy input $ x_t $ at time step $ t $ using a diffusion model. It computes the noise estimate $ \epsilon_\theta $ if not provided, then reverses the diffusion process by scaling and shifting $ x_t $ with precomputed coefficients and standard deviations to reconstr...
def predict_x0(self, x_t, t: torch.LongTensor, eps_theta=None, model=None): std = self.marginal_std(t) coef = _extract_tensor_with_time(self.sqrt_alphas_cumprod, t) if eps_theta is None: eps_theta = self.calc_score(model, x_t, t)['eps_theta'] x_0 = (x_t - eps_theta * std) / c...
def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def train(args, train_dataset, model, tokenizer, dev_set=None, eval_set=None): if args.is_text_embed: init_from_bert_embeddings(a...
The main task of the code is to train and evaluate a pre-trained transformer-based model (e.g., BERT) for text classification on datasets like Yelp or IMDb. It supports cross-context training, custom user/product embeddings, and hyperparameter tuning. The code parses arguments, loads data, initializes the model, trains...
def main(): parser = argparse.ArgumentParser() parser.add_argument("--task_name", type=str, default="yelp-2013", help="the name of the training task (the dataset name)") parser.add_argument("--model_size", type=str, default="base", help="the size of pre-train...
def _PromptThenMaybeExecute(self, items=[], summary='', per_item_desc=lambda item: item, per_item_executor=lambda item: None): results = [] if items: print(summary) diff_action = s...
The function merges two list collections (api_lists and config_lists) by identifying and creating missing lists, deleting unnecessary ones, and updating members of existing lists. It uses set operations to determine additions/removals, prompts for confirmation, and merges members where configurations match. The result ...
def _MergeLists(self, api_lists, config_lists): # Step 1: Compute list sets. api_set = {l.name for l in api_lists} config_set = {l.name for l in config_lists} canonical_lists = {l.name:l for l in api_lists} # Step 2: Create missing lists. lists_to_add = config_set.difference(api_set) self._P...
def _MergeFollows(self, api_follows, config_follows): # Step 1: Compute follow sets. api_set = {follow.username for follow in api_follows} config_set = {follow.username for follow in config_follows} canonical_follows = {follow.username:follow for follow in api_follows} # Step 2: Add missing follows....
This code merges follows and lists from two TwitterAccount instances (api_account and config_account) using helper methods, then constructs a new TwitterAccount with the merged data and config_account's meta_lists.
def MergeAccounts(self, api_account, config_account): canonical_follows = self._MergeFollows(api_account.follows, config_account.follows) canonical_lists = self._MergeLists(api_account.lists, config_account.lists) self._MergeM...
def measure_values_analog(self): self.data_unreliable = collections.OrderedDict() for key in self.data: if self.data[key]['sensor_type'] in ['ADC_diods', 'SPI0', 'SPI1', 'ADC_resistor']: self.data[key]['value'], self.data[key]['status'], self.data_unreliable[key] = self.read_...
The main task of the code is to initialize the main loop by reading initial sensor data based on configured sensor types, starting corresponding measurement threads (e.g., analog sensors, maxigauges, ion pumps), waiting for these threads to complete their initial measurements, and then launching the main loop to contin...
def main_loop_init(self): # if loop runs for the first time print('Reading initial sensor data.') if ('ADC_diods' in self.sensor_types) or ('ADC_resistor' in self.sensor_types) or ('temp_chip' in self.sensor_types): self.measure_values_analog() if 'maxigauges' in self.sensor_...
def select_atoms(self, selection, model_idx=0): """Function to select a set of atoms, given the selection criteria.""" # TODO: make selection language the same as VMD and convert to gemmi's language? sel = gemmi.Selection(selection) ref_atoms = [] for i, model in enumerate(sel.mo...
This function calculates the center of mass (COM) and the normal vector of the plane containing an aromatic residue's ring. It identifies ring atoms based on residue type (TYR, PHE, HIS, TRP), selects their coordinates, computes the plane's normal using these points, and returns the COM and normal vector. The TRP ring ...
def get_aromatic_ring_center_and_normal(self, aromatic_residue, model_idx=0, trp_ring=0): """ Given an aromatic residue, find its aromatic ring center(s) and the normal to the plane containing the ring(s). Input: aromatic_residue = (str: resname, str: chain, int: seqid) Output: ...
def get_nearby_aromatic(self, ref_atom, max_dist=7, model_idx=0, tol=0.01): """ Given a reference atom, find nearby aromatic rings that belong to Y, F, W, or H. """ atom_list = self.find_neighboring_atoms(ref_atom, max_dist=max_dist, model_idx=model_idx, tol=tol) aromatic...
This function identifies aromatic residues near each metal site in a molecular structure. It calculates the distance (d0) and angle (theta0) between aromatic ring centers and metal atoms, filtering those within specified thresholds (max_d0, max_theta0). For each valid aromatic residue, it stores the residue, d0, and th...
def find_aromatics_near_metal_sites(self, cutoff=7, max_d0=5.5, max_theta0=55, model_idx=0, tol=0.01): """ After finding metal sites, find aromatic residues around them. """ if len(self.metal_site...
def buildSettlement(catanBoard,player,isStartTurns): nodes = catanBoard.getNodes() currentRoads = catanBoard.getRoads() validNodes = [] for i in nodes: invalidNode = False if (i.getStatus() == None) and ((i.canBuild(currentRoads,player) == True) or (isStartTurns == True)): ...
The function enables players to take turns building settlements and roads on a Catan board, collecting resources from adjacent non-desert tiles during the first four iterations, then continuing the turn sequence without resource collection. It alternates player order (backwards then forwards) over eight iterations, upd...
def startTurns(catanBoard,players,playerTurn,resources): #going backwards through players #build one settlement and one road (road has to connect to settlement) #collect resources based off where the settlement is #go forwards through players, repeat but do not collect resources this time for i in ...
def createPlayerButtons(players,playerTurn): x = 250 y = 90 playerButtons = [] for player in players: if (player != players[playerTurn]) and (player.getResources() != []): buttonA = PlayerButton(player.getColour(),x,y,50,50,player) buttonA.setText(str(player.ID+1)) ...
This function handles the effects of using specific development cards in a Catan-like game. It processes player actions for stealing resources (knight), building roads (road building), selecting resources (year of plenty), and collecting resources via monopoly. The code updates game state, manages UI interactions, and ...
def useDevelopmentCard(players,playerTurn,card,catanBoard,resources): msg = "" player = players[playerTurn] if card == "knight": playersToStealFromButtons = createPlayerButtons(players,playerTurn) if playersToStealFromButtons == []: msg = "No players to steal from" else: ...
def createPlayerButtons(players,playerTurn): x = 250 y = 90 playerButtons = [] for player in players: if (player != players[playerTurn]) and (player.getResources() != []): buttonA = PlayerButton(player.getColour(),x,y,50,50,player) buttonA.setText(str(player.ID+1)) ...
The code facilitates resource trading between players or the bank in a game. It creates buttons for selecting trade partners, adjusting resource quantities, and validating trades. When the player presses Enter, it checks if the trade meets rules (e.g., 4:1 with the bank) and updates resources if valid. Error messages a...
def trade(players,playerTurn): #4 options below: other 3 players, "bank" as buttons, outline edge of chosen option #counter for each resource #if bank chosen, only 4 of 1 resource can be traded tradeButtons = createPlayerButtons(players,playerTurn) buttonA = PlayerButton(GREY,550,90,50,50,"BANK...
def yt_get_content(link): transcript = yt_get_transcript(link) title, description, uploader = yt_get_video_info(link) return { "youtube_video_details": { "title": title, "description": description, "uploader": uploader, "transcript": transcript, ...
This function fetches content from a given URL, handling redirects and validating URLs. It distinguishes between YouTube links, images, PDFs, and text content. For images/PDFs, it returns specialized content handlers; for text, it extracts text. Invalid/local URLs trigger exceptions. The function returns processed cont...
def request_link_content(link): if yt_is_valid_url(link): return yt_get_content(link), [] with httpx.Client() as client: # By doing the redirect itself, we might already allow a local request? with client.stream("GET", link, timeout=4, follow_redirects=True) as response: res...
def should_ignore_post(post): sender_id = post["user_id"] # Ignore own posts if sender_id == driver.client.userid: return True if sender_id in mattermost_ignore_sender_id: logger.debug("Ignoring post from an ignored sender ID") return True if post.get("props", {}).get("fro...
The main task of the code is to process incoming chat messages by parsing event data, determining if the chatbot should respond, extracting message context (including threads), handling content like links/files, constructing formatted messages, and triggering AI generation for responses. It manages typing indicators, v...
def process_message(event_data): post = json.loads(event_data["data"]["post"]) if should_ignore_post(post): return current_message, channel_id, sender_name, root_id, post_id, channel_display_name = extract_post_data( post, event_data ) stop_typing_event = None typing_indicator_...
def nl_parameter(self,section,name,default=''): n=self.nml if section in n.keys(): if name in n[section].keys(): return n[section][name] return default def log_line(self,line,t_format='short'): self.line_to_file(line,open(self.log_file,'a'),t_format) def final...
This code initializes a Quasi-Geostrophic (QG) model by configuring parameters, grid, and data structures based on a specified mode (e.g., 'rossby', 'two_layer', 'exponential'). It sets up logging, physical constants (e.g., Coriolis parameter f0, beta), grid dimensions, and initial vorticity fields. The mode determines...
def initialize(self): self.mode = self.nl_parameter('Main','mode','rossby').lower() md=self.mode self.log_file = self.nl_parameter('Main','log_name','{}.log'.format(md)).lower() print('LOGGING TO FILE: {}'.format(self.log_file) ) self.iter_file = self.nl_parameter('Main','log_...
def rotate_img(self) -> Tuple[Image, float, Tuple[float, float]]: med_slope = self.calc_med_slope() rotation_angle = - med_slope * 60 image_center = tuple(np.array(self.color_img.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, rotation_angle, 1.0) rotated = cv2...
This function processes an image of a musical instrument by flipping, rotating, cropping, detecting frets and strings, and saving intermediate images at each step for analysis or visualization.
def init_with_saving_imgs(self): self.step = 1 self.color_img = cv2.flip(src=self.color_img, flipCode=1) self.save_img(step=f"{self.step}_initial_img", i=self.i) self.step += 1 self.rotated, self.rotation_angle, self.image_center = self.rotate_img() self.rotated.save_img(...
def init_with_saving_imgs(self): self.step = 1 self.color_img = cv2.flip(src=self.color_img, flipCode=1) self.save_img(step=f"{self.step}_initial_img", i=self.i) self.step += 1 self.rotated, self.rotation_angle, self.image_center = self.rotate_img() self.rotated.save_img(...
This code initializes an image processing class for analyzing a musical instrument's neck. It flips, rotates, and crops the image, then detects frets and strings using Hough lines. If save_img is True, it saves images; otherwise, it processes the image for feature extraction, including calculating fret positions and st...
def __init__(self, save_img=False, **kwargs) -> None: # , file_name:str=""): Image.__init__(self, **kwargs) # , file_name=file_name) if save_img: self.init_with_saving_imgs() else: self.color_img = cv2.flip(src=self.color_img, flipCode=1) self.rotated, self....
def wait_for_element_visibility(self, *args): return self.driver_wait().until(EC.visibility_of_element_located(*args)) def find_and_fill_input(self, field: str, input_value: str): input_field = self.wait_for_element_and_click((By.XPATH, f"//input[@placeholder='{field}']")) input_field.send_keys(...
The code automates a user login process by navigating to a URL, locating and clicking a sign-in button, filling username and password fields, logging the action, and handling a "Not Now" popup. It uses Selenium for browser automation, waits for elements to load, and interacts with web forms to simulate user authenticat...
def sign_in(self): self.driver.get(self.url) sign_in_button = self.wait_for_element_visibility((By.CSS_SELECTOR, 'button.btn.btn-primary')) self.find_and_fill_input('Username', self.login) self.find_and_fill_input('Password', self.password) sign_in_button.click() logging....
def test_ex2(): # Build outputs for specific tests triangle_up_side_down_expected_output = [] for i in range(5, 0, -1): triangle_up_side_down_expected_output.append('*' * i) triangle_expected_output = [] for i in range(1, 5): triangle_expected_output.append('*' * i) try: ...
The main task of the code is to determine and execute the appropriate test function based on the prefix of `student_file`. It checks for specific prefixes like "EX2.", "EX3.", etc., and runs corresponding tests (e.g., `test_ex2()`). If no match is found, it logs an error indicating the test cannot be determined. The co...
def main(): if "EX2." in student_file: test_ex2() elif "EX3." in student_file: test_ex3() elif "EX4." in student_file: test_ex4() elif "EX51." in student_file: test_ex5(1) elif "EX52." in student_file: test_ex5(2) elif "EX5" in student_file: test_e...
def get_binance(): r = requests.get(config.BINANCE_URL) data = json.loads(r.text) with open(config.PRICE_FILE, 'w') as outfile: json.dump(data, outfile) def telegram_id(): r = requests.get(f'https://api.telegram.org/bot{config.TOKEN}/getUpdates') data = json.loads(r.text) global chat_id chat_id = data['result'...
The main task of the code is to continuously monitor and update Binance data, Telegram IDs, and cryptocurrency prices using a loop that reloads configuration settings every `config.UPDATE_FREQ` minutes. It repeatedly executes `get_binance()`, `telegram_id()`, and `get_price()` functions to fetch real-time data, ensurin...
def main(): while True: importlib.reload(config) get_binance() telegram_id() get_price() time.sleep(config.UPDATE_FREQ*60)
def handle_vdisks(): result = get_command_result('/usr/local/nutanix/bin/vdisk_config_printer') vdisk_list = ops.get_vdisk_list(result) json_string = json.dumps(vdisk_list, indent=2) print_debug(json_string) if not DEBUG: requests.put(TREE_URL + 'vdisks/', json_string) def handle_stats(): result = get_c...
The main task of the code is to repeatedly execute functions handling virtual disks, statistics, VMs, and other resources (handle_vdisks, handle_stats, handle_vms, handle_pds, request_building_tree) in a loop with error handling. It pauses for a configurable interval (INTERVAL seconds) between cycles, printing progress...
def main(): while(True): try: handle_vdisks() handle_stats() handle_vms() handle_pds() request_building_tree() except Exception as e: print(traceback.format_exc()) count = INTERVAL while(count > 1): if count % 10 == 0: print(f'wait {count} secs') ...
def play_game(board): global total_score print() print('Game Begins!!!') empty_board(board) draw_board(board) turn = chooseFirstTurn() for i in range(9): if turn == 'Computer': fillPosition(board, 'O', computer_choice(board)) draw_board(board) if w...
The function `dashBoard` handles user choices in a Tic-Tac-Toe game interface. It routes actions based on the `choice` parameter: '1' starts the game, '2' saves the score, '3' displays the leaderboard, and 'q' exits with a thank-you message. It serves as a control hub for game operations, ensuring user interactions tri...
def dashBoard(board, choice): if choice == '1': play_game(board) elif choice == '2': save_score(total_score) elif choice == '3': leader_board = load_scores() display_leaderboard(leader_board) elif choice == 'q': print('---------------------------------------') ...
def send(self,packet): """ Store the last packet to resend on certain errors """ self.lastPacket = packet self.server.send(packet) def clearText(self): self.textBox.configure(state='normal') self.textBox.delete(1.0,END) for i in range(25): ...
This code assigns a user to a specified room by updating the room state, notifying the user of their entry, requesting a list of users in the room, updating the UI, and returning a confirmation event with no error status.
def assignRoom(self, room): error = False self.room = room event = f'<SERVER> you joined room \"{self.room}\"' packet = encodePacket(OPCODES["OPCODE_LIST_USERS"],room) self.send(packet) self.clearText() self.buildRoomFrame() return event, error
def resend(self): """ Resend most recent packet """ self.printEvent("<CLIENT> Resent packet",True) self.server.send(self.lastPacket) def sendName(self): packet = encodePacket(OPCODES["OPCODE_HELLO"], self.username) self.send(packet) def updateRooms(self, roomStr):...
This function processes incoming server messages based on their opcode. It handles errors, updates room/user lists, assigns rooms, and triggers client actions like sending names or clearing data. It generates event messages for user feedback and manages state changes, with some opcodes requiring future implementation.
def processMessage(self, message): """ message - (OPCODE, LENGTH, PAYLOAD) """ opCode, length, payload = message error = False event = "<SERVER> " # Server sent error message if opCode == OPCODES["OPCODE_ERR"]: event += "Last packet r...
def start_play(self): self.first_draw() for player_id in self.players: self.players[player_id].card_check_complete() if not self.players[player_id].cards_left(): self.draw(self.players[player_id]) def player_status(self, player_id: str) -> dict: data = dic...
The code manages a Quartets game's state transitions, handling player turns, group selection, card exchanges, and game end logic. It initializes the game, processes player actions (choosing groups, targeting players, exchanging cards), updates player statuses, and determines game completion by checking deck emptiness a...
def play(self, **kwargs) -> dict: data = dict() data["result"] = {"error": True, "status": dict()} # if not len(self.drawing_deck): # self.state = Quartets_GameState.FINISHED if self.state == QuartetsGameState.NOT_STARTED: self.start_play() self.idx_...
def huffman_encoding(data): if not data: return None # Character frequency in the form of a tuple (priority_number, data) freq = [(data.count(e), e) for e in sorted(set(data))] root = _build_huffman_tree(freq) codes = {} _get_codes(root, codes) encoded_data = "".join(codes[n] for...
The code tests Huffman encoding/decoding by encoding input text, measuring sizes, decoding it back, and verifying if the decoded text matches the original, ensuring correctness and efficiency of the Huffman implementation.
def test_encoding(text): if not text: print("Warning! provided text is of NoneType. Test aborted!") return print("Original Text:\t\t {}".format(text)) print("Size:\t\t\t {}".format(sys.getsizeof(text))) encoded_data = huffman_encoding(text) print("Huffman Encoding:\t {}".format(e...
def get_label(g, subject): output = g.preferredLabel(subject, lang='en') if not output: return unicode(subject) # TODO: qname? return unicode(output[0][-1]) def slugify(content, prefix=None): _content = content.replace(" ", "-").lower() # TODO if prefix: return u'%s/%s' % (prefix, ...
The main task of the code is to process a list of graph subjects by extracting their labels, generating slugs, and collecting ordered properties. It iterates through each subject, uses `get_label` to retrieve its name, creates a URL-friendly slug with `slugify`, and gathers properties via `iter_subj_pred` using a speci...
def iter_subjects(g, subjects, slug_prefix=None, predicate_ordering=DEFAULT_PREDICATE_ORDERING): for subject in subjects: label = get_label(g, subject) yield (subject, { "label": label, "slug": slugify(label, slug_prefix), "prop...
def read_rdf_files(input_files, graph=None): if graph is None: graph = rdflib.ConjunctiveGraph() graph = rdflib.ConjunctiveGraph() # Graph() for input_file in input_files: with codecs.open(input_file, 'r', encoding='utf-8') as f: graph.parse(f, format=RDF...
The code processes RDF files to generate a structured health reference document. It organizes data into sections like "Drug Groups" and "Therapies," using specific predicates to order information. The processed data is then rendered into an HTML template, combining structured content with highlighted source code for di...
def healthref(input_files, output): """ mainfunc """ g = read_rdf_files(input_files) c = OrderedDict() sections = c['sections'] = OrderedDict() sections['drug-groups'] = { "title": "Drug Groups", "object": TD.DrugGroup, "predicate_ordering": [ # RDF.type, ...
def forward(forwardNum): if forwardNum <= 0: console.append('Improper forward input of ' + str(forwardNum) + '. Please try again.') else: if forwardNum == 1: console.append('Moving forward 1 inch.') forwardBackwardDirection() else: console.append('Movi...
This function handles POST requests from a web form, executing directional movement commands (forward, backward, left, right) based on user input values. It updates the console state, re-renders the index page with updated data, and redirects to login upon exit. Each movement action retrieves an integer from the form, ...
def handleInput(): if request.method == 'POST': if 'forwardSubmit' in request.form: forwardEntry = int(request.form['moveForward']) forward(forwardEntry) return render_template('index.html', console=console, directional=directional) elif 'backwardSubmit' in reques...
def getToFillIndex(puzzle, allowed): toFillPrioritiesAndIndices = [] for i in range(PUZZLE_SIZE): if puzzle[i] == 0: toFillPrioritiesAndIndices.append([ countBits(allowed[i]), countNeighboursVariability(puzzle, allowed, i), i ]) ...
This function recursively solves a puzzle by trying allowed values in prioritized order, updating the puzzle state and constraints, and backtracking if a value leads to a dead end. It sets the global SOLVED_PUZZLE when a complete valid solution is found.
def solvePuzzleRecursive(puzzle, allowed, idx=IDX_NOT_SET, value=0): global SOLVED_PUZZLE if (idx == IDX_NOT_SET): # ''' no index is selected to fill (i.e. initial function call) ''' idx = getToFillIndex(puzzle, allowed) if (value > 0): # ''' set value and update allowed vector ''' puzzl...
def mask(value): return 0 if value == 0 else 1 << (value - 1) def updateAllowed(puzzle, allowed, idx): allowed[idx] = 0 pos = coord(idx) i = pos[0] j = pos[1] safeMask = ~(puzzle[idx]) ''' disallow value for the block ''' block_i = i - i % BLOCK_SIZE block_j = j - j % BLOCK_SIZE ...
The code solves a 1D puzzle by validating input size, initializing puzzle and allowed arrays, applying masks to input values, updating allowed positions based on non-zero values, recursively solving the puzzle, and returning the solution if successful. It checks input validity, processes constraints, and uses recursion...
def solve_1d(puzzle_input): if len(puzzle_input) != PUZZLE_SIZE: raise Exception("Expected input size:" + str(PUZZLE_SIZE) + ". But found:" + str(len(puzzle))) puzzle = [0] * PUZZLE_SIZE allowed = [mask(PUZZLE_LENGTH + 1) - 1] * PUZZLE_SIZE for idx in range(PUZZLE_SIZE): puzzle[idx] = m...
def solve_1d(puzzle_input): if len(puzzle_input) != PUZZLE_SIZE: raise Exception("Expected input size:" + str(PUZZLE_SIZE) + ". But found:" + str(len(puzzle))) puzzle = [0] * PUZZLE_SIZE allowed = [mask(PUZZLE_LENGTH + 1) - 1] * PUZZLE_SIZE for idx in range(PUZZLE_SIZE): puzzle[idx] = m...
The code solves a 2D puzzle by converting it to 1D format, using a 1D solver function, then converting the result back to 2D. If the solver returns a non-success status (first element ≠ 1), it propagates that result. Otherwise, it returns a success status (1) with the 1D solution converted back to 2D format. The core t...
def solve_2d(puzzle_input): result = solve_1d(_2d_to_1d(puzzle_input)) if result[0] != 1: return result else: return [1, _1d_to_2d(result[1])]
def get_mask(self, image): """ Returns mask of image. We use floodfill algorithm that compares 4 neighboring pixels and based on specified threashold fills mask image that is bigger by two pixels in every direction with white color and than we remove left noise by running...
The code extracts a mask from an image to identify the board's area, detects its contour, draws the contour on the original image, crops the board region using the contour, splits the board into segments, and optionally saves processed images. It handles fallback to a saved contour if detection fails and manages debug ...
def find_and_draw_edges(self, image, origin): """ Extract mask of the image. Based on this mask calls function to find main area where board is located in the image. Calls function find_board which returns conture of a board. Draws conture of board Args: imag...
def __get_file_name(self, path): """ Args: path(string): Path to file Returns: string: File name extracted from path """ head, tail = ntpath.split(path) name = tail or ntpath.basename(head) return name.split('.')[0] def write_video_metadat...
The function `write_metadata` extracts metadata from images or videos by determining the file type (video or image) and calling the appropriate method. It generates a default output file name if none is provided and handles errors like unrecognized formats or invalid file paths.
def write_metadata(self, input_file, output_file=None): """ Main function for getting metadata from images or videos. It checks if format of a file is supported and then calls approperiate function Args: input_file(string): Path to file to process output_...
def create_trackbars(self): """ Creates window for displaying trackbars and mask of image """ # create window cv.namedWindow('result') cv.createTrackbar('lo', 'result', self.lo, 255, self.trackbar_callback) cv.createTrackbar('hi', 'result', self.hi, 255, self.trac...
The code processes a video file to analyze frames, detect boards (via `get_board`), and track performance metrics like FPS and average frame processing time. If debug mode is off, it calculates these metrics and displays progress; if on, it creates trackbars for adjustments. The loop reads frames, processes them, and e...
def process_video(self, video): """ Main video search function Args: video(string): Path to video file to process """ if self.debug is False: # avgpf - average time it took to process frames in one second frame_counter, fps, old_frames, timer,...
def create_socket(ip: str, port: int, listen: bool = False) -> Optional[socket.socket]: """Create a TCP/IP socket at the specified port, and do the setup necessary to turn it into a connecting or receiving socket. Do not actually send or receive data here, and do not accept any incoming connect...
The code implements a server loop that handles client connections for registration and secure key exchange protocols. It listens on a specified IP and port, processes client requests (quit, register, generate shared secret), manages a user database, and executes corresponding functions for registration (`server_registe...
def server_loop(IP, port, g, N, k, bits, verbose=False): database = dict() # for tracking registered users sock = create_socket(IP, port, listen=True) if sock is None: if verbose: print(f"Server: Could not create socket, exiting.", flush=True) ...
def safe_prime(bits: int = 512) -> int: """Generate a safe prime that is at least 'bits' bits long. The result should be greater than 1 << (bits-1). PARAMETERS ========== bits: An integer representing the number of bits in the safe prime. Must be greater than 1. RETURNS ======= ...
The function `server_prepare` generates cryptographic parameters for a secure key exchange protocol. It creates a safe prime number $ N $, computes a primitive root $ g $ modulo $ N $, and derives a hash value $ k $ using Blake2b from byte representations of $ g $ and $ N $. These parameters $(g, N, k)$ are returned as...
def server_prepare() -> tuple[int, int, int]: """Do the preparations necessary to accept clients. Generate N and g, and compute k. RETURNS ======= A tuple of the form (g, N, k), containing those values as integers. """ N = safe_prime() g = prim_root(N) N_bytes = int_to_bytes(N, ...
def generate_iv(length: int) -> bytes: """Generate an initialization vector for encryption. Must be drawn from a cryptographically-secure pseudo-random number generator. PARAMETERS ========== length: The length of the IV desired, in bytes. RETURNS ======= A bytes object containing the ...
The function encrypts plaintext with padding using a cipher key, then appends an HMAC of the IV and ciphertext. It generates an IV, pads the plaintext, encrypts it with the cipher, combines IV and ciphertext, computes HMAC over this combined data, and returns the concatenated result as bytes.
def pad_encrypt_then_HMAC( plaintext: bytes, key_cypher: bytes, key_HMAC: bytes, hasher: Hasher, block_ids: Callable[[int], Iterator[bytes]], ) -> bytes: """Encrypt a plaintext with your encryption function. Note the order of operations! PARAMETERS ========== plaintext: The bytes ob...
def get_bus_stops_dataframe(trip_id): df_stop_times_subset = df_stops_times.loc[df_stops_times['trip_id'] == trip_id] df_bus_stops = pd.merge(df_stop_times_subset, df_stops, on='stop_id') df_bus_stops = df_bus_stops.sort_values(by=['stop_sequence']) df_bus_stops = df_bus_stops.reset_index(drop=True) df_bus_stops['...
The function `calibrate(trip_id)` generates a time-synchronized, spatially calibrated trajectory for a bus trip by aligning GPS stop data with a predefined route shape. It retrieves trip details, identifies anchor points on the route, calculates distances between stops, interpolates positions using linear interpolation...
def calibrate(trip_id): try: current_trip = df_trips[(df_trips["trip_id"] == trip_id)] current_trip_list = current_trip.values.tolist() current_shape_id = current_trip_list[0][5] #get the shape_id value for this trip_id o_route_id = current_trip_list[0][0] #original route id o_trip_headsign = current_trip_li...
def partial_fit(self, sample): """ Runs one update of training. """ # Get batch and move data to devic _in, _target = self.__move_sample_to_device(sample) # Apply transforms if self.transforms is not None: _in, _target = self.transforms(_in, _targ...
The code defines a training loop that trains a model for a specified number of epochs, tracks batch losses, validates periodically, and implements early stopping if validation loss meets stopping criteria. It saves the model upon early stopping and prints progress updates. The loop processes training data in batches, c...
def train(self, epochs=10, track_every=20): """ Defines the main training loop of the pipeline. """ self.model.train() print("Model put in training mode.") for i in range(epochs): stop_training = False batch_losses ...
def create_generifs_from_abstracts( self, gene: str, abstracts: str ) -> Iterable[str]: """ Creates GeneRIFs (Gene Reference Into Function) data from a set of abstracts. Args: gene (str): The name of the gene to be summarized. abstracts (str): A collection of abstrac...
This function identifies genes involved in a biological process by generating summaries from gene data (RIFs and abstracts) and either returning these summaries or a narrative about the genes' roles in the process.
def find_biological_process_from_genes( self, input_genes: Union[Iterable[Union[str, int]], dict], just_summaries: bool = False, add_abstracts: bool = False, ) -> Union[str, dict]: """ Determines the involvement of a set of genes in a specific biological process, eith...
def get_saving_name(details): vendor, image_name, slice_num = details name = vendor + '_' + image_name + '_' + str(slice_num).zfill(3) return name def predict_mask(image, model, CROP_H, CROP_W, threshold=0.5): h,w=image.shape[:2] mask=np.zeros((h,w)) for i in range(0, h, CROP_H): for j...
This function processes stacked image slices by generating segmentation masks using a model, saving masks as PNGs, and optionally creating and saving overlay images combining original images and masks. It iterates through input slices, applies model prediction with a threshold, and stores results in specified directori...
def process_stacked_slices(stacked_slice_iterator, model, H, W, mask_fol, OVERLAY, overlay_fol): for tup in stacked_slice_iterator: stack_img, details = tup save_name = get_saving_name(details) img=np.moveaxis(stack_img, 0, -1) mask=predict_mask(img, model, H, W, 0.9) # sa...
def _omit_empty_columns(self, df): omit_list = [] for col in df.columns: count_nan = df[col].isna().sum() ratio = count_nan / self.total if ratio > self.NAN_TOLERANCE: omit_list.append(col) return df.drop(columns=omit_list) def _normalize(self,...
This code preprocesses a kidney disease dataset by reading, cleaning (removing empty columns, normalizing), and splitting data into training/test sets based on 'is_train'. It constructs input/output tensors for machine learning, mapping features to tensor dimensions and handling multi-dimensional data. The main task is...
def __init__(self, is_train): self.TRAIN_RATIO = 2 self.NAN_TOLERANCE = 0.5 self.is_train = is_train self.file_location = "kidney_disease.csv" csv_data = pd.read_csv("kidney_disease.csv") self.total = len(csv_data) df = pd.DataFrame(csv_data) df = df.drop...
def get_show_entity(show): show_entity = { 'id': show['ids']['trakt'], 'title': show['title'], 'year': None, 'overview': show['overview'], 'runtime': show['runtime'], 'trailer': show['trailer'], 'homepage': show['homepage'], 'genres': show['genres'], ...
This function inserts popular TV shows from the Trakt API into a database, handling up to max_show_count entries. It fetches show data in pages, validates entries, inserts show details, genres, seasons, and cast into the database, tracks progress, and returns a list of inserted show IDs while handling errors.
def insert_shows(limit=20, max_show_count=1000): limit = max(1, min(limit, TRAKT_MAX_LIMIT)) max_show_count = max(1, min(max_show_count, TRAKT_MAX_SHOW_COUNT)) inserted_ids = [] result_page = 1 total_counter = 0 while total_counter < max_show_count: url = f"{TRAKT_API_URL}/shows/popular...
def insert_genres(): url = f'{TRAKT_API_URL}/genres/movies' genre_request = requests.get(url, headers=headers) counter = 0 trakt_expected_genre_count = len(genre_request.json()) for i, genre in enumerate(genre_request.json()): statement = "INSERT INTO genres (name) VALUES (%(name)s);" ...
The main task of the code is to initialize a database schema and populate it with data either by connecting to the TRAKT API (downloading show/genre/actor data) or by executing pre-prepared SQL files containing local data dumps. The program asks the user to choose between API-based data insertion (slower, dynamic) or f...
def main(): print("The program can try connecting to the TRAKT API to download data or use local data to insert instead (faster)?") answer = input("Do you want to connect to the TRAKT API? (y/n) ") init_db.init_db() init_db.create_schema() if answer.lower() == "y": insert_genres() i...
def convert_to_target (item, yaml, ovp): global ovp_trace data = yaml[item] res = False # temp fixups.. if item == "Privilege_Spec_Version" and str(data) == "1.1": data = "1.10" ### the ones with a '#' ini the comment as last field - could be hidden if we are just ignoring them if item =...
The function converts YAML configuration files into an OVPsim control file for RISC-V simulations. It merges ISA and platform YAMLs, processes key-value pairs to format them for OVPsim, validates architecture alignment (e.g., xlen), and writes the configuration with specific syntax. It includes checks for compatibility...
def write_ovp(isa_yaml, platform_yaml, OVPsim_check, work_dir, args_trace): global ovp_trace ovp_trace = args_trace logger.info ("Initiating writeOVPsim config file ("+str(ovp_trace)+")") logger.info('Loading input file: ' + str(isa_yaml)) yaml = utils.load_yaml(isa_yaml) yaml.update(utils.load...
def is_auth_company(current_user): admin = get_admin(current_user) if not admin.update_company: return False return True def is_auth_colleague(current_user, colleague=None): if not colleague: colleague = current_user admin = get_admin(current_user) if not admin.update_colleague: ...
The function generates a navigation menu with left and right sections, dynamically populating links based on user authentication status and provided list. It includes user-specific links (logout, profile) and admin-specific links (Company, Colleagues, Privilegs) conditional on permissions, using predefined URL mappings...
def get_nav(current_user, lst = ["Main"], colleague = None): if not colleague: colleague = current_user left = { "Home": "/", "Sample": "/sample", "Main": "/main", "Profile": "profile", "Company": "/company_profile", "Colleagues": "/colleagues", "...
def predecessor(graph, idx): edges = graph['operation', 'precedence', 'operation'].edge_index return pred_one(edges, idx) def scheduled(operation): return operation[OP_FEATURES["status"]] == SCHEDULED def end_op(graph, idx): return op_val(graph, idx, 'start') + op_val(graph, idx, 'duration')
This function determines if an operation in a graph can be scheduled at time `t` by checking if it is not already scheduled and if all predecessors (if any) are either non-existent, the first operation, or have completed by time `t`.
def to_schedule(graph, idx, t): op = graph['operation'].x[idx] pred_idx = predecessor(graph, idx) return (not scheduled(op)) and (pred_idx==None or pred_idx==0 or (scheduled(graph['operation'].x[pred_idx]) and t>=end_op(graph,pred_idx)))
def solve(model, instance, train=False): graph, graph2instance, makespan = instance_to_graph(instance) sequences = [[] for _ in graph['resource'].x] utilization = [0 for _ in graph['resource'].x] nb_operations_to_schedule = graph['operation'].x.shape[0] - 2 time = 0 error = False requirement...
The code validates a machine learning model on given instances by calculating average reward and loss using Proximal Policy Optimization (PPO). It evaluates the model in inference mode, computes rewards and loss for each instance, aggregates metrics, and prints averages. Finally, it re-enables training mode for the mod...
def validate(model, instances): model.eval() total_rewards = 0 total_loss = 0 with torch.no_grad(): for instance in instances: rewards, values, probabilities, states, actions, actions_idx = solve(model, instance, train=True) loss = PPO_loss(model, probabilities, states, a...
def choose(max): """make sure the user enters the right input""" while True: try: choice = input(Fore.YELLOW + "choose an option : ").strip() if not choice.isdigit() or int(choice) < 1 or int(choice) > max: raise ValueError choice = int(choice) ...
The main task of the code is to present a menu-driven password manager interface, allowing users to retrieve, add, delete, update passwords, or exit. It handles user choices, validates inputs, and routes actions to corresponding functions (e.g., `retrieve_one`, `add`, `delete_one`). It includes error handling, retry op...
def main_menu(f): """make user choose an option and handle translating between methods""" print("Please choose an option:") print("1. Retrieve a password ") print("2. Retrieve all passwords") print("3. Add a password") print("4. Delete a password") print("5. Delete all passwords") print(...
def ransol(fieldsList): n=10 l=[] for i in range(n): s=[] for a,b in fieldsList: c=random.randint(0,(len(b)-1)) s.append(b[c]) l.append(s) return l def geneticAlgo(ip): ta=ip.copy() generations=400 for i in range(generations+1): a,b=pic...
The code implements a genetic algorithm to optimize crop allocation across fields, using initial random solutions and global parameters like crop yield, rate, and requirements. It processes the population through the genetic algorithm, calculates deviations, and returns the optimized result for meeting specified agricu...
def findSolution(fieldsList,cropYield,cropRate,Requirement): initialPop=ransol(fieldsList) print(initialPop) global fieldsListG fieldsListG=fieldsList global cropYieldG cropYieldG=cropYield global cropRateG cropRateG=cropRate global RequirementG RequirementG=Requirement glo...
def debug(*a, **kw): if debug_on: print(*a, **kw) def commit_candidate(self): self.commit_string(self.candidates[self.lookup_table.get_cursor_pos()]) def commit_string(self, text): self.commit_text(IBus.Text.new_from_string(text)) self.preedit_string = '' self.update_candidat...
This function processes keyboard events for an input method, handling key presses to edit or commit pre-edit text, navigate candidate lists, and manage lookup tables. It ignores key releases, processes navigation (page/up/down), number key selections, and ASCII characters, committing text when appropriate. The goal is ...
def do_process_key_event(self, keyval, keycode, state): debug("process_key_event(%04x, %04x, %04x)" % (keyval, keycode, state)) # ignore key release events is_press = ((state & IBus.ModifierType.RELEASE_MASK) == 0) if not is_press: return False if self.preedit_strin...
def _update_static_export(self, step_time): start_time = datetime.now() objects = self._get_unfinished_export_objects('STATIC') if not objects: return True while objects: obj = objects.pop() tmesh = self._get_static_triangle_mesh_data(obj) ...
This function manages sequential export stages (STATIC → KEYFRAMED → ANIMATED) by updating progress with `step_time`, transitioning to the next stage upon completion, and returning `True` when reaching 'FINISHED'. It updates progress via stage-specific methods and resets progress to 0.0 when advancing stages, finalizin...
def update_export(self, step_time): if self.export_stage == 'STATIC': is_finished = self._update_static_export(step_time) self.export_progress = self._get_export_stage_progess('STATIC') if is_finished: self.export_stage = 'KEYFRAMED' self.expor...
def is_material_library_available(): return material_data.materials and material_data.blend_file def __validate_enum_icons(): if not is_material_library_available(): return filedir = os.path.dirname(os.path.realpath(__file__)) blend_path = os.path.join(filedir, material_data.blend_file) ico...
The function initializes and loads custom icons for materials from a blend file. It checks material library availability, processes material data, validates icons, loads materials from the blend file, generates icons if missing, stores them in a global dictionary, and cleans up temporary materials, finally marking cust...
def __initialize_material_library_icons(): global CUSTOM_ICONS global IS_CUSTOM_ICONS_LOADED if not is_material_library_available(): return material_enums = [] mdata = material_data.materials for m in reversed(mdata): e = (m.identifier, m.name, m.description, len(material_enums...
def __check_custom_icons_initialized(): global IS_CUSTOM_ICONS_LOADED if not IS_CUSTOM_ICONS_LOADED: __initialize_material_library_icons() def __get_non_material_library_enums(): enums = [] mdata = bpy.data.materials for m in reversed(mdata): e = (m.name, m.name, "", m.preview.icon_i...
This function generates a list of material enums for UI selection by combining non-library and library material entries, inserting a 'none' option at the start, and adding numerical identifiers to each enum for UI handling.
def get_surface_material_enums_ui(scene = None, context = None): __check_custom_icons_initialized() non_library_enums = __get_non_material_library_enums() library_enums = __get_surface_material_library_enums() enums = non_library_enums + library_enums enums.insert(0, __get_none_material_enum()) ...
def __check_custom_icons_initialized(): global IS_CUSTOM_ICONS_LOADED if not IS_CUSTOM_ICONS_LOADED: __initialize_material_library_icons() def __get_non_material_library_enums(): enums = [] mdata = bpy.data.materials for m in reversed(mdata): e = (m.name, m.name, "", m.preview.icon_i...
The function generates a list of material enum items for a UI, combining non-library and library materials, inserting a 'none' option at the start, and adding numerical identifiers to each enum entry for UI display or processing.
def get_whitewater_material_enums_ui(scene = None, context = None): __check_custom_icons_initialized() non_library_enums = __get_non_material_library_enums() library_enums = __get_whitewater_material_library_enums() enums = non_library_enums + library_enums enums.insert(0, __get_none_material_enum(...
def __check_custom_icons_initialized(): global IS_CUSTOM_ICONS_LOADED if not IS_CUSTOM_ICONS_LOADED: __initialize_material_library_icons() def __get_material_library_enums(): global CUSTOM_ICONS enums = [] mdata = material_data.materials for m in reversed(mdata): e = (m.identifie...
The function generates a list of material import enums for a UI, combining library entries with an "All Materials" option and adding numerical identifiers for UI display. It initializes custom icons, retrieves library enums, inserts an "All Materials" enum at the start, and appends number-based identifiers to each entr...
def get_material_import_enums_ui(scene = None, context = None): __check_custom_icons_initialized() library_enums = __get_material_library_enums() library_enums.insert(0, __get_all_materials_enum()) __add_material_enum_number_identifiers(library_enums) return library_enums
def set_main_theme(self, theme_name): """ Sets the main theme in use. """ if self.game_themes.get(theme_name): self.theme = self.game_themes.get(theme_name) else: self.theme = self.game_themes.get("Default") def bind_direction_keys(self): """ Bind main key...
This code initializes a Tkinter-based game interface with customizable themes. It sets up the main window, binds directional keys, creates side panels, a grid layout for game cells, and a theme menu. The class configures UI elements, enforces aspect ratios, and prepares the game environment with selected themes, ultima...
def __init__(self, game, dimensions, all_themes, master=None): tk.Frame.__init__(self, master) self.master = master self.game = game self.dimensions = dimensions self.game_themes = all_themes self.set_main_theme("Sci-fi") self.grid_cells = [] self.score = ...
def loadDict ( ): applicationDict = {} try: inFile = open('jobChartData.pickle', 'rb+') applicationDict = pickle.load(inFile) except OSError as error: print ('Error: failed to read from file', error ) except EOFError as error: print ('No saved data found, creating a new ...
The main task of the code is to run a menu-driven application that repeatedly displays a menu, validates user input, and processes selected options (1-7) using a dictionary (`applicationDict`). The loop continues until the user selects the quit option (7), with `processChoice` handling each menu action.
def main ( ): MIN_MENU_CHOICE = 1 MAX_CHOICE_QUIT = 7 choice = -1 applicationDict = { } applicationDict = loadDict ( ) while choice != MAX_CHOICE_QUIT: printMenu ( ) choice = getValidInteger ( MIN_MENU_CHOICE, MAX_CHOICE_QUIT, 'Enter menu choi...
def get_candidates(seating_plans) -> (list[str], list[str]): result = ([], []) for sp in seating_plans: add = [sorted(list(team)) for team in list(zip(*sp))] result = (result[0] + add[0], result[1] + add[1]) return remove_duplicates(result[0]), remove_duplicates(result[1]) def subtract_confi...
The function generates all valid match combinations by considering confirmed matches and possible candidates, subtracting confirmed pairs from candidate lists, and checking feasibility against seating plans and match counts. It returns a list of sets containing confirmed and valid new match pairs.
def get_all_possible_match_combinations(seating_plans, all_match_counts: list[int], confirmed_matches: list[(str, str)]) -> list[set[(str, str)]]: confirmed_matches_set = set(confirmed_matches) candidates_a, candidates_b = get_candidates(seating_plans) candidates_a_su...
def create_dataloader(data, batch_size, shuffle = True, device = None, **kwargs): ds = ExperienceDataset(data, device = device) return DataLoader(ds, batch_size = batch_size, shuffle = shuffle, **kwargs) def shift(t, value = 0, shift = 1, dim = -1): zeros = (0, 0) * (-dim - 1) return F.pad(t, (*zeros, s...
This code implements Proximal Policy Optimization (PPO) training for an actor-critic model. It processes stacked memory sequences, computes policy and value losses with advantage normalization, applies gradient clipping, and updates both actor and critic networks through minibatch iterations. The algorithm incorporates...
def learn( self, memories: Deque[Memory] ): # stack all data stored in the memories all_memories_stacked_and_padded = list(map(partial(pad_sequence_fixed, batch_first = True), zip(*memories))) # prepare dataloader for policy phase training dl = create_dataloader(al...
def shift(t, value = 0, shift = 1, dim = -1): zeros = (0, 0) * (-dim - 1) return F.pad(t, (*zeros, shift, -shift), value = value) def log_prob(prob, indices): assert prob.shape[:2] == indices.shape, f'preceding shapes of prob {prob.shape[:2]} and indices {indices.shape} must match' return log(prob.gathe...
The code trains a language model using reinforcement learning with human feedback (RLHF) by iteratively generating sequences, evaluating them with a reward model, and optimizing the policy via stored experiences. It samples prompts, generates actions with an actor-critic model, calculates rewards, and updates the model...
def train( self, num_episodes = 50000, max_timesteps = 500, update_timesteps = 5000, max_batch_size = 16, max_seq_len = 2048, eos_token = None, temperature = 1. ): device = self.device time = 0 memories = deque([]) for...
def lxprint(a): #Status display global PIPE_PATH with open(PIPE_PATH, "a") as p: p.write(a + "\r\n") def retrieveExperiment(driveLabel): global mountDir global imageDir global protocolFile global resultsFile global resultsFileBase global imageExt global parameterDict glob...
This function monitors for USB insertion, validates the drive's label and format, mounts it if valid, executes an experiment, and unmounts the drive. It uses pyudev for detection, subprocess for system commands, and regex to check for specific labels. Errors are reported if the drive is invalid or not found, and the pr...
def checkForUSB(): global mountDir lxprint("Please insert USB drive:") context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') connected = False labelName = None while True: time.sleep(0.2) #Search for whether a USB dri...
def configBoot(): global reboot global devnull lxprint("Checking if monitor is configured correctly...") #use raspi-config to change device sonfiguration #Any outputs from program are redirected to /dev/null #Check if Raspberry Pi is already set to boot into terminal with autologin out1, dum...
The function `checkPiConfig()` performs system configuration tasks on a Raspberry Pi, including checking user permissions, removing temporary files, configuring boot and screensaver settings, installing dependencies like xscreensaver, importing libraries, disabling automount, and triggering a reboot if required. It ens...
def checkPiConfig(): global reboot global temp_file global pyudev reboot = False if os.geteuid() != 0: #Remove temp config file if it exists f = Path(temp_file) if f.is_file(): subprocess.call("sudo rm " + temp_file, shell=True) configBoot() if not...
def HMAC( data:bytes, key:bytes, hasher:Hasher ) -> bytes: """Perform HMAC with the given hash function . Be sure to read the HMAC spec carefully! PARAMETERS ========== data: The bytes object to be hashed. key: A bytes object to be used as a key. hasher: A Hasher instance. ...
The function `pad_encrypt_and_HMAC` encrypts plaintext using a cipher key, pads it, and appends an HMAC tag for authentication. It generates an IV, pads the plaintext to the hasher's digest size, encrypts the padded data, prepends the IV, and appends the HMAC tag (computed with the HMAC key). The output combines IV, ci...
def pad_encrypt_and_HMAC( plaintext:bytes, key_cypher:bytes, key_HMAC:bytes, hasher:Hasher, \ block_ids:Callable[[int], Iterator[bytes]] ) -> bytes: """Encrypt a plaintext with your encryption function. Note the order of operations! PARAMETERS ========== plaintext: The bytes object...
def encrypt( iv:bytes, data:bytes, key:bytes, hasher:Hasher, \ block_ids:Callable[[int], Iterator[bytes]] ) -> bytes: """Encrypt the given data, with the given IV and key, using the given hash function. Assumes the data has already been padded to align with the digest size. Do not prepend the ...
The function `decrypt_and_verify` decrypts encrypted data using a cipher key and verifies its integrity via HMAC. It checks the ciphertext's structure, extracts the HMAC, decrypts the payload, unpad it, and validates the HMAC against the decrypted data. If all steps succeed, it returns the plaintext; otherwise, it retu...
def decrypt_and_verify( cyphertext: bytes, key_cypher: bytes, key_HMAC:bytes, hasher:Hasher, \ block_ids:Callable[[int], Iterator[bytes]] ) -> Optional[bytes]: """Decrypt a plaintext that had been encrypted with the prior function. Also performs integrity checking to help ensure the original wasn't ...
def proc_ocr(img): info_text = pytesseract.image_to_string(img, lang='eng', config=tessdata_dir_config, output_type=Output.DICT) res_txt = info_text['text'] # print('tess result : ' + res_txt) num = get_digit(res_txt) # print('extrated num : ' + num) return num def rgb_bin(img): h_im, w_im ...
The function performs OCR on an input image by attempting multiple preprocessing steps: inverting the image, binarizing it, resizing, and applying different OCR methods (proc_ocr, ocr_colr). It returns the first detected number from these processes. If all fail, it returns an empty string.
def ocr_one(img_one): h, w = img_one.shape[:2] img_inv = 255 - img_one num = proc_ocr(img_inv) # print('org_num' + num) # show_img(img_inv, False) if len(num) > 0: return num img_bin = rgb_bin(img_one) num = proc_ocr(img_bin) # print('bin_num' + num) # show_img(img_bin, ...
def ocr_one(img_one): h, w = img_one.shape[:2] img_inv = 255 - img_one num = proc_ocr(img_inv) # print('org_num' + num) # show_img(img_inv, False) if len(num) > 0: return num img_bin = rgb_bin(img_one) num = proc_ocr(img_bin) # print('bin_num' + num) # show_img(img_bin, ...
The function processes an image to extract and recognize numbers from the first row of a document. It identifies regions of interest (ROI) based on contours, applies OCR to the main area, and processes adjacent regions for additional numbers. After filtering and sorting, it concatenates OCR results into a string, combi...
def proc_first_row(img, contours, roi): res = '' xx, yy, ww, hh = roi xfi, yfi, wfi, hfi = 0, 0, 0, 0 roi_fi = [] for i in range(0, len(contours)): c = contours[i] x, y, w, h = cv2.boundingRect(c) if y > yy - hh: continue if y < yy - 3 * hh: co...
def remove_overlap(img, rois): rect_roi = [] # === {{ remove the overlap rectangls len_rts = len(rois) for i in range(0, len_rts): bOverlap = False (xi, yi, wi, hi) = rois[i] for j in range(0, len_rts): if i == j: continue (xj, yj, wj, hj) ...
The code detects and recognizes numbers in an image by processing contours, filtering regions of interest, grouping them into lines, and applying OCR to extract digits. It resizes, thresholds, and segments the image to identify potential number areas, then concatenates OCR results into a string.
def detect_number(filepath): image = cv2.imread(filepath) if image is None: return 'Invalid iamge' res = '' h_img, w_img = image.shape[:2] gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) img_re = cv2.resize(image, (w_img * 3, h_img * 3)) gray_re = cv2.resize(gray, (w_img * 3, h_img *...
def _setup_specification(self, spec): for field, value in spec.model_dump().items(): if value: self._write_value(field, value) def _setup_localisation(self, strings): for locale in strings: strings_path = self.path / f"strings/{locale.language}" string...
The main task of the code is to initialize a USB Gadget device using values from a model. It configures the device specification, localisation strings, HID functions, and links them to a configuration. The function sets up components like device specs, HID functions, and configuration parameters (e.g., max power) to fi...
def setup_from_model(self): """ Set up the gadget using values from the model. """ log.info( "Setting up USB Gadget Device Specification", gadget_name=self.gadget_name ) self._setup_specification(self.model.spec) log.info("Setting up Localisation Stri...
def ref_interactive(self, px, py, pr): ''' Manual refinement of the detected diffraction pattern via one of the methods provided in the class CircleDetection. The user can change the position of the center of the diffraction pattern and also the radius of the detected ...
The code initializes an image processing class by calling a base constructor, setting parameters, and applying correction methods (manual, var, sum) to adjust detected coordinates and radii. It swaps axes for 'hough' detection and optionally visualizes refinements, handling different detection-correction method combina...
def __init__(self, image_path, detection_method, correction_method=None, heq=False, icut=None, cmap='gray', messages=False, final_replot=False): # (1) Call the constructor of the base class to initialize its methods super().__init__(image_path...
def make_reservation(): customer = ask_name() destination = select_destination() print(f"Your randomly selected destination is: {destination.city}") while True: try: vehicle = select_vehicle() print(f"You've selected a {vehicle.vtype}") if vehicle.vtype == 'b...
The code defines a menu-driven interface for a Random CityTrip system, allowing users to book a trip, view their reservation, or exit. It validates numeric input and recursively loops until the user selects option 3, which terminates the program with a thank-you message.
def menu(): while True: print("\nMENU") print("[1] Book a Random CityTrip") print("[2] View your Random CityTrip") print("[3] Exit\n") try: selection = int(input("YOUR SELECTION: ")) except ValueError: print("Only numbers please") else...
def alloc(cScope: bytearray,size: int,value:int=0): optr = vptr() #print(size) #print(istack) #print(len(istack)) optr.start = len(cScope) #print(optr.start) optr.size = size for i in range(size): istack.append(value) return optr def pushVar(cVars,name: str, ptr: vptr): ...
The code simulates a simple programming language interpreter, managing memory allocation, variable declarations, arithmetic operations, and control flow. It processes a list of tokens, handling variable types (`int`, `char`, `bool`), assignments, arithmetic updates (`+=`, `-=`), conditional statements (`if`), loops (`w...
def simulate_Code(words: list): #out = [] global istack #print(words) # cScope = istack # cVars = varList scopeVars = vptr(0,0) cVarPTL = [scopeVars] index = 0 while index < len(words): wordInfo = words[index] word = wordInfo["word"] #indexWord = wordInfo...
def test_sync0(self): # Test if the data in the buffer is the first sync bit # This bit consists of high amplitude with ~21 samples # and low amplitude with ~10 samples avh = self.signal_avr(0, 20) avl = self.signal_avr(26, 33) if avh < avl * 2: return # high signal ampl. should be gr...
This code processes a signal buffer to detect synchronization bits and decode data. It maintains a buffer, checks for clipped signals, transitions between states ('wait', 'sync', 'data'), and appends decoded bits to a data list. When sync is detected, it switches to data decoding; if errors occur (e.g., invalid bit val...
def process(self, value): self.buf.pop(0) self.buf.append(value) self.pulse_len += 1 if self.pulse_len <= 35: return # buffer not filled if self.clipped % 10000 == 1: logging.error("Clipped signal detected, you should reduce gain of receiver!") if self.decoder_state == 'wait': ...
def test_sync_block(self): # A valid sync block has the levels on-off-on-off-on-off. # Each level has a duration of avr. 15 samples. # But allow a jitter of 5 samples for each level change. avh0 = self.signal_avr(0, 10) avl0 = self.signal_avr(20, 25) if avh0 < avl0 * 2: return # high sign...
This code processes a signal buffer by updating its state, detecting sync blocks, and managing signal transitions. It checks for clipped signals, updates pulse length, and determines signal states based on noise levels. When conditions are met, it triggers frame/packet decoding, resets, or logs errors, ensuring proper ...
def process(self, value): self.buf.pop(0) self.buf.append(value) self.pulse_len += 1 if self.clipped % 10000 == 1: logging.error("Clipped signal detected, you should reduce gain of receiver!") if self.decoder_state == 'wait': if self.pulse_len > 90: self.test_sync_block() ...
def load_csv(filename): dataset = list() is_first = True with open(filename, 'r') as file: csv_reader = reader(file) for row in csv_reader: if not row: continue if is_first: is_first = False continue dataset....
The code performs cross-validation (5-fold) on a dataset using a Naive Bayes classifier. It preprocesses data, splits into folds, trains on each fold's complement, predicts test samples, computes accuracy, recall, and precision metrics, and visualizes confusion matrices. Results are aggregated across folds and printed ...
def naive_bayse(filename): dataset = load_csv(filename) classes_metadata = preprocess_data(dataset) n_folds = 5 folds = cross_validation_split(dataset, n_folds) scores = list() recalls = list() precisions = list() accuracies = list() for fold in folds: train_set = list(folds...
def _initialization(self): self.net.apply(self._weights_init_xavier) if self.option.is_train and self.option.use_pretrain: if self.option.checkpoint is not None: self._load_model() else: print("no prtrained model") def _load_model(self): c...
The code trains a model using a specified training data loader, optionally with validation. It initializes the model, loads a checkpoint if provided, sets training mode, and iterates over training steps. Depending on the configuration, it performs baseline or standard training. After each step, it updates the learning ...
def train(self, train_loader, val_loader=None): self._initialization() if self.option.checkpoint is not None: self._load_model() self._mode_setting(is_train=True) start_epoch = 0 for step in range(start_epoch, self.option.max_step): if self.option.train_b...
def get_monotonic_array(self, state): size=self.board_size monotonic_array = np.zeros((size, size)) for i in range(size): for j in range(size): if state.board[0, i, j] == 1: monotonic_array[i, j] = 0 elif state.board[1, i, j] == ...
The code evaluates game states to find optimal moves by checking for immediate wins, blocking opponent's threats, handling open 3s, and selecting actions with minimal heuristic values from a model when no clear threats or wins are present.
def __call__(self, state): monotonic_array = self.get_monotonic_array(state) actions = state.valid_actions() board = monotonic_array # Can we win in this move? win_pattern = [1, 1, 1, 1, 0] win_actions = self.find_win_moves(monotonic_array, win_pattern) # Is the...
def __makeRequest(self, videoId: str) -> int: request = Request( 'https://www.youtube.com/watch' + '?' + urlencode({ 'v': videoId, 'pbj': 1, }), headers = { 'User-Agent': userAgent, }, data = urlencode({}...
The code initializes an object to process a video link by fetching its ID, making a request, and parsing data if the response status is 200. It retrieves components based on the specified mode and raises an error for invalid status codes.
def __init__(self, videoLink: str, componentMode: str, resultMode: int): self.resultMode = resultMode statusCode = self.__makeRequest(self.__getVideoId(videoLink)) if statusCode == 200: self.__parseSource() self.__getComponents(componentMode) else: rai...
def __makeRequest(self, playlistLink: str) -> int: playlistLink.strip('/') request = Request( playlistLink + '&pbj=1', data = urlencode({}).encode('utf_8'), headers = { 'User-Agent': userAgent, }, ) try: response...
The code initializes a class with parameters for a playlist link, component mode, and result mode. It sends a request to the playlist link, checks the HTTP status code, and if successful (200), parses the source data and retrieves components. Otherwise, it raises an error for invalid status codes.
def __init__(self, playlistLink: str, componentMode: str, resultMode: int): self.componentMode = componentMode self.resultMode = resultMode statusCode = self.__makeRequest(playlistLink) if statusCode == 200: self.__parseSource() self.__getComponents() else...