dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def respond(err, res=None): return { 'statusCode': '400' if err else '200', 'body': err.message if err else json.dumps(res), 'headers': { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*", }, } def getTopPlayersHandler(params): if ...
This code routes HTTP requests to specific handlers based on the URL path and method. It checks the `path` and `httpMethod` parameters, and if they match predefined endpoints (e.g., "/topplayers", "/subscribe"), it invokes corresponding functions like `getTopPlayersHandler` or `subscribeHandler`. If no match is found, ...
def router(path,httpMethod,params=None,body=None): if path=="/topplayers" and httpMethod=="GET": return respond(None, getTopPlayersHandler(params)) elif path=="/player" and httpMethod=="GET": return respond(None, getPlayerHandler(params)) elif path=="/playerv2" and httpMethod=="GET": ...
def next(self): self.current_char = self.file.read(1) if self.current_char == '': self.end_of_file = True return False self.pos += 1 self.column_number += 1 if self.current_char == '\n': self.line_number += 1 self.column_n...
This method determines the type of markdown token to return based on indentation and current character. If in 'markdown' mode, it checks indentation: zero indent checks for '#' (headline) or default paragraph; non-zero indent returns an unknown token.
def token(self): self.next() if self.mode == 'markdown': if self.indent == 0: if self.current_char == '#': return self.read_markdown_headline() else: return self.read_markdown_paragraph() else: ...
def all_same(items): return all(x == items[0] for x in items) def find_best_split_of_all(x, y): Max_MI = -100 index = -1 H_Y = cal_entropy(y) median_list = np.median(x,axis=0).tolist() for i in range(482): cur_median = median_list[0][i] H_Y_X = cal_en...
This code recursively builds a decision tree by splitting data on features with the highest mutual information. It creates internal nodes for splits and leaf nodes for terminal predictions, tracking node counts and depth. The function checks for uniform labels or low information gain to terminate recursion, returning s...
def fit(self, x, y, par_node={}, depth=0): global no_leaf_nodes, no_internal_nodes if par_node is None: return None elif len(y) == 0: return None elif all_same(y): no_leaf_nodes +=1 # print('label :',y[0],'depth :',depth,'node typ...
def train(args, train_dataset, eval_dataset, model, tokenizer): """ Train the model """ #if args.local_rank in [-1, 0]: tb_writer = SummaryWriter() args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else Distr...
The code defines a script for fine-tuning a pre-trained model (e.g., BERT) on a vision-and-language task, such as Visual Question Answering (VQA). It processes text and image data, supports training, evaluation, and testing with configurable parameters like model type, loss functions, batch sizes, and data formats. The...
def main(): parser = argparse.ArgumentParser() ## Required parameters parser.add_argument("--data_dir", default=None, type=str, required=True, help="The input data dir. Should contain the .tsv files (or other data files) for the task.") parser.add_argument("--txt_data_dir", defa...
def train(args, train_dataset, val_dataset, model, tokenizer): args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = RandomSampler(train_dataset) train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, num_worke...
The main task of the code is to train and evaluate an image-text retrieval model using BERT and image features. It parses arguments for data paths, model configurations, training parameters (e.g., batch size, learning rate), and evaluation settings. The script supports training with COCO dataset features, cross-image i...
def main(): parser = argparse.ArgumentParser() parser.add_argument("--data_dir", default='datasets/coco_ir', type=str, required=False, help="The input data dir with all required files.") parser.add_argument("--img_feat_file", default='datasets/coco_ir/features.tsv', type=str, require...
def getRelRate(self): print('Compute matrix for each rating - avg. rating of user') return self.train0 - self.getMeanMatrix() def getCovarMatrix(self, ARel): print('Get Weight matrix numerator term') wNum = self.getCovarMatrixNumerator(ARel) print('Get Weight matrix denominator t...
The main task of the code is to generate recommendations (self.reco) by calculating a delta adjustment using a relational rate (aRel), covariance matrix (weights), and delta values. It combines this delta with training data means (trainMean) to produce a DataFrame of predicted values, aligning columns/indices with miss...
def calcRec(self): aRel = self.getRelRate() weights = self.getCovarMatrix(aRel) delta = self.getDelta(weights, aRel) self.reco = pd.DataFrame(self.trainMean + delta, columns=list(self.trainNan.columns), index=list(self.trainNan.index)) return self.reco
def getRelRate(self): print('Get Relative Rate') return self.train0 - self.getMeanMatrix() def getCovarMatrix(self, ARel): print('Get Weight matrix numerator term') WNum = self.getCovarMatrixNumerator(ARel) print('Get Weight matrix denominator term') WDenom = self.getCova...
The code calculates a recommendation matrix by combining a training mean with a delta value derived from covariance weights and relevance rates, then returns this as a DataFrame with matching columns and indices.
def calcRec(self): ARel = self.getRelRate() Weights = self.getCovarMatrix(ARel) Delta = self.getDelta(Weights, ARel) self.reco = pd.DataFrame(self.trainMean + Delta, columns=list(self.train0.columns), index=list(self.train0.index)) return self.reco
def get_auth_user(self, username, email, password): """ Retrieve the auth user from given POST payload by using either `allauth` auth scheme or bare Django auth scheme. Returns the authenticated user instance if credentials are correct, else `None` will be returned """ ...
The code validates user authentication credentials by checking if a user exists with provided username/email/password, ensuring the user is active, and verifying their email status. It raises errors for invalid credentials or unverified emails and attaches the validated user to the attributes for further processing.
def validate(self, attrs): username = attrs.get('username') email = attrs.get('email') password = attrs.get('password') user = self.get_auth_user(username, email, password) if not user: msg = _('Unable to log in with provided credentials.') raise ...
def print_menu(self) -> None: """Outputs main menu choices.""" system("clear") console.print( """\n\n\n[bold green] ████████ ...
This code runs a main menu loop for a food picker application, allowing users to select options like picking, searching, adding, editing, or deleting restaurants. It handles user input, executes corresponding methods, and maintains the loop until the exit option (6) is chosen. Invalid inputs trigger error messages, and...
def food_picker_main(self) -> None: """Runs main menu and user menu selection.""" picking_food = True while picking_food: self.print_menu() user_input = console.input( "[green]\nPlease pick a menu option: [blink]" ).strip() match...
def get_neighbors( row: int, col: int, max_rows: int, max_cols: int ) -> set[tuple[int, int]]: """gets all neighboring cells for a given cell. Args: row(int): row of current cell ranging between [0-self.mine_rows] col(int): col of current cell ranging between [0-self.mine_cols] max_...
This function handles left-click events on a grid cell in a minesweeper game. It reveals the cell, checks if it contains a mine (triggering game over), and automatically reveals adjacent cells if the clicked cell has no neighboring bombs. It also processes flagged cells and ensures proper game initialization on the fir...
def left_clicked(self, row: int, col: int) -> None: """presses the cell Args: row(int): row of current cell ranging between [0-self.mine_rows] col(int): col of current cell ranging between [0-self.mine_cols] """ print(f"left Clicked {self.grid[row][col]}") ...
def left_clicked(self, row: int, col: int) -> None: """presses the cell Args: row(int): row of current cell ranging between [0-self.mine_rows] col(int): col of current cell ranging between [0-self.mine_cols] """ print(f"left Clicked {self.grid[row][col]}") ...
This code initializes a Minesweeper game GUI, setting up the grid dimensions, mine count, game state variables, and UI components like the grid, flag counter, timer, and restart button. It configures event handlers for cell interactions and prepares the game environment for player actions.
def __init__(self, mine_rows: int, mine_cols: int) -> None: self.mine_rows: int = mine_rows self.mine_cols: int = mine_cols self.num_of_mines: int = int(self.mine_rows * self.mine_cols * MINES_PERCENTAGE) self.flags_available: int = self.num_of_mines self.window = tk.Tk() ...
def nullable(re: Regexp) -> bool: if isinstance(re, Empty): return False if isinstance(re, Epsilon): return True if isinstance(re, Symbol): return False if isinstance(re, Sequence): return nullable(re.left_re) and nullable(re.right_re) if isinstance(re, Alternative): ...
This function computes the derivative of a regular expression with respect to a given symbol, following the rules of formal language theory. It handles various regex constructs (sequence, alternative, star, etc.) by recursively applying derivative rules, returning a new regex that matches strings formed by removing the...
def derivative(symbol: str, unit: Regexp) -> Regexp: if isinstance(unit, Empty): return Empty() if isinstance(unit, Epsilon): return Empty() if isinstance(unit, Symbol): if symbol == unit.symbol: return Epsilon() return Empty() if isinstance(unit, Sequence): ...
def _get_key_and_iv(self, password, salt): ''' Derive the key and the IV from the given password and salt. This is a niftier implementation than my implementation in C++ because I modified it to support different digests. @param password The password to use as the seed. ...
The code encrypts plaintext using AES-256-CBC with a password, optionally generating OpenSSL-compatible output. It derives keys/IVs, pads data, encrypts via AES-CBC, and encodes results in base64. OpenSSL mode adds a 'Salted__' prefix and salt, while standard mode omits it. The function returns base64-encoded ciphertex...
def encrypt(self, password, plaintext): ''' Encrypt the plaintext using the password, optionally using an openssl compatible encryption algorithm. If it is run in openssl compatibility mode, it is the same as running openssl like this: $ openssl enc -aes-256-cbc -e ...
def err(msg, level=1, ofp=sys.stdout): ''' Display error message with context information and exit. ''' _msg('ERROR', msg, level+1, ofp) abort_threads() sys.exit(1) def _get_key_and_iv(self, password, salt): ''' Derive the key and the IV from the given password and salt. ...
The code decrypts ciphertext using AES-CBC encryption with a password, supporting OpenSSL compatibility. It handles salted key derivation when enabled, extracts IV from ciphertext, performs base64 decoding, and applies PKCS7 unpadding to return plaintext.
def decrypt(self, password, ciphertext): ''' Decrypt the ciphertext using the password, optionally using an openssl compatible decryption algorithm. If it was encrypted in openssl compatible mode, it is the same as running the following openssl decryption command: $...
def stat_inc(stats, key, value=1): ''' Increment the stat in a synchronous way using a mutex to coordinate between threads. ''' th_mutex.acquire() try: stats[key] += value finally: # avoid deadlock from exception th_mutex.release() def lock_file(opts, password, path, stats):...
The function processes a file by incrementing a file count statistic and either locking or unlocking the file based on the 'lock' option in 'opts', using the provided password and path, while checking if an abort flag is not set.
def process_file(opts, password, path, stats): ''' Process a file. ''' if th_abort is False: stat_inc(stats, 'files') if opts.lock is True: lock_file(opts, password, path, stats) else: unlock_file(opts, password, path, stats)
def getopts(): ''' Get the command line options. ''' def gettext(s): lookup = { 'usage: ': 'USAGE:', 'positional arguments': 'POSITIONAL ARGUMENTS', 'optional arguments': 'OPTIONAL ARGUMENTS', 'show this help message and exit': 'Show this help mess...
The main task of the code is to process files/directories in parallel using threads, track operational statistics (e.g., locked files, read/written data), manage thread concurrency with a semaphore, handle keyboard interrupts for cleanup, and generate a summary report. It uses a password for operations, likely encrypti...
def main(): ''' main ''' opts = getopts() password = get_password(opts) stats = { 'locked': 0, 'unlocked': 0, 'skipped': 0, 'files': 0, 'dirs': 0, 'read': 0, 'written': 0, } # Use the mutex for I/O to avoid interspersed output...
def optional_print(self, msg): if self.outs: print(msg) def deal(self) -> None: """Deal cards to players. Increase deck size if too small to deal.""" if len(self.deck.deck) < len(self.players) * 4 + 52: self.deck.deck_reset() self.deck.shuffle() for ...
The code's main task is to manage a game loop by shuffling the deck, dealing cards to players, processing each player's turn, settling the round's outcomes, and resetting for the next turn, repeating this process for a specified number of turns.
def play(self) -> None: """Take turns for all players, settle up, and reset for the next turn.""" self.deck.shuffle() for i in range(self.turns): self.optional_print("\n" + "It's a new deal!") self.deal() self.d1_card = self.dealer_hand("curr")[0][0] ...
def semesters_dump(): print('\nHere are your semesters:\n----------------------------------------------') l = return_semesters() sorted_l = sorted(l, key=lambda cs: cs.name) for cs in sorted_l: print(cs.name) print('----------------------------------------------') def load_courselist_from_se...
The function adds a new assignment to a user's agenda by collecting details like course, name, description, and due date, then saving it to the user's data. It first lists available courses for the specified semester, prompts for input, creates an `Assignment` object, appends it to the user's agenda, and persists the u...
def add_new_assignment_to_agenda(): semesters_dump() sem = input('Which semester is this assignment for?') s = load_courselist_from_semesters(sem) for c in s.courses: print(c) user = load_current_user() a = Assignment( course=str(input('What course is this for? ')), name=...
def _config(confFiles = POOF_CONFIG_FILES, confDir = POOF_CONFIG_DIR, showConfig = True): confFile = confFiles['poof.conf'] _initializeConfigIn(confFile, confDir) configStr = open(confFile, 'r').read() try: actualConfiguration = json.loads(configStr) except: die('invalid JSON? Faile...
The main task of the code is to verify the installation and configuration of required components (e.g., rclone) and configuration files, checking for missing programs, invalid paths, misconfigured settings, and suspicious values in encryption/S3 sections. It returns status codes indicating verification results, such as...
def _verify(component = RCLONE_PROG, confFiles = POOF_CONFIG_FILES, allComponents = True): status = PoofStatus.OK if not shutil.which(component): return component, PoofStatus.MISSING_CLONING_PROGRAM click.echo('installed %s? - %s' % (component, status)) if allComponents: for component...
def _config(confFiles = POOF_CONFIG_FILES, confDir = POOF_CONFIG_DIR, showConfig = True): confFile = confFiles['poof.conf'] _initializeConfigIn(confFile, confDir) configStr = open(confFile, 'r').read() try: actualConfiguration = json.loads(configStr) except: die('invalid JSON? Faile...
The code toggles remote target encryption on/off by modifying configuration settings. It initializes configuration objects from input parameters, then invokes an internal function `_cryptoggle` to update encryption states in the specified configuration files, effectively switching encryption status between enabled and ...
def cryptoggle(conf): """ Toggle remote target encryption ON/OFF. """ poofConf = _config(confFiles = conf.confFiles, showConfig = False) cloneConf = _cconfig(confFiles = conf.confFiles, showConfig = False) _cryptoggle(poofConf, cloneConf, conf.confFiles)
def _verify(component = RCLONE_PROG, confFiles = POOF_CONFIG_FILES, allComponents = True): status = PoofStatus.OK if not shutil.which(component): return component, PoofStatus.MISSING_CLONING_PROGRAM click.echo('installed %s? - %s' % (component, status)) if allComponents: for component...
This function clones files between local and cloud storage using rclone, syncing directories based on configuration. It verifies settings, constructs rclone commands for sync operations, handles errors, and optionally deletes local files post-sync if 'nukeLocal' is enabled. The process checks configurations, skips miss...
def _clone(toCloud, confDir = POOF_CONFIG_DIR, confFiles = POOF_CONFIG_FILES, nukeLocal = True, verbose = False): _, status = _verify(confFiles = confFiles) if status != PoofStatus.OK: die("cannot poof the files to the cloud", 4) conf = _config(confFiles = confFiles, showConfig = False) p...
def isSupported(hostOS): """ Usage: hostOS = platform.system() """ return hostOS == LAUNCH_AGENT_REQUIRED_OS def isEnabled(hostOS = LAUNCH_AGENT_REQUIRED_OS, launchAgentFile = LAUNCH_AGENT_FULL_PATH, launchAgent = LAUNCH_AGENT_POOF): if isSupported(hostOS): if os.path.exists(launchAgentFile...
This function configures a macOS launch agent by checking system compatibility, enabling the agent if disabled, reading its plist configuration file, displaying the content, and copying it to the clipboard. It exits if called on non-macOS systems.
def launchdConfig(hostOS = LAUNCH_AGENT_REQUIRED_OS, agentFile = LAUNCH_AGENT_FULL_PATH, launchAgent = LAUNCH_AGENT_POOF, launchAgentProg = LAUNCH_AGENT_PROG, launchAgentUserName = LAUNCH_AGENT_USER_NAME): if isSupported(platform.system()): if not isEnabl...
def get_connected_devices(): adb_client = get_adb_client() if adb_client is None: logger.error("ADB client is not found") return None else: connected_devices = [] for device in adb_client.devices(): connected_devices.append(device.serial) return connected_...
The main task of the code is to identify and return a connected, available device that matches a specified platform. It checks connected devices, filters available ones, and selects the first device whose capabilities match the desired platform. If no suitable device is found, it logs errors and returns None.
def get_device(): connected_devices = get_connected_devices() desired_platform = Args.get("platform") if connected_devices is None or len(connected_devices) < 1: logger.error("No connected device found!") return None else: logger.info("Connected devices : "+str(connected_devices)...
def initialize(_sciper): """Takes a sciper and initializes the system. This function loads assignment parameters from {sciper}_auth.json. Args: _sciper (int): sciper """ global db global sciper sciper = _sciper print("Hi,") print(f"Your sciper id is {sciper}.") print( "Warning:...
The main task of the code is to implement a brute-force password cracking system targeting SHA-256 and Scrypt-encrypted passwords. It initializes with a SCIPER, filters user lists, generates password guesses using a counter, and checks each guess against remaining users. Matches trigger output and file saving. The acti...
def main(): """ Assignment 3: cracking passwords This scripts lets you check your password guesses . You need to call initialize with your sciper. Afterward you can check your passwords with: check_correctness_sha(username, password) check_correctness_scrypt(username, password) If the password is correct, t...
def enemyCount(data): numEnemies = sum(1 for enemies in data['board']['snakes']) -1 # minus one because the board counts itself in "snakes" return numEnemies def returnMaze(data): boardx = data['board']['height'] boardy = data['board']['width'] maze = np.zeros((boardx,boardy),dtype=int) return m...
The code implements a snake AI that uses the A* pathfinding algorithm to determine the optimal movement direction. It processes game data to create a maze grid, marks enemy and self positions, identifies the closest fruit, and calculates a path to it while avoiding obstacles. The AI returns the direction derived from t...
def move(): data = bottle.request.json """ TODO: Using the data from the endpoint request object, your snake AI must choose a direction to move in. """ # print('--') numEnemies = enemyCount(data) #print(numEnemies) # print(data['turn']) #obtaining 'maze' for astar ...
def nvt(output_name, T_i, T_f, run_time, simulation_time, parameters, run_description, multiple_restarts = None, volume_change = None): """ simple wrapper for md_run input: run_time, simulation_time floats in ps output: code, simulation_time updated """ return md_run('nvt', output_name, T_i, T_f...
The main task of the code is to execute a simulation experiment by generating LAMMPS input files for equilibration steps, managing multiple restarts, and organizing output directories. It merges constant and variable parameters with system info, adjusts time units, constructs run descriptions, and writes files for each...
def run_exp(constant, variable, id, previous_folder = None, next_folder = None): """ input: two dicts containing the constant and variable parameters id: int providing the id used for naming""" os.chdir(working_dir) parameters = {**constant, **variable, **dict(config['system_info'])} # merge t...
def find_ancestors_recursively(self, node): if node.parent is None: return [node.index] else: ancestors_of_parent = self.find_ancestors_recursively(self.all_bb_nodes[node.parent]) ancestors_of_parent.append(node.index) return ancestors_of_parent def ancestors_path_value(self, node): ...
The function calculates an upper bound for a node in an optimization problem by evaluating remaining requests, adjusting capacities, computing feasible routes, and combining objective values with ancestral path contributions. It updates the node's upper bound and tracks the global minimum upper bound for optimization.
def compute_upper_bound(self, node): if hasattr(node, 'reqs_to_route'): remaining_reqs = [self.amod_prob.requests[r] for r in node.reqs_to_route] else: remaining_reqs = copy.deepcopy(self.amod_prob.requests) ancestors_of_parent = self.find_ancestors_recursively(node) for ancestor in ance...
def adjust_caps_ancestors(self, node, ancestors = None): if node is None and ancestors is None: capacities_dict = copy.deepcopy(self.amod_prob.capacity) return capacities_dict elif node is not None: ancestors_of_node = self.find_ancestors_recursively(node) else: ancestors_of_node = a...
This function computes a lower bound for a node in a routing problem by determining remaining capacities and requests, solving an LP relaxation with these constraints, and adding ancestor path values. It handles cases where nodes have predefined capacities/requests or calculates them from ancestors, ensuring accurate l...
def compute_lower_bound(self, node): if hasattr(node, 'remaining_capacity'): caps_dict = node.remaining_capacity else: caps_dict = self.adjust_caps_ancestors(node) if hasattr(node, 'reqs_to_route'): remaining_reqs = [self.amod_prob.requests[r] for r in node.reqs_to_route] else: ...
def adjust_capacities(self, caps_dict, paths): for path in paths: for k in range(len(path) - 1): if self.amod_prob.road.has_edge(path[k], path[k+1]): if (path[k], path[k+1]) in caps_dict.keys(): caps_dict[(path[k], path[k+1])] -= 1 elif (path[k+1], path[k]) in caps_dict...
This function generates child nodes in a branch-and-bound algorithm by solving an LP relaxation for a given request, creating paths, updating capacities, and computing bounds. It handles both root nodes (no parent) and child nodes, adjusting remaining capacity and propagating constraints. Nodes with infinite bounds are...
def open_node(self, request_id, parent): request = self.amod_prob.requests[request_id] if parent is None: capacity = copy.deepcopy(self.amod_prob.capacity) requests = copy.deepcopy(self.amod_prob.requests) else: parent_node = self.all_bb_nodes[parent] capacity = parent_node.rema...
def find_start_ckpt_end_ckpt(expression,start_checkpoint,end_checkpoint,cur): if(find_indices(expression,'start')): start_checkpoint = cur - 3 if(find_indices(expression, 'end')): end_checkpoint = cur - 3 return start_checkpoint, end_checkpoint def assign_to_disk_variables(variables,t1): ...
The code processes an input file containing expressions, tracks disk variables, logs checkpoints, performs undo recovery, and writes sorted disk variables to an output file. It reads expressions, assigns variables, identifies checkpoints, executes recovery, and outputs results in a specific format.
def main(): disk_variables = {} logs = [] start_checkpoint = -1 end_checkpoint = -1 input_file = sys.argv[1] cur = 1 for expression in open(input_file): sp_expression = expression.split() s_exp = expression.strip() if(cur != 1): if(s_exp == ""): ...
def form_string(command,exp): start = "<"+command+" " mid = start + exp+">" close = mid + "\n" return close def write_to_disk(output_file,memory_variables,disk_variables): var1 = "" var2 = "" sort_var1 = sorted(memory_variables) for i in sort_var1: t1 = i + " " t2 = t1 + ...
This function processes transactions in reverse order, undoing operations by replaying log entries in chunks. It manages memory and disk variables, writes to an output file, and commits transactions once all operations are processed, aiming to revert system state by reapplying transaction logs in reverse.
def undo_logging(x,output_file,transactions,disk_variables,all_transactions,transaction_list): memory_variables = {} completed_transactions = {} variable_and_value = {} varaibles_temp = {} for j in transactions.keys(): completed_transactions[j]=False k=0 present = transaction_list[k...
def assign_to_disk_variables(variables,t1): e_variables = variables[0::2] o_values = variables[1::2] for j in range(len(e_variables)): t1[e_variables[j]] = int(o_values[j]) return t1 def check_if_tran(e): t1 = e.split(" ")[0] t1_1 = t1[0] if(t1_1 == 'T'): return True else...
The main task of the code is to process a transaction log file, parse transactions and operations, track disk variables, and generate an undo log based on a specified parameter x. It reads input from a file, categorizes lines into transactions, handles read/write operations, and writes the resulting undo log to an outp...
def main(): transactions = {} disk_variables = {} all_transactions = {} transaction_list = [] input_file = sys.argv[1] x = int(sys.argv[2]) flag = 0 trans = "" for expression in open(input_file): if flag == 0: exps = expression.split() disk_variables ...
def remove_inval_dup(self, cards): if len(cards) > 0: # Remove invalid values while max(cards) > RankDefines.JOKER.value: cards.remove(max(cards)) while min(cards) < (RankDefines.TWO.value - 1): cards.remove(min(cards)) # Remove duplicates and sort edit_cards = sorted(set(cards)) else: ...
The main task of the code is to determine the poker hand role (e.g., straight, flush) for a 5-card set by processing card suits and ranks after removing invalid cards and duplicates. It checks for JOKER presence, extracts suit/rank lists, sorts them, and calls a subfunction to evaluate the final role.
def check_role_main(self, cards): role = RoleDefines.NO_PAIR.value # Remove invalid values, duplicates and sort edit_cards = self.remove_inval_dup(cards) #print("cards :", edit_cards) # Check the number of cards if len(edit_cards) == 5: # Determine if JOKER is included if edit_cards.count(RankDefin...
def general_info(self): name_xpath_id, birth_date_xpath_id = [1, 5] name_path = f'//*[@id="identificacao"]/div/div/div[3]/div/div/div[2]/div[1]/ul/li[{name_xpath_id}]/text()' name = self.response.xpath(name_path).get().strip() birth_path = f'//*[@id="identificacao"]/div/div/div[3]/div/...
The code aggregates parliamentary member data by collecting general info, expenses, salary, and attendance records into a structured dictionary, including the provided gender.
def run(self, gender): nome, birthday = self.general_info() gastos_parlamentar = self.gastos_par() gastos_gabinete = self.gastos_gab() salario_bruto = self.salario_bruto() presenca = self.presenca() return { "genero": gender, "nome": nome, ...
def handle_compound_glyphs(glyph: dict[str, Any]) -> list[GlyphContour]: all_components = glyph["components"] result: list[GlyphContour] = [] for component in all_components: glyph_name, transformation = component.getComponentInfo() g = glyf_table[glyph_name].__dict__ result.extend(...
The function prepopulates a glyph contour cache by gathering supported glyphs, processing their contours (compound or coordinate-based), generating polylines, calculating font dimensions, and storing results in a cache for efficient later access.
def prepopulate_glyph_cache(): inputs = [] # all the supported glyphs for _, v in CHAR_TO_GLYPH_NAME.items(): inputs.append(v) # add uppercase and lowercase letters for ch in range(65, 91): inputs.append(chr(ch)) inputs.append(chr(ch+32)) for key in inputs: ...
def _process_springer_catalogue(max_lookups=None): global COVERAGE_CACHE, LOOKUPS_PERFORMED current_year = datetime.datetime.now().year years = [str(year) for year in range(2015, current_year + 1)] for year in years: # Perform a simple check before wasting any time on processing catalogu...
The main task of the code is to update coverage statistics by processing a transformative agreements CSV file. It loads cached data, checks for Springer Nature DOIs, fetches missing publication dates from SpringerLink or CSV files, updates persistent caches, compares publication years with agreement periods, and retroa...
def update_coverage_stats(transformative_agreements_file, max_lookups, refetch=True): global COVERAGE_CACHE, JOURNAL_ID_CACHE, PERSISTENT_PUBDATES_CACHE, LOOKUPS_PERFORMED LOOKUPS_PERFORMED = 0 if os.path.isfile(COVERAGE_CACHE_FILE): with open(COVERAGE_CACHE_FILE, "r") as f: try: ...
def _compute_histograms(self,X): """ Compute histograms for input image X Args: X (np.ndarray): Input array with shape (height, width) Returns: p_yx (np.ndarray): Histograms array with shape (height, width, n_bins) """ height = X.shape[0] wi...
The code performs Deterministic Annealing (DA) for image clustering, optimizing cluster assignments via Expectation-Maximization (EM) iterations. It initializes cluster probabilities, iteratively updates them using KL divergence and entropy maximization, perturbs centroids to avoid local minima, and visualizes cluster ...
def _fit_DA(self, X): """ Compute HC for input image X with DA estimation. Args: X (np.ndarray): Input array with shape (height, width) Returns: self """ height = self.p_yx.shape[0] width = self.p_yx.shape[1] self...
def _compute_histograms(self,X): """ Compute histograms for input image X Args: X (np.ndarray): Input array with shape (height, width) Returns: p_yx (np.ndarray): Histograms array with shape (height, width, n_bins) """ height = X.shape[0] wi...
The code computes image centroids using either Maximum a Posteriori (MAP) or Deterministic Annealing (DA) estimation. It first calculates histogram probabilities for input image X, then applies the chosen method to fit model parameters. The function updates the instance's attributes and returns itself, enabling chainin...
def fit(self, X): """Compute HC for input image X Compute centroids. Args: X (np.ndarray): Input array with shape (height, width) Returns: self """ np.random.seed(self.random_state) # com...
def prolog_query(self, thread: PrologThread, query: str): logging.info("Executing " + query) return thread.query(query) def modify_bluetoken_quantity(self, quantity_offset: int): """ Add a positive o negative quantity to be added to the bluetoken quantity :param quantity_offset: The num...
This function handles a player discarding a card by removing it from their hand, adding it to the discard pile, granting a blue token, and potentially removing it from the deck if its properties were unknown. It also shifts remaining cards in the hand and triggers the next card draw for the player, ensuring game state ...
def client_card_discard(self, dataAV: GameData.ServerActionValid, dataGSD: GameData.ServerGameStateData): """ To be used when a player discards a card. What it does is: - Removes the card from the players hand - Adds the card from the discard pile - Adds a blue token - I...
def prolog_query(self, thread: PrologThread, query: str): logging.info("Executing " + query) return thread.query(query) def remove_card_from_deck(self, value: int, color: str): """ To be used to remove a card from the deck. Updates the KB, reducing the quantity of that card of 1. ...
This function handles placing a card on the table by removing it from the player's hand, updating the game state, and managing card knowledge. It checks if the card's properties were unknown to the owner, removing it from the deck if so. It shifts remaining hand cards, updates the table's firework pile, and triggers th...
def client_place_firework(self, dataPMO: GameData.ServerPlayerMoveOk, dataGSD: GameData.ServerGameStateData): """ To be used when a player places a card on the table. What it does is: - Removes the card from the player's hand - Adds the card from the correspondin...
def prolog_query(self, thread: PrologThread, query: str): logging.info("Executing " + query) return thread.query(query) def add_card_to_discard(self, value: int, color: str): """ To be used to add a card to the discard pile. Updates the KB, increasing the quantity of that card of 1. ...
This function handles the consequences of a player playing an incorrect card in a game. It removes the card from the player's hand, discards it, and draws a new card. If the card's properties were unknown to the owner, it's also removed from the deck. Red tokens are incremented by 1. The function adjusts hand indices i...
def client_thunder_strike(self, dataPTS: GameData.ServerPlayerThunderStrike, dataGSD: GameData.ServerGameStateData): """ To be used when a player plays the wrong card. What it does is: - Removes the card from the player's hand - If lotus owner didn't know about the properties of the car...
def calcCornerVertices(self, sid, rid): # Calc prev and next hex corner seed ids. sid_cprev = (sid + NUM_SIDES - 1) % NUM_SIDES sid_cnext = (sid + 1) % NUM_SIDES # Calc |t| for each edge lerp, when starting from |sid|. edgeType_prev = self.edgeTypes[sid_cprev] edgeType ...
The code computes clipped regions for Voronoi diagram seeds by iterating over corners, edges, and interior points. It maps each seed (sid) to its region vertices (vids), handling corner vertices, edge intersections, and interior regions. Regions are adjusted for clockwise orientation, ensuring proper polygon clipping a...
def calcClippedRegions(self): self.sid2region = {} for sid in range(0, NUM_SIDES): rid = self.vor.point_region[sid] if self.debug == sid: print("Calc clip region for corner {0}".format(sid)) vids = self.calcCornerVertices(sid, rid) self.sid...
def initEdgePattern(self, pattern): if len(pattern) != NUM_SIDES: error("Invalid patternL {0}".format(pattern)) # Build mapping from corner to edge pattern. self.corner2edge = {} for eri in EDGE_REGION_INFO: info = EDGE_REGION_INFO[eri] edge = info[0]...
The code initializes edge patterns, sets a random seed (or uses provided one), configures a random number generator, and initializes fixed, interior, and exterior seed structures for further processing.
def init(self): self.initEdgePattern(self.options['pattern']) if self.options['seed'] == None: self.options['seed'] = random.randint(0,5000) print("Seed:", self.options['seed']) self.rng = np.random.RandomState(self.options['seed']) self.initFixedSeeds() sel...
def calcSeedWeight(self, baseSeed): x, y = baseSeed a, b, c, sid0, sid1 = self.calcHexTriWeights(x, y) # Seed is within current triangle, calculate weight. w1 = self.cornerWeight[self.cornerType[sid0]] w2 = self.cornerWeight[self.cornerType[sid1]] w3 = self.cente...
The code analyzes Voronoi regions by mapping regions to seeds, recalculating seed distances, ensuring terrain types are assigned, validating vertex-sharing (3 regions max), and identifying problematic edges, small regions, and closely spaced seeds to refine spatial data integrity.
def analyze(self): # Create a dict to map from region id to seed id. self.rid2sid = {} for sid in range(0, len(self.vor.point_region)): rid = self.vor.point_region[sid] self.rid2sid[rid] = sid # Recalculate the min seed distance for each seed. self.seed2m...
def analyze(self): # Create a dict to map from region id to seed id. self.rid2sid = {} for sid in range(0, len(self.vor.point_region)): rid = self.vor.point_region[sid] self.rid2sid[rid] = sid # Recalculate the min seed distance for each seed. self.seed2m...
This code generates a Voronoi diagram using concatenated seed points from hexagons, edge seeds, interior seeds, and outside seeds. It organizes seed offsets, calculates active seed counts, computes the Voronoi structure, initializes vertex handling for boundary adjustments, and prepares for analysis/visualization. The ...
def generate(self): self.seeds = np.concatenate((self.vHex, self.vEdgeSeeds)) if len(self.vInteriorSeeds) > 0: self.seeds = np.append(self.seeds, self.vInteriorSeeds, 0) self.seeds = np.append(self.seeds, self.vOutsideSeeds, 0) # Record offsets into the seed array. s...
def get_latest(self): """ method to query table and get the latest fraud data""" try: response = self.api_table.query( KeyConditionExpression=Key("id").eq("weather") & Key("sk").begins_with(today), ScanIndexForward=False, Limit=1 ) ...
The code's main task is to determine the type of the input item and call the corresponding data retrieval method (e.g., get_latest, get_24h_devt, etc.), returning the result or None if no matching type is found. It acts as a dispatcher routing requests to specialized data-fetching functions based on the item's type att...
def get_data(self, item): """ check type and call appropriate get method""" if item.type == "latest": return self.get_latest() elif item.type == "24h_devt": return self.get_24h_devt() elif item.type == "24h_average": return self.get_24h_average() ...
def _check_keydown_event(self, event):#additional method is applied to optimise the code if event.key==pg.K_d: self.ship.moving_right=True elif event.key==pg.K_a: self.ship.moving_left=True elif event.key == pg.K_q: s.exit() elif event.key == pg.K_w: ...
The main task of the code is to handle user input events in a Pygame application. It checks for window-close requests, keyboard key presses/releases to control movement, and mouse clicks to trigger actions like starting the game. Events are processed sequentially, with specific methods called based on the event type to...
def check_events(self): for event in pg.event.get(): if event.type==pg.QUIT: s.exit() elif event.type==pg.KEYDOWN:#Moving Ship self._check_keydown_event(event) elif event.type==pg.KEYUP:#Stop moving self...
def _check_fleet_edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): if self.stats.ships_left>0: self.stats.ships_left -=1 self.sb.prep_ships() s...
This function updates alien movement, checks for collisions between the player's ship and aliens, and verifies if any aliens have reached the bottom of the screen, triggering responses like ship damage or game-over conditions.
def _update_aliens(self): self._check_fleet_edges() self.aliens.update() #Alien-ship collision if pg.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() self._check_aliens_bottom()
def check_events(self): for event in pg.event.get(): if event.type==pg.QUIT: s.exit() elif event.type==pg.KEYDOWN:#Moving Ship self._check_keydown_event(event) elif event.type==pg.KEYUP:#Stop moving self...
The `run_game` method serves as the main game loop, continuously checking for keyboard/mouse events, updating game elements (ship, bullets, aliens) if the game is active, and refreshing the screen to render changes in real-time.
def run_game(self):#Main loop for the game while True:#Watch the keyboard or mouse events self.check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self.update_screen()
def events(self): self.keyList = pygame.key.get_pressed() self.eventList = pygame.event.get() for event in self.eventList: if event.type == pygame.QUIT: self.exit() if self.keyList[pygame.K_ESCAPE] and self.pausedWait > 10: self.play() self.pausedWait = 0 self.pausedWait += 1 def update(self, ...
This code runs a main game loop using Pygame, maintaining a target FPS by calculating delta time (dt). It continuously processes events, updates game state with dt, and renders the game window until the loop is exited, then quits Pygame.
def run(self): self.mainLoop = True while self.mainLoop: dt = self.clock.tick(self.FPS) / 1000 self.events() self.update(dt) self.draw(self.win) pygame.quit()
def keytest(data): for key in keys: ctx = AES.new(binascii.unhexlify(key), AES.MODE_ECB) dat = ctx.decrypt(data) if (dat[0:4] == b'\x50\x4B\x03\x04'): print("Found correct AES key: " + key) return binascii.unhexlify(key) elif (dat[0:4] == b'\x41\x56\x42\x30'):...
This code decrypts OPPOENCRYPT!-encrypted files or ZIP archives. It checks the file's magic number, decrypts using AES with a key derived from the file data, extracts ZIP contents, identifies encrypted files, and decrypts them to an 'out' directory. It handles two modes: direct decryption for OPPO files and ZIP archive...
def main(): print("ozipdecrypt 1.1 (c) B.Kerler 2017-2020") filename=args["<filename>"] with open(filename, 'rb') as fr: magic = fr.read(12) if (magic == b"OPPOENCRYPT!"): pk = False elif magic[:2] == b"PK": pk = True else: print("ozip has ...
def print_log(*args): global log_file if log_file is None: return print("".join(map(str,args)), file=log_file) def STRIPZERO(offset, vmlinux, step=4): NOTZERO = INT32 if step==4 else INT for i in range(offset,len(vmlinux),step): if NOTZERO(i, vmlinux): return i def do_to...
This function sets the 'marker_table' entry in the kallsyms dictionary to a given offset, logs the value, adjusts the offset based on symbol count and pointer size, strips leading zeros using the vmlinux file, then calls 'do_token_table' with the updated offset to process token-related data in a kernel symbol table ana...
def do_marker_table(kallsyms, offset, vmlinux): kallsyms['marker_table'] = offset print_log('[+]kallsyms_marker_table = ', hex(offset)) offset += (((kallsyms['numsyms']-1)>>8)+1)*(kallsyms['ptr_size'] // 8) offset = STRIPZERO(offset, vmlinux) do_token_table(kallsyms, offset, vmlinux)
def INT(offset, vmlinux): bytes = kallsyms['ptr_size'] // 8 s = vmlinux[offset:offset+bytes] f = 'I' if bytes==4 else 'Q' (num,) = struct.unpack(f, s) return num def STRIPZERO(offset, vmlinux, step=4): NOTZERO = INT32 if step==4 else INT for i in range(offset,len(vmlinux),step): if N...
The function identifies the 'type_table' offset in the vmlinux file by checking a 256-byte range for a specific 32-bit pattern (0x54545454). If valid, it sets `kallsyms['type_table']` to this offset, skips entries by `ptr_size/8`, strips trailing zeros, and adjusts the offset before calling `do_marker_table`. If invali...
def do_type_table(kallsyms, offset, vmlinux): flag = True for i in range(offset,offset+256*4,4): if INT(i, vmlinux) & ~0x20202020 != 0x54545454: flag = False break if flag: kallsyms['type_table'] = offset while INT(offset, vmlinux): offset += (ka...
def print_log(*args): global log_file if log_file is None: return print("".join(map(str,args)), file=log_file) def ord_compat(ch): try: value = ord(ch) except TypeError: value = ch return value def STRIPZERO(offset, vmlinux, step=4): NOTZERO = INT32 if step==4 else ...
This function processes the name and type tables from the vmlinux file, decompressing symbol names using token tables and populating kallsyms with symbol names and types. It calculates offsets, aligns data, strips zeros, and iterates through symbols to extract and store name-type pairs in kallsyms.
def do_name_table(kallsyms, offset, vmlinux): kallsyms['name_table'] = offset print_log('[+]kallsyms_name_table = ', hex(offset)) for i in range(kallsyms['numsyms']): length = ord_compat(vmlinux[offset]) offset += length+1 while offset%4 != 0: offset += 1 offset = STRIPZERO(...
def new_playlist(self, playlist_name): request = self.youtube.playlists().insert( part="snippet", body={ "snippet": { "title": playlist_name } }, fields="id" ) response = self.__executeRequest(req...
This function adds Spotify tracks to a YouTube playlist by searching for matching videos, avoiding duplicates. It checks if tracks are already in the playlist, searches YouTube if not, adds found videos, and updates track statuses. It prints progress and stats upon completion.
def addToPlaylist(self, spotify_tracks, playlistName): # Checks if the target even exists. if not playlistName in self.playlistMap: self.new_playlist(playlistName) self.get_playlist_videos(self.playlistMap[playlistName]) self.curTarg = playlistName inYoutubePlaylis...
def make_slug(post): """Make URL slug for post.""" date = post['creationTime'].split(' ')[0] summary = '-'.join(w.lower() for w in RE_NONWORD.split(summarize(post, 4)) if w) postid = post['url'].rsplit('/')[-1] return '{}-{}-{}'.format(date, summary, postid) def get_image(post): """Try to get a...
The code processes Google+ posts from a specified directory, filtering public posts, generating HTML files with metadata, and saving them with slugs. It extracts post details, includes images if available, and formats content using a template.
def main(): parser = argparse.ArgumentParser() parser.add_argument('dir') args = parser.parse_args() posts = os.path.join(args.dir, 'Google+ Stream', 'Posts') for dirpath, dirnames, filenames in os.walk(posts): for name in filenames: with open(os.path.join(dirpath, name), encodi...
def currentEdge(obj, board:Board): """ Finds an edge that corresponds to the players current position. Returns: Edge if an edge was found. Otherwise: None """ edge = board.firstEdge if posInRange(edge.start, edge.end, (obj.x, obj.y)): return edge # Move to the next element ...
This function handles player movement during an incursion, validating new positions against the playable area. It manages edge creation/termination when movement direction changes, updates the game board's edge buffers, and adjusts the playable area and score based on captured territory. The logic prevents backward mov...
def handleIncursion(player, board, moveVector, previousMoveVector, startingIncurringEdge): newPlayerPos = Point(player.x + moveVector[0], player.y + moveVector[1]) newPositionIsContainedInArea = board.playableAreaPolygon.contains(newPlayerPos) newPositionIsTouchingArea = board.playableAreaPolygon.touches(ne...
def make_initial_window(self): # Create the layout self.setup_theme() layout_initial = [ [sg.Text("QiX", justification='center', size=(1280, 4), pad=((0, 0), (200, 0)), text_color=self.text_color, background_color=self.bg_color)], [sg.Text("Select D...
The code renders an initial screen with difficulty selection options, handles user interactions (exit or difficulty choice), and returns True if a difficulty is selected, otherwise False.
def render_initial_screen(self): initial_window = self.make_initial_window() # Create an event loop while True: if self.update['update']: initial_window = self.update_initial_window(initial_window) event, values = initial_window.read() # End...
def limitVectorDirection(vector): """ Converts a vector to (+-1,0), (0,+-1), or (0,0). Assumption: The input vector consists of two numerical elements. Returns: A tuple in the form: (val, val) """ if abs(vector[0]) == 1: return (math.copysign(1, vector[0]), 0) elif abs(vector...
The main task of the code is to implement a game loop for a 2D platformer or puzzle game, handling player movement, enemy AI (Sparx and Qix), collision detection, scoring, and game states. It initializes game entities, processes user input, manages incursion mechanics, enforces movement rules, checks for win/loss condi...
def main(): uiLoop = True while uiLoop: fpsclock=pygame.time.Clock() gui = GUI() if gui.render_initial_screen(): level = int(gui.selected_difficulty) else: break print("Creating Board...") board = Board() board.gameStart(level...
def setup_menu(term): print(term.home + term.clear) print(term.white + term.bold + 'wordle-py') print(term.normal + term.mediumseagreen + term.italic + 'by cameron') print(term.move_down(1) + term.white(term.aquamarine3 + term.bold('Guess the word:'))) # Bold doesn't do anything to these char...
The main task of the code is to initialize a terminal interface, set up a menu, position the cursor at coordinates (2,5), and handle user input in cbreak mode for real-time interaction. The `Terminal()` object manages screen operations, `setup_menu()` likely configures the UI, and `handle_input()` processes inputs with...
def main(): term = Terminal() setup_menu(term) # move to starting spot echo(term.move_xy(2, 5)) with term.cbreak(): handle_input(term)
def init_report_backend(self, report_data): """ Initialize the report backend with the report data and extra data. Args: report_data: The report data dict object. """ extra_data = self.report_settings.get('EXTRA_DATA', {}) extra_data['extra_arguments'] = self...
The main task of the code is to initialize a report pipeline by fetching report data using `get_report_generation_data` and request headers, then passing this data to `init_report_backend` to set up the appropriate report backend for processing.
def init_report_pipeline(self, *args, **kwargs): """ Initialize the report pipeline to fetch the report data and then initialize the appropriate report backend. """ self.init_report_backend( report_data=self.get_report_data( report_generation_request_r...
def deal_hand(n): """ n: int >= 0 Returns a random hand containing n lowercase letters. """ hand={} num_vowels = int(math.ceil(n / 3)) hand['*'] = 1 for i in range(1, num_vowels): x = random.choice(VOWELS) hand[x] = hand.get(x, 0) + 1 for i in range(num_vow...
The code allows a user to play a series of hands in a word game. It initializes a total score, prompts for the number of hands, and iterates through each hand. For each hand, it displays the letters, offers a substitution, plays the hand, and optionally replays it. Scores from each hand are accumulated into the total, ...
def play_game(word_list): """ Allow the user to play a series of hands word_list: list of lowercase strings """ total_hands_score = 0 num_of_hands = int(input("Enter total number of hands: ")) while num_of_hands > 0: hand = deal_hand(HAND_SIZE) print("Current hand:"...
def update_text_areas_with_data(self, ip_address, metrics): """Update the text areas with new device metrics.""" for metric, value in metrics.items(): value_label = self.text_areas[ip_address][metric] value_label.configure(text=str(value)) def update_status_label_from_data(self, ...
This function processes device data by either using provided metrics or default values if data is missing. It updates text areas, status labels, and gauge charts with the extracted metrics (Watts, Volts, Amps, etc.) for a given IP address, then schedules the next data update.
def process_device_data(self, ip_address, data): """Process and display device data.""" # Define default metrics to be used if data fetch fails or is incomplete default_metrics = { "Watts": 0, "Volts": 0, "Amps": 0, "WattHours (Total Wh)": 0, ...
def send_device_command(self, ip_address, command, retries=3): """Send a command to the device and return the response, with retries.""" url = f"http://{ip_address}/rpc/{command}?id=0" for attempt in range(retries): try: return requests.get(url, timeout=10) ...
The main task of the code is to fetch device status data from a specified IP address by sending a "Switch.GetStatus" command, process the response if successful (status code 200), and handle network errors by rescheduling the data update after a 5-second delay to retry the operation.
def fetch_data(): try: response = self.send_device_command(ip_address, "Switch.GetStatus") if response.status_code == 200: self.process_device_data(ip_address, response.json()) except requests.RequestException as e: self.handle_...
def setup_tab_main_frame(self, tab): """Create and configure the main frame within a tab.""" main_frame = ctk.CTkFrame(tab) main_frame.grid(row=0, column=0, sticky='nsew') tab.grid_rowconfigure(0, weight=1) tab.grid_columnconfigure(0, weight=1) return main_frame def setup...
The code creates a new tab for a given IP address, initializes its UI components (status labels, text areas, gauges, buttons), and updates data. It structures the tab's layout, sets up interactive elements, and ensures data is populated for the specified IP address.
def create_tab(self, ip_address): """Create a new tab for the given IP address and initialize its content.""" tab = self.tab_view.add(ip_address) main_frame = self.setup_tab_main_frame(tab) self.setup_status_label(ip_address, main_frame) self.setup_text_areas(ip_address, main_fra...
def setup_ui(self): """Set up the user interface of the application.""" self.title("Device Monitoring") self.setup_main_frame() self.setup_tab_view() self.initialize_data_containers() self.configure_dark_mode() def setup_logging(self): """Set up logging for the ap...
The code initializes an object by calling the parent class constructor, setting up the user interface, configuring logging, and reading credentials. These steps prepare the application's UI, logging system, and authentication details during object creation.
def __init__(self): super().__init__() self.setup_ui() self.setup_logging() self.read_credentials()
def draw_node(self): for node in self.graph.Nodes.values(): x = self.my_scale(node.getx(), x=True) y = self.my_scale(node.gety(), y=True) gfxdraw.circle(self.SCREEN, int(x), int(y), 15, (13, 45, 234)) id_surf = self.get_font(10).render(str(node.id), True, "white")...
The main task of the code is to render game elements during gameplay by calling methods to draw nodes, edges, Pokémon, and agents on the screen, updating the visual display while the game is active.
def display_while_playing(self): # display_surf = pygame.Surface((1250, 620)) # display_surf.fill("black") # self.SCREEN.blit(display_surf, (10, 40)) self.draw_node() self.draw_edge() self.draw_pokemon() self.draw_agent()
def parse_args(): parser = ArgumentParser(description= "Tool to generate a raster of pixel-by-pixel surface area from a digital elevation model.") parser.add_argument('in_path', type = str, required = True, help = "Path to raster or directory of rasters to perform the routine on.") parser.add_argument('-o',...
The main task of the code is to process input data into a raster format. It checks if the input is a directory using `args.is_directory`: if true, it processes the directory with `sa_raster_dir`; otherwise, it generates a raster from a single file using `gen_sa_raster`, specifying input and output paths. The function h...
def main(): args = parse_args() if args.is_directory: sa_raster_dir(args.in_path) else: gen_sa_raster(args.in_path, args.out_path)
def ether_type_name(ethertype): if ethertype in ether_type_names: return ether_type_names[ethertype] return "UNKNOWN" def handle_arp(self, packet_in: ofproto_v1_0_parser.OFPPacketIn, eth_header: ethernet.ethernet, arp_header: arp.arp): sel...
This method processes OpenFlow packet-in events by logging packet details, updating MAC-to-port mappings for the switch, and delegating ARP or IPv4 packet handling to specialized functions based on Ethernet type. It extracts network layer information, tracks source MAC addresses, and routes packets for further processi...
def handle_packet_in(self, event: ofp_event.EventOFPPacketIn): packet_in = event.msg # type: ofproto_v1_0_parser.OFPPacketIn datapath_id = packet_in.datapath.id frame = packet.Packet(packet_in.data) eth_header = frame.get_protocol(ethernet.ethernet) self.mac_to_port.setdefault(...
def add_flow(self, datapath, priority, table_id, match, inst, **additional_args): ofproto = datapath.ofproto parser = datapath.ofproto_parser if all(isinstance(action, parser.OFPAction) for action in inst): inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, ...
This function configures OpenFlow switches by adding routing/switching flows based on switch ID. For switch 1, it sets controller forwarding and adds host IP/Ethernet mapping flows. For switch 4, it creates bidirectional flows with specific port matching, Ethernet field modification, TTL decrement, and port output acti...
def switch_features_handler(self, ev): datapath = ev.msg.datapath ofproto = datapath.ofproto parser = datapath.ofproto_parser self.num_links = int(cfg.CONF.num_links) self.num_hosts_per_link = 1 if datapath.id == 1: self.add_flow(datapath, 1, 0, ...
def fmt_ip(self, iN = 0, jN = 0): return "10.0.{}.{}".format(iN, jN) def add_routing_flow(self, datapath, ip, **additional_args): ofproto = datapath.ofproto parser = datapath.ofproto_parser self.add_flow(datapath, 2, 1, parser.OFPMatch( eth_dst=self.fmt_eth()...
This code initializes network flows for routing and switching in an SDN environment. It iterates through links, generates IP addresses, adds corresponding routing and switching flows to the datapath, sends a barrier request to synchronize operations, and marks the experiment as complete by setting execute to False.
def execute_experiment(self, datapath): self.barrier_time = monotonic() for i in range(self.num_link): iN = i + 1 ip = self.fmt_ip(iN) self.add_routing_flow(datapath, ip) self.add_switching_flow(datapath, self.ip_to_eth(ip)) datapath.send_msg(datap...
def get_label(data, n_labels=3, label_type='angle'): if label_type == 'angle': labels = stress_2_angle(np.vstack([x[:,1].T for x in data])) # angle/slope mapped to [0,1] in a time window elif label_type == 'pos': labels = np.vstack([x[:,1].mean() for x in data]) # mean value within the time wind...
This function loads EEG data for a specific subject, normalizes features, splits data into time windows, generates labels (angle, emotion, or combined), reshapes the dataset into (N, window_size, 66), and prepares k-fold cross-validation indices for training/testing.
def load_and_split_dataset(eeg_ft_dir = 'ALIGNED_DATA', split_size=100, subject_num = 5, k=5, label_type='angle', num_classes=3): # choose the subject subject_data_files = glob.glob(os.path.join(eeg_ft_dir, '*.csv')) # sort the files by the index given to them file_name_2_index = lambda file : int(file....
def get_label(data, n_labels=3, label_type='angle'): if label_type == 'angle': labels = stress_2_angle(np.vstack([x[:,1].T for x in data])) # angle/slope mapped to [0,1] in a time window elif label_type == 'pos': labels = np.vstack([x[:,1].mean() for x in data]) # mean value within the time wind...
The code loads EEG data for a specified subject, normalizes features, splits data into chunks, generates labels, extracts EEG features, reshapes data, and prepares cross-validation splits. It processes raw EEG data into normalized feature windows, extracts task-relevant labels, and structures data for k-fold validation...
def load_and_split_dataset(eeg_ft_dir = 'ALIGNED_DATA', split_size=100, subject_num = 5, k=5, label_type='angle', num_classes=3): # choose the subject subject_data_files = glob.glob(os.path.join(eeg_ft_dir, '*.csv')) # sort the files by the index given to them file_name_2_index = lambda file : int(file....
def load_and_split_dataset(eeg_ft_dir = 'ALIGNED_DATA', split_size=100, subject_num = 5, k=5, label_type='angle', num_classes=3): # choose the subject subject_data_files = glob.glob(os.path.join(eeg_ft_dir, '*.csv')) # sort the files by the index given to them file_name_2_index = lambda file : int(file....
The main task of the code is to perform **k-fold cross-validation** for a hybrid model combining an **autoencoder** (for feature extraction) and an **LSTM classifier** (for classification) on EEG data. It processes labeled data (angle, position, or both), trains the encoder and classifier iteratively, evaluates perform...
def main_runner(subject_choice=1, label_type='angle'): # Before we create the models, we will first prepare the data by splitting it and preprocessing it. eeg_feeltrace_dir = 'ALIGNED_DATA' # directory containing *.csv files # hyper parameters window_size = 200 # must be an int in milliseconds subj...
def processCollisionBetweenBallAndWorldANdSetBallPosition(ball): ball.previousPreviousX = ball.previousX ball.previousPreviousY = ball.previousY ball.previousX = ball.x ball.previousY = ball.y futureFineRotation = ball.fineRotation + int(ball.xVelocity / 2) if (futu...
The function simulates physics interactions in a game, handling ball-ground collisions, player movement based on input, and ball-player collisions. It updates positions, checks for collisions, and manages collision states for both players and the ball, returning whether the ball touches the ground.
def physicsEngine(player1, player2, ball, userInputArray): isBallTouchingGround = processCollisionBetweenBallAndWorldANdSetBallPosition(ball) for i in range(2): if (i == 0): player = player1 theOtherPlayer = player2 else: player = player2 theOther...
def plot_points(result,control,runtime): curve_x, curve_y = zip(*result) control_x, control_y = zip(*control) plt.plot(curve_x, curve_y, label='Bezier Curve') plt.plot(control_x, control_y, color='red', label='Control Points') plt.title(f"Bezier Curve - Runtime (overall): {runtime} ms") plt.xla...
This code creates a GUI popup window with options to visualize a Bezier curve: a static graph, animation per iteration, or animation per point. It uses Tkinter to build the interface, displaying buttons that trigger plotting functions with parameters like control points, runtime, and iteration count.
def pop_up_normal_dnc(curve,control_points,runtime_ms,iteration): new_window = tk.Toplevel() new_window.title("Bezier Curve") texts = "Pilih hasil keluaran" label = tk.Label(new_window, text=texts, font=("Arial", 12), justify="center", anchor="center", fg="black", wraplength=500) label.grid(row=0, c...
def input_box(parent, n): control_points = [] iterations = 0 dialog = tk.Toplevel(parent) dialog.title("Bezier Curve Inputs") # STYLING style = ttk.Style() style.configure('InputBox.TFrame', background='#f8c4cc') style.configure('InputBox.TSpinbox', padding=5) style.configure('I...
This function generates a Bezier curve using the DNC (Deep Neural Curve) method with given control points and iterations. It measures execution time, then displays the resulting curve, control points, runtime, and iteration count in a pop-up window.
def normal_dnc(root): control_points, iterations = input_box(root, 3) start_time = time.time() curve = bezier_dnc(control_points,iterations) end_time = time.time() runtime_ms = (end_time-start_time) * 1000 pop_up_normal_dnc(curve,control_points,runtime_ms,iterations)
def _create_help(self, store: Optional[str] = None) -> str: """Create help message. :param store: Either an audio store name or an alias. TODO: Currently the help is created dynamically, but it's actually static. """ # For convenience, get prefix + help. al...
The code parses text commands starting with a specified prefix, processes them into tokens, and returns either a text response or an audio file path. It handles commands like "help," "search," "disconnect," and "random," with the latter selecting a random audio file from weighted stores. If invalid commands or argument...
def parse_message( self, content: str ) -> Tuple[Union[str, None], Union[str, None]]: """Parse text messages. :param content: Message contents as a string. :returns: 2-length tuple, both of which are either string or None. The first entry corresponds to a text message th...
def check_infeasible_action(self, current_item_requested, action, feasible_action): """ Checks whether the models action is infeasible. This means no blood group in stock that could be a match :param current_item_requested: int, the blood group currently in request :param action: int, th...
The code implements a reinforcement learning step function to evaluate an action in a blood matching scenario. It checks action feasibility, match compatibility, stock availability, and correctness, determining the reward and episode termination. The function returns the new state, reward, done flag, and metadata based...
def step(self, action): """ Does the step in the RL algorithm. Checks whether the episode is done and calculates the reward for each step. In this order: - Does an feasible action exists? - Is the match compatible? - Is the match in stock? - Good match :p...
def setupGame(colorList, board): #NOTE DEFINE pieceDicts AND CONSIDER DICTIONARY VS ARRAY """Instantiates all the pieces within a list of dictionaries, one for each color.""" ## place pieces on board GUI() ## instantiate all pieces() pieceDicts = [{}, {}] for i in range(0,2): # sets the prefix...
The code runs a single game, alternating turns between White and Black, handling moves, checking end conditions, and managing game outcomes. It initializes the board, processes player moves, displays results, and allows restarting or quitting via buttons. If the game ends normally, it returns False; if quit, returns Tr...
def game(board): """runs a single game.""" # initializes some variables endOfGame = False currentColor = 0 colorList = ["White", "Black"] previousMessage = "" # starts the game and board board.setGameStart("It is White's move.") pieceDicts = setupGame(colorList, board) wh...
def clear_artifacts(): """ It removes all files with the extension `.pkl` from the `artifacts` directory """ # remove all artifacts recursively with pkl extension for root, dirs, files in os.walk('artifacts', topdown=False): for name in files: if name.endswith('.pkl'): ...
The main task of the code is to execute an experiment on a specified dataset by clearing artifacts, creating directory structures, running experiments with given parameters, analyzing data indices, identifying optimal parameters, and training neural networks using those optimal parameters to achieve a target variance.
def entry(dataset: str = 'APS_SYSTEM_FAILURE', clear: bool = True, limit: int = 100, goal_variance: float = 0.9): if limit is None: limit = None else: limit = int(limit) # get dataset name from input string dataset_name = DatasetName(dataset) # clear artifacts if specified if c...
def list_song(): """Display all the songs from the csv file after the user choose L in the menu""" print(my_song) print("{} songs learned, {} songs still to learn".format(my_song.count_learned(), my_song.count_unlearned())) sort_song(my_song) def add_song(collection): """Add songs function""" t...
The main task of the code is to manage a song database by allowing users to list songs, add new songs, search songs, mark songs as complete, and save changes to a CSV file. The program runs in a loop, displaying a menu for user interaction until the user chooses to quit, at which point data is saved and the program exi...
def main(): """Main function of the program""" print("Songs to Learn 1.0 - by Quan Nguyen") print("{} songs loaded".format(len(my_song.song_list))) print("\n") flag = False while not flag: print("Menu: ") print("L - List songs") print("A - Add new song") print("S...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The function `set_channel` configures a specified voltage on a hardware channel of a board by converting inputs, validating parameters, calculating a DAC code, and sending a POST request to an API. It converts the board serial number, checks for errors in board, channel, and voltage validity, computes the DAC code, ret...
def set_channel(board_sn, channel, voltage): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) errors.error_control(channel_converter(channel)) errors.error_control(check_voltage(voltage)) DAC_code = find_volt_to_bit(board_sn, channel, voltage) errors.err...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The main task of the code is to set a voltage value on a specified channel of a board via an API. It converts input parameters, validates board and channel existence, constructs a JSON payload, sends a POST request to the voltage endpoint, and checks the response status. If successful, it returns the status code; other...
def set_channel_bit(board_sn, channel, DAC_code): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) errors.error_control(channel_converter(channel)) node = get_node(board_sn) errors.error_control(node) data = {"node": node, "channel": channel, "DAC_code":...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The main task of the code is to configure voltage settings across multiple channels (1–128) on a specified hardware board by converting a target voltage to a DAC code, sending HTTP POST requests to set each channel's voltage, and handling errors during validation or communication. It ensures all channels are updated be...
def set_channels(board_sn, voltage): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) errors.error_control(check_voltage(voltage)) node = get_node(board_sn) errors.error_control(node) channels = range(1,129) print("Wait...") for channel in channe...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The main task of the code is to retrieve voltage data from a specified channel on a board by constructing an API request, validating inputs, handling errors, and converting ADC codes to voltage values, returning the rounded result.
def read_channel(board_sn, channel): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) errors.error_control(channel_converter(channel)) node = get_node(board_sn) errors.error_control(node) url ="http://" + IP + "/api/voltage/" + str(node) + "/" + str(chan...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
This function retrieves the ADC code from a specified hardware channel via an API. It validates the board and channel, constructs a URL, sends a GET request, checks for errors in the response, and returns the ADC_code if successful, otherwise returns 0.
def read_channel_adc_code(board_sn, channel): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) errors.error_control(channel_converter(channel)) node = get_node(board_sn) errors.error_control(node) url ="http://" + IP + "/api/voltage/" + str(node) + "/" +...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The code reads voltage data from 128 channels of a specified board by sending HTTP GET requests to a server, handling errors, and converting ADC codes to voltage values. It iterates through each channel, attempts multiple requests per channel, checks for successful responses, and prints channel numbers with correspondi...
def read_channels(board_sn): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) node = get_node(board_sn) errors.error_control(node) channels = range(1,129) for channel in channels: url ="http://" + IP + "/api/voltage/" + str(node) + "/" + str(chan...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The code retrieves reference voltage data from an API endpoint by converting a board serial number to a node identifier, handling errors, and returning the voltage in kilovolts after dividing the API response value by 1000.
def ref_voltage(board_sn): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) node = get_node(board_sn) errors.error_control(node) url ="http://" + IP + "/api/ref_voltage/" + str(node) with requests.get(url) as resp: response = resp.json() ...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The function retrieves the external supply voltage for a given board by querying an API endpoint, converts the board serial number, handles errors, and returns the voltage in kilovolts (kV) after dividing the raw response by 1000. If the API request fails (non-200 status code), it logs an error and returns 0.
def hv_supply_voltage(board_sn): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) node = get_node(board_sn) errors.error_control(node) url ="http://" + IP + "/api/ext_voltage/" + str(node) with requests.get(url) as resp: response = resp.json() ...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The main task of the code is to retrieve temperature data from multiple MEZ modules on a specified board. It converts the board identifier, validates the board and node, queries an API for each MEZ module (1-4), processes ADC codes into temperatures, and returns a dictionary of rounded temperatures. Error handling chec...
def mez_temp(board_sn): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) node = get_node(board_sn) errors.error_control(node) mez_nums = range(1,5) mez_temps = {} for mez_num in mez_nums: url ="http://" + IP + "/api/mez_temp/" + str(node) + "...
def convert_node_to_board_sn(node): if node<NODE_ID_MAX: data = parse_yaml(PATH_YAML) errors.error_control(data) for fnode in data["Nodes"]: if node == fnode["NodeID"]: return fnode["BoardSN"] return -6 return node def check_boards(board_sn): board...
The main task of the code is to reset a board by sending an HTTP GET request to a specific API endpoint after validating the board's node information. It converts the board serial number to a node identifier, checks for errors, constructs the reset URL, and handles the response. If the reset is successful, it prints a ...
def reset(board_sn): board_sn = convert_node_to_board_sn(board_sn) errors.error_control(check_boards(board_sn)) node = get_node(board_sn) errors.error_control(node) url ="http://" + IP + "/api/reset/" + str(node) with requests.get(url) as resp: response = resp.json() if "error" i...
def check_user_driving_ride(rideNo): """ Double check the current user is the one driving the ride (preventing malicious input from people changing URLs) Return true if the current user is who is driving this ride """ #means the user isn't logged in and should not be able to perform this functi...
The main task of the code is to allow a logged-in user to edit or cancel a ride they are currently driving. It retrieves the ride details, validates form inputs, and either updates the ride information, deletes it if canceled, or redirects to appropriate pages based on form submission outcomes. The function ensures onl...
def edit(): """ Edits a ride that the user is already driving """ rideNo=request.args.get('rideNo') editRideForm=forms.EditRideFactory() ride=None userDrivingRide=check_user_driving_ride(rideNo) #only perform the following if the logged in user is driving this ride if userDrivingRid...
def get_actions(self): empty_location = self._get_empty_location() actions = [] if empty_location[0] > 0: actions += ['u'] if empty_location[0] < 2: actions += ['d'] if empty_location[1] > 0: actions += ['l'] if empty_location[1] < 2: ...
This code applies a specified action to a puzzle state by validating the action, creating a new state copy, determining the empty tile's position, updating its position based on the action, swapping tiles, and returning the modified state.
def apply_action(self, a): valid_actions = self.get_actions() assert a in valid_actions new_state = self.copy() pos1 = self._get_empty_location() pos2 = [pos1[0], pos1[1]] if a == 'u': pos2[0] -= 1 elif a == 'd': pos2[0] += 1 elif...
def generate_all_models(symbols): """Generate all possible models based on a list of propositional symbols.""" return list(product([True, False], repeat=len(symbols))) def evaluate_knowledge_base(kb, model): """Check if the Knowledge Base (KB) is true in a model.""" for fact in kb.facts: if not ...
This function checks if a query is logically entailed by a Horn knowledge base using truth table evaluation. It generates all possible truth assignments for the KB symbols, counts models that satisfy the KB, and verifies if all such models also satisfy the query. If any valid KB model fails to entail the query, it retu...
def truth_table_check_hornkb(kb, query): """Main evaluation function for the Knowledge Base.""" count = 0 symbols = kb.get_all_symbols() true_models = [] if query not in symbols: return ("NO", count) entailed = True models = generate_all_models(symbols) for model in models...
def signal_input(file:set) -> list: signal = [] with open(file) as f: # return f.readlines() pair = [] for line in f: if line == '\n': signal.append(pair) pair = [] else: pair.append(ast.literal_eval(line.strip())) ...
(The code solves two parts of a problem involving signal packet ordering. Part 1 checks if pairs of packets are in correct order, sums indices of valid pairs. Part 2 sorts all packets (plus added [[2]], [[6]]) and calculates the product of positions (+1) of the distress signals. The main tasks are: 1) validate packet o...
def main(): signal = signal_input('./data/d13.txt') ## Part 1 correct_order = [] for idx, line in enumerate(signal): l, r = line # print(f'------------') # print(f'SIGNAL : {idx}') # print(l, r) order = recurse_compare(l,r) correct_order.append(order) ...
def _get_obs(self): return np.array([self.state[obs] for obs in self.observations]) def check_done(self): if np.sqrt((self.state['x'] - self.goal['x'])**2 + (self.state['y'] - self.goal['y'])**2) <= self.successThreshold: return 1 elif self.time > self.maxTime: return 1 ...
The main task of the code is to compute the next observation by applying the action to the current state using matrix operations, determine the reward and termination status, update the environment state, and return these values for reinforcement learning training. It models dynamic system transitions, tracks state his...
def step(self, action): self.action = action state = self._get_obs() self.history.append(state) observation = np.matmul(self.A, np.squeeze(state)) +\ np.matmul(self.B, np.squeeze(action)) terminated = self.check_done() reward = self.get_reward() self.t...
def pos_to_pixel(self, pos): return (int(pos[0] * self.factor + self.window_size / 2), -int(pos[1] * self.factor - self.window_size / 2)) def multiple_small_polytope(self, canvas): [p1r1, p2r1, p3r1] = self.vertices1 [p1r3, p2r3, p3r3] = self.vertices2 pygame.draw.polyg...
The main task of the code is to render a visual frame of a mouse navigation environment using Pygame. It initializes rendering components, draws obstacles, the goal, the mouse's initial position, and its movement history, and handles both human-display and RGB-array output modes. The function ensures consistent framera...
def _render_frame(self): if self.window is None and self.render_mode == "human": pygame.init() pygame.display.init() pygame.display.set_caption('MouseCheese') self.window = pygame.display.set_mode( (self.window_size, self.window_size)) if s...
def launchScreen(window): window.setBackground(color_rgb(10,10,70)) text = Text(Point(int(w/2),int(h/5)),"Tic Tac Toe") text.setTextColor(color_rgb(230,230,80)) text.setSize(25) text.setFace('helvetica') text.draw(window) text2 = Text(Point(int(w/2),int(h*1.5/5)),"by A. Doige") text2.setTextColor(color_rgb(230,...
The code defines a 'menu' function that initializes a game by displaying a launch screen, selecting a shape, determining the starting player, and launching the game. It uses global variables to store the chosen shape and starting player, then calls the 'game' function to begin gameplay.
def menu(win): launchScreen(win) global shapE shapE = pickShape(win) global startEr startEr = whoStarts(win) game(win)
def menu(win): launchScreen(win) global shapE shapE = pickShape(win) global startEr startEr = whoStarts(win) game(win) def backLoop(window): window.getMouse() cleanWindow(window) window.setBackground(color_rgb(5,5,40)) text = Text(Point(int(w/2),int(h/5)),"") text.setTextColor(color_rgb(230,230,80)) text.se...
The main task of the code is to initialize a graphical window for a Tic-Tac-Toe game ("TATETI"), set global variables for window dimensions and game elements, and manage the game loop. It calls a menu function, processes user decisions (rematch, restart, or exit), and ensures proper cleanup of drawn shapes via a list. ...
def main(): win = GraphWin("TATETI",501,501) global h h = win.height global w w = win.width global xSide xSide = int(w/3) global ySide ySide = int(h/3) global drawnShapes drawnShapes = [] # Every new shape that will not immediatly be undrawn has to be added to this list so the cleanScreen() can work menu(...