dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def over(self, player, opponent, turn): if self.end(self.possible_moves(player, opponent)): if self.end(self.possible_moves(player, opponent)) and self.end(self.possible_moves(opponent, player)): if player.score() > opponent.score(): return True, turn, "No more mo...
This code implements a turn-based game loop where a human player and an AI alternate turns. It checks for game-ending conditions, updates the board state, displays scores, and handles game conclusion by printing the winner or tie result. The loop continues until the game ends, with the AI making moves using a provided ...
def play(self, player, opponent, hash_map): turn = "black" board = Board(player, opponent) while True: if turn == "black": end, winner, type = self.over(player, opponent, turn) if end: print('Game is OVER') if wi...
def parse_args() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description='Fetch and unpack a Rust source archive') exclusive_group = parser.add_mutually_exclusive_group() exclusive_group.add_argument("-b", "--beta", dest="build_type", action="store_const", default='', const='beta', help="fet...
The main task of the code is to automate a workflow involving Git branch setup, repository cleaning, fetching version-specific archives, and committing changes based on command-line arguments and build configurations, ensuring structured version control and artifact management.
def main() -> None: args = parse_args() rust_version = args.rust_version + get_extra_tag(args.build_type) branch_name = BRANCH_NAME % rust_version setup_git_branch(branch_name, args.overwrite) clean_repository() fetch_archive(args.build_type, rust_version) commit_files(branch_name, rust_version)...
def host_config(target: str, macosx_flags: str, linker_flags: str) -> str: cc_wrapper_name = OUT_PATH_WRAPPERS / ('clang-%s' % target) cxx_wrapper_name = OUT_PATH_WRAPPERS / ('clang++-%s' % target) linker_wrapper_name = OUT_PATH_WRAPPERS / ('linker-%s' % target) instantiate_template_exec( ...
The main task of the code is to generate a `config.toml` file and compiler wrappers for Rust builds. It computes platform-specific compiler/linker flags, adjusts environment variables (e.g., `PATH`, `LIBRARY_PATH`), handles LTO settings, and instantiates configuration templates with host/device-specific flags. This ens...
def configure(args: argparse.ArgumentParser, env: dict[str, str]): """Generates config.toml and compiler wrapers for the rustc build.""" # # Compute compiler/linker flags # macosx_flags: str = '' host_ld_selector: str = '-fuse-ld=lld' if build_platform.is_linux() else '' host...
def learn_file_words(input_file_path): """ *Opens a file *For each line: *Uses regex to replace all characters other than letters, apostrophes, and hyphens with a space *Splits the line into space-separated tokens *Uses isalpha to find the tokens that consist only of letters ...
The code defines a main function that processes user commands in a loop, executing actions like learning/forgetting words, exploring word relationships, or finding word ladders based on input. It handles commands such as LEARNFILE (loading word files), LEARN/FORGET (adding/removing words), EXPLORE (querying word detail...
def main(): """Takes user input and executes it until receiving the QUIT command.""" while True: user_input = input(">> ") tokenized_user_input = user_input.split() first_word = tokenized_user_input[0] command = first_word.upper() if command == "QUIT": print(...
def cleanup2(plane): #function for cleaning up whitespace and non-alpha-numeric characters plane = plane.replace("-", "") plane = plane.replace(" ", "") plane = plane.lower() plane = plane.replace("\n", "") plane = plane.replace("(", "") plane = plane.replace("...
The code searches for an aircraft match based on a partial name input. It cleans the input, checks for trivial cases, compares against bomber substrings, calculates similarity scores using multiple algorithms (e.g., edit distance, gestalt), filters by country prefixes, sorts results, and returns the best match (shortes...
def search2(plane): plane = cleanup2(plane) if len(plane) <= 2 and plane != "j2" and plane != "j4" and plane != "j6" and plane != "j7" and plane != "t2": return "No match" for plane1 in bombers: substring = cleanup2(plane1)[:len(plane)] if plane in substring: retur...
def cleanup2(plane): #function for cleaning up whitespace and non-alpha-numeric characters plane = plane.replace("-", "") plane = plane.replace(" ", "") plane = plane.lower() plane = plane.replace("\n", "") plane = plane.replace("(", "") plane = plane.replace("...
The code searches for a plane in a database by comparing the input (after cleanup) against aircraft names, using similarity metrics (custom functions like `isSim`, `defSim`, `gestalt`). It distinguishes between foreign/non-foreign planes, applies different matching logic, and returns the best match based on similarity ...
def search2(plane): plane = cleanup2(plane) if len(plane) <= 2: return "No match" for plane1 in bombers: substring = cleanup2(plane1)[:len(plane)] if plane in substring: return "Bombers are useless" similarities = {} #di...
def GPIBActivate(): SendMsg('++addr 15') def SendMsg(message): return comm.SendSerialCommandAndGetResponse(message) def SetVoltage(voltage): GPIBActivate() val = str(voltage) SendMsg('B'+val+',0,0X')
The main task of the code is to disable an output device by activating the GPIB interface, sending a shutdown command ('N0X'), and setting the voltage to 0.0 to turn off the output.
def TurnOutputOff(): GPIBActivate() SendMsg('N0X') SetVoltage(0.0)
def shuffle_cards(self) -> None: """Construct pinochle deck 2 of each suit/value card excluding none, then shuffle deck.""" self.deck = [ Card(suit, value) for value in Values for suit in Suits for _ in range(2) if suit != Suits.NONE and value ...
The `play_round` method orchestrates a complete round of the pinochle game by sequentially executing key phases: shuffling the deck, dealing cards to players, conducting a bidding round, scoring hands, playing tricks, and cleaning up after the round. This ensures all necessary steps for a single game round are performe...
def play_round(self) -> None: """Execute full round of pinochle.""" self.shuffle_cards() self.deal_cards() self.bid_round() self.score_hands() self.tricks() self.cleanup_round()
def make_mask(self, centroids): cmax = np.max(centroids) size = cmax + self.pad mask = np.zeros((size, size)) return mask def extract_features(self, mask, centroids, messages = True): # make mask for pattern if messages: print("\nGenerating mask.....
The function predicts dipole values using a trained model on processed features of centroids, saves results as a CSV with centroid coordinates, features, and predictions, and optionally generates plots. It scales input features, reshapes predictions, and combines data into a structured DataFrame for output.
def predict_dipole(self, messages = True): mask = self.make_mask(self.centroids) feats = self.extract_features(mask, self.centroids) X = self.scaler.transform(feats) if messages: print("Making predictions..") preds = self.model.predict(X) preds = preds.re...
def load_medical_record_subsentences(medical_record): record = string_to_record_nonlinewise(medical_record) sentences = [] curSentence = [] for word in record: word = word.lower() if len(word) < 1: continue curSentence.append(word) if end_of_point(word): sentences.append(" ".join(curSenten...
The code extracts phenotypes from medical records by matching text against HPO (Human Phenotype Ontology) synonyms, filtering by term occurrences and flags (e.g., negative, family history), and returns structured results listing HPO IDs, names, occurrence counts, earliest mentions, and example sentences.
def extract_phenotypes(record, names, hpo_syn_file=HPO_SYN_MAP_FILE): safe_ID_to_lines = defaultdict(set) medical_record = load_medical_record_subsentences(record) medical_record_subsentences = [] medical_record_words = [] medical_record_flags = [] subsent_to_sentence = [] for subsents in medical_record: ...
def preprocess_image(self, raw_bgr_image): """ description: Convert BGR image to RGB, resize and pad it to target size, normalize to [0,1], transform to NCHW format. param: input_image_path: str, image path return: image: ...
The code performs batch inference on raw images using a GPU-accelerated model. It preprocesses images, transfers data to the GPU, executes the model, retrieves predictions, synchronizes results, and applies post-processing to draw bounding boxes with labels on the original images, returning annotated images and inferen...
def infer(self, raw_image_generator): threading.Thread.__init__(self) # Make self the active context, pushing it on top of the context stack. self.ctx.push() # Restore stream = self.stream context = self.context engine = self.engine host_inputs = self.host...
def setAction(self, action, agent_topics): # action_list = [self.turn_left_f, self.turn_left_h, self.turn_left_m, self.turn_left_l, self.turn_right_f, self.turn_right_h, self.turn_right_m, self.turn_right_l, self.stop] pid_list = [self.pid, self.pid_2, self.pid_3] input_list = [self.goa...
The code processes agent actions to compute next states, rewards, and termination flags. It sets actions, retrieves environment states, calculates rewards, and returns next_states, rewards, dones, and next_pxes as numpy arrays for reinforcement learning step updates.
def step(self, actions, agent_topics): self.setAction(actions, agent_topics) # next_states = [0 for _ in range(self.num_agents)] # rewards = [0 for _ in range(self.num_agents)] # dones = [0 for _ in range(self.num_agents)] # next_pxes = [0 for _ in range(self.n...
def setParam(self, param, val): self._params[param] = val def traceField(self, name, value): if value: self._traceLog.append(str(name) + "=" + repr(value)) def sendRequest(self, httpMethod, domain, path, params, token, secret=None, useHTTPS=False, timeout=None, userKey=None): params...
The main task of the code is to synchronously send an API request by configuring the domain, path, parameters, and authentication, handling timeouts, validating SSL certificates, and returning structured responses or errors. It constructs the request URL, sets default parameters, checks required credentials, sends the ...
def send(self, timeout=None): """Send the request synchronously""" if self._method[0:1] == "/": self._method = self._method[1:] if self._method.find(".") == -1: self._domain = "socialize." + self._apiDomain self._path = "/socialize." + self._method e...
def remove_background(project_name, input_image): app_settings = get_app_settings() if not input_image.startswith("http"): input_image = open(input_image, "rb") os.environ["REPLICATE_API_TOKEN"] = app_settings["replicate_com_api_key"] model = replicate.models.get("pollinations/modnet") ver...
The function `execute_image_edit` processes image editing tasks by applying masks (automated/manual/previous/inverted) and replacing backgrounds or using inpainting. It handles various mask selection methods, modifies images based on replacement type ("Replace With Image" or "Inpainting"), and uploads the edited image....
def execute_image_edit(type_of_mask_selection, type_of_mask_replacement, project_name, background_image, editing_image, prompt, negative_prompt, width, height, layer, index_of_current_item): if type_of_mask_selection == "Automated Background Selection": removed_background = remove_background(project_name, ...
def prompt_model_stability(project_name, index_of_current_item, timing_details, input_image): app_settings = get_app_settings() project_settings = get_project_settings(project_name) os.environ["REPLICATE_API_TOKEN"] = app_settings["replicate_com_api_key"] index_of_current_item = int(index_of_current_it...
The main task of the code is to generate a stylized image by selecting a model from timing_details, extracting its parameters, and passing them to the corresponding processing function. It returns the output image URL based on the chosen model (e.g., Stable Diffusion, Depth2Img, Pix2Pix, etc.) and input source image.
def restyle_images(index_of_current_item, project_name, project_settings, timing_details, source_image): index_of_current_item = int(index_of_current_item) model_name = timing_details[index_of_current_item]["model_id"] strength = timing_details[index_of_current_item]["strength"] app_settings = get_app_...
def get_model_details(model_name): with open('models.csv', 'r') as f: reader = csv.reader(f) for row in reader: if row[0] == model_name: model_details = { 'name': row[0], 'id': row[1], 'keyword': row[2], ...
The function triggers an image restyling process by updating project settings with provided parameters, selecting a source image based on the project stage, generating a new image variant using a specified pipeline (e.g., Mystique or restyle_images), and optionally promoting the newly generated variant as the primary i...
def trigger_restyling_process(timing_details, project_name, index_of_current_item, model, prompt, strength, custom_pipeline, negative_prompt, guidance_scale, seed, num_inference_steps, which_stage_to_run_on, promote_new_generation, project_settings, custom_models, adapter_type): get_model_details(model) prompt ...
def add_joint_res(res_arr,to_add,size,is_pred = False): for indx in range(size): conv_arr = [] pred_lbl = [] pred_lbl.append(to_add[0][indx]) pred_lbl.append(to_add[1][indx]) pred_lbl.append(to_add[2][indx]) #print(pred_lbl) for elm in pred_lbl: val = elm.item() if is_pred: val,_ = __pred_p...
The main task of the code is to train a multi-model architecture with three components (code, sequence, training models) using binary cross-entropy loss. It processes batches, computes individual and joint losses, performs backpropagation, tracks training/validation accuracies/losses, and saves model checkpoints per ep...
def train(model,training_generator,validation_generator,log,loss_type = ""): model.to(device) model.train() losses = [] trn_accs = [] trn_rocs = [] trn_hmm_losses = [] eval_accs = [] eval_rocs = [] eval_losses = [] train_acc = 0 regularization = torch.tensor(0.).to(device) optimizer = optim.Adam(mode...
def read_tracks(in_file, gpx_trk): track_number = 1 try: for trk_data in gpx_trk: read_track(in_file, trk_data, track_number) track_number += 1 print("done") except AttributeError: track_number = 0 read_track(in_file, gpx_trk, track_number) def read_wa...
The function reads a GPX file from a specified directory, parses its XML content, and processes tracks, waypoints, and routes by calling respective functions to handle each data type.
def read_in(directory, in_file): full_file = f'{directory}{in_file}' with open(full_file) as fd: gpx = xmltodict.parse(fd.read()) if gpx['gpx'].get('trk'): read_tracks(in_file, gpx['gpx']['trk']) if gpx['gpx'].get('wpt'): read_waypoint(in_file, gpx['gpx']['wpt'])...
def compute_edges(l): i, j, edges = 0, 0, [] for dir, n in l: edges.append((i, j, dir, n)) i, j = move(i, j, dir, n) return edges def move(i, j, dir, n_steps=1): d = { 'U': (i - n_steps, j), 'D': (i + n_steps, j), 'R': (i, j + n_steps), 'L': (i, j - n_step...
The code optimizes the size of a digital structure by transforming edge-based instructions into weighted operations. It calculates movement distances between sorted coordinates, constructs weight maps based on gaps between indices, and applies these to compute an optimized layout size via the full_dig_size function.
def full_dig_size_opti(l): edges = compute_edges(l) i_vals, j_vals = list(sorted(set(i for i, _, _, _ in edges))), list(sorted(set(j for _, j, _, _ in edges))) new_instructions = [] for i, j, dir, n in edges: ni, nj = move(i, j, dir, n) start_loc = (i_vals.index(i)) if dir in ('U', 'D') ...
def test1(): fp = open("testcase01.txt", 'r') right, count = runTest(fp) fp.close() cur_total = round(right/count * 5, 2) global TOTAL TOTAL += cur_total return f"Testcase 01: {cur_total} / 5" def test2(): fp = open("testcase02.txt", 'r') right, count = runTest(fp) fp.close() ...
The main task of the code is to execute ten test functions (test1 to test10), print their individual results, and display the total score stored in the global variable TOTAL. It serves as a testing framework to evaluate and aggregate outcomes from multiple test cases.
def main(): print(test1()) print(test2()) print(test3()) print(test4()) print(test5()) print(test6()) print(test7()) print(test8()) print(test9()) print(test10()) print ("\n\nTotal Score: ", TOTAL )
def pair_first_round(self): sorted_players = self.order_players(self.players) S1count = len(self.players) // 2 for index in range(S1count): self.pairs.append( [sorted_players[index], sorted_players[S1count+index]]) def pair_even_round(self): sorted_brackets_k...
The main task of the code is to validate player inputs (non-zero and even count), organize players into score-based brackets, and generate pairings for the next tournament round using specific pairing logic depending on the round number, returning the resulting match pairs.
def make_it(self): if len(self.players) == 0: raise ValueError('No players') if len(self.players) % 2 == 1: raise ValueError('Odd number of players') self.assign_bye() brackets = {} for player in self.players: if player['score'] not in brack...
def is_triangle(sides): a, b, c = sides if a * b * c <= 0: return False return a + b >= c and b + c >= a and a + c >= b def equilateral(sides): return is_triangle(sides) and len(set(sides)) == 1 def isosceles(sides): return is_triangle(sides) and len(set(sides)) == 2 or equilateral(sides)
The code checks if a set of three side lengths forms a valid scalene triangle by verifying they form a triangle, are not equilateral, and are not isosceles.
def scalene(sides): return is_triangle(sides) and not equilateral(sides) and not (isosceles(sides))
def find_starts(config, data): """ Find the starts of interesting activity in the signal. The result is a list of indices where interesting activity begins, as well as the trigger signal and its average. """ trigger = butter_bandpass_filter( data, config.bandpass_lower, config.bandpass...
The code processes radar data by loading complex-valued signals, applying filtering, detecting trigger events, aligning traces via cross-correlation, and extracting valid traces for analysis. It loads raw data, cuts transient segments, identifies trace starts, filters signals, correlates traces with templates, shifts a...
def main(): capture_file = 'data/raw__1.npy' global config config = obj(config) with open(capture_file) as f: data = np.fromfile(f, dtype=np.complex64) data = np.absolute(data) # cut usless transient data = data[int(config.drop_start * config.sampling_rate):] trace_starts, trig...
def retrieve_password(): # ~THIS IS TERRIBLE SECURITY, DON'T EVER DO THIS~ with open("/home/user/Desktop/Simple-Python-HTTP-Server/local_keys/openssl_passphrase.txt","r") as passfd: print("Retreiving password...") password = passfd.readlines()[0].strip("\n") #print("Test...the password is: %...
The main task of the code is to retrieve a password, test a connection using it, and run a loop. If the connection is refused, it prints an error message. Finally, it exits with "Quitting!".
def main(): try: password = retrieve_password() test_connection(password) loop() except ConnectionRefusedError: print("No connection found to server!") print("Quitting!")
def upload_start(self, build_id, file, artifact_type=None): '''Start a multipart upload. Returns the upload_id and upload_name''' url = f'{self.api_gw_url}/uploads/{build_id}/start-upload' upload_name = os.path.basename(file) # mime type upload_type = mimetypes.guess_type(file...
The main task of the code is to perform a multipart upload of a file by splitting it into parts, uploading each part sequentially with generated URLs, collecting ETags for each part, and finalizing the upload. It handles errors by aborting the process if interrupted, ensuring no partial uploads remain. The function log...
def multipart_upload(self, build_id, file, artifact_type=None): '''Multipart upload method''' LOGGER.info(f'Uploading application {file}') upload_id = upload_name = None try: upload_id, upload_name = self.upload_start(build_id, file, artifact_type) # Split file...
def protect_start(self, build_id): '''Initiate build protection''' url = f'{self.api_gw_url}/builds/{build_id}' params = {} params['cmd'] = 'protect' self.ensure_authenticated() response = ApsRequest.patch(url, headers=self.headers, params=params) LOGGER.debug(f...
The function `protect_build` initiates a build protection process for a given `build_id`, starts the protection, and continuously polls its status until completion. It logs progress, handles errors by deleting the build if protection fails, and returns `True` if the build reaches the 'protect_done' state, otherwise `Fa...
def protect_build(self, build_id): '''High level protect build command. This operation does the following - protect_start - poll protection state (protect_get_status) until protection is completed''' LOGGER.info(f'Starting protection for build {build_id}') # Start prote...
def create_build(self, application_id=None, subscription_type=None): '''Create a new build''' url = f'{self.api_gw_url}/builds' # Create a new build body = {} if application_id: body['applicationId'] = application_id if subscription_type: body['su...
The main task of the code is to add a new build by creating it, setting metadata (if enabled), and uploading a binary file if conditions are met. It handles errors by returning responses or deleting failed builds. The function checks if the application ID is provided and whether upload is enabled before proceeding with...
def add_build(self, file, application_id=None, set_metadata=True, upload=True, subscription_type=None): '''Add a new build''' response = self.create_build(application_id, subscription_type) if 'errorMessage' in response: return response build_id = response['id'] if ...
def get_parents(member_id): member_rec = get_member_rec(member_id) pa = ma = pa2 = ma2 = None if member_rec.father2_id: pa = member_rec.father_id pa2 = member_rec.father2_id elif member_rec.mother2_id: ma = member_rec.mother_id ma2 = member_rec.mother2_id else: ...
The function `get_family_connections` retrieves and filters family relationships (parents, grandparents, siblings, spouses, children) for a given member, hiding non-visible entries unless the user is an admin. It constructs a structured `Storage` object with these connections and a flag indicating if any family relatio...
def get_family_connections(member_id): auth, VIS_NEVER = inject('auth', 'VIS_NEVER') ###debugging only! get_all_relatives(member_id) #fc = get_all_family_connections(member_id) #path = fc.find_path(493) parents = get_parents(member_id) for p in ['pa', 'ma', 'pa2', 'ma2']: if parents...
def get_parent_list(member_id): parents = get_parents(member_id) result = [] for p in parents: result.append(parents[p]) return result def get_siblings(member_id): parents = get_parents(member_id) if not parents: return [] db, VIS_NEVER = inject('db', 'VIS_NEVER') pa, ma ...
The code retrieves all first-degree relatives of a given member by collecting IDs from parents, siblings, spouses, and children using set operations to avoid duplicates.
def get_all_first_degree_relatives(self, member_id): result = set([rec.id for rec in get_parent_list(member_id)]) result |= set([rec.id for rec in get_siblings(member_id)]) result |= set([rec.id for rec in get_spouses(member_id)]) result |= set([rec.id for rec in get_children(member_id)]...
def upkeep_phase(self) -> None: print(f"<** The {self.current_ship.get_name()} - TURN {self.turn_count} **>\n") self.log_stats() def main_phase_1(self): print(f"<** The {self.current_ship.get_name()} - Main Phase 1 **>\n") def combat_phase(self): print(f"<** The {self.current_ship.get_na...
The code orchestrates a game turn by sequentially executing phases: upkeep, main phase 1, combat, main phase 2, and cleanup. Each method handles specific turn tasks, ensuring structured progression through game mechanics like resource management, player actions, battle resolution, and state resets.
def start_turn(self) -> None: self.upkeep_phase() self.main_phase_1() self.combat_phase() self.main_phase_2() self.clean_up_phase()
def check_if_game_over(self) -> bool: ships_remaining = [] for ship in self.ship_list: if not ship.sunk(): ships_remaining.append(ship) if len(ships_remaining) == 1: print("<$$$ EXP Gains $$$>") for ship in self.ship_list: ship....
The code manages a battle loop by repeatedly sorting ships by speed, determining action order, incrementing the turn count, and processing each active ship's turn until the game ends. It checks for game over conditions, updates ship statuses, and prints turn progression.
def start_battle(self) -> None: while not self.check_if_game_over(): self.sort_ships_list_on_spd() self.get_action_order() self.turn_count += 1 for ship in self.get_ships_not_sunk(): self.current_ship = ship self.other_ships = self....
def s_box_lookup(byte: int, s_box: list[list[int]] = AES_S_BOX) -> int: """Look up byte in specified substitution box""" # shift first 4 bits of byte over, leaving us with just the first 4 bytes row = byte >> 4 # set the first 4 bytes to 0 by and-ing them with 0, leaving just the last 4 bytes ...
This function performs one round of AES encryption on a grid. It applies SubBytes (S-box substitution), ShiftRows (row rotation), MixColumns (column mixing, skipped if final), and AddRoundKey operations to the grid using the provided round key, returning the transformed grid.
def encrypt_grid_round(round_key: list[list[int]], grid: list[list[int]], final = False) -> list[list[int]]: grid = [[s_box_lookup(val) for val in row] for row in grid] # SubBytes grid = [rotate_row_left(grid[i], i) for i in range(BOX_SIDE)] # ShiftRows if not final: grid = mix_columns(grid) # MixColumns ...
def add_sub_key(block_grid: list[list[int]], key_grid: list[list[int]]) -> list[list[int]]: return [[block_grid[i][j] ^ key_grid[i][j] for j in range(BOX_SIDE)] for i in range(BOX_SIDE)] def mix_columns(grid: list[list[int]]) -> list[list[int]]: new_grid = [[] for i in range(BOX_SIDE)] for i in range(B...
This function performs one round of AES decryption on a grid. It applies AddRoundKey, MixColumns (if not the final round), ShiftRows (rotating rows), and SubBytes using the inverse S-box to transform the grid state.
def decrypt_grid_round(round_key: list[list[int]], grid: list[list[int]], final = False) -> list[list[int]]: grid = add_sub_key(grid, round_key) # AddRoundKey for i in range((not final) and 3): grid = mix_columns(grid) # MixColumns grid = [rotate_row_left(grid[i], -1 * i) for i in range(BOX_SIDE)] # Sh...
def break_into_grids(s: bytes, should_pad: bool = True) -> list[list[list[int]]]: """Turn bytes into list of 4x4 grids in column major order""" return [make_grid(s[i:i+BOX_AREA], should_pad) for i in range(0, len(s), BOX_AREA)] def expand_key(key: bytes, total_rounds: int) -> list[list[int]]: rcon = make_ro...
This function encrypts data using a block cipher algorithm by dividing the input into grids, expanding the key into multiple rounds, applying round-specific encryption steps with subkeys, and flattening the processed grids into a byte stream for output.
def encrypt(key: bytes, data: bytes) -> bytes: grids = break_into_grids(data, should_pad=True) expanded_key = expand_key(key, ROUNDS+1) round_key = extract_key_for_round(expanded_key, 0) grids = [add_sub_key(grid, round_key) for grid in grids] for round in range(1, ROUNDS+1): ro...
def break_into_grids(s: bytes, should_pad: bool = True) -> list[list[list[int]]]: """Turn bytes into list of 4x4 grids in column major order""" return [make_grid(s[i:i+BOX_AREA], should_pad) for i in range(0, len(s), BOX_AREA)] def expand_key(key: bytes, total_rounds: int) -> list[list[int]]: rcon = make_ro...
This code decrypts data using a key through a multi-round cipher algorithm. It breaks data into padded grids, expands the key for each round, and applies inverse transformations iteratively. The final step flattens decrypted grids into a byte stream, reversing encryption steps like key addition and grid operations to r...
def decrypt(key: bytes, data: bytes) -> bytes: grids = break_into_grids(data, should_pad=True) expanded_key = expand_key(key, ROUNDS+1) for round in range(ROUNDS, 0, -1): round_key = extract_key_for_round(expanded_key, round) grids = [decrypt_grid_round(round_key, grid, final=(round ...
def encrypt(key: bytes, data: bytes) -> bytes: grids = break_into_grids(data, should_pad=True) expanded_key = expand_key(key, ROUNDS+1) round_key = extract_key_for_round(expanded_key, 0) grids = [add_sub_key(grid, round_key) for grid in grids] for round in range(1, ROUNDS+1): ro...
The code provides an interactive AES encryption/decryption tool with base64 encoding. It demonstrates encrypting/decrypting example messages, accepts user commands for encryption/decryption, validates input, handles exit requests, and includes error checks for invalid operations or decode failures.
def main() -> None: # base64 just for command line ease of use import base64 going = True leave_codes = ["q", "exit"] print(""" █████ ███████ ███████ ███████ ███ ██ ██████ ██████ ██ ██ ██████ ████████ ██ ██ ██ ██ ██ ████ ...
def timestamp(self): '''Generate timestamp in Googlesheets format UTC (counts days from 30/12/1899)''' time.sleep(0.01) # 0.01s necessary to allow timestamp to update to new value python_timestamp = datetime.now(timezone.utc) - datetime(1899, 12, 30, tzinfo = timezone.utc) sheets_timestamp = python_timestamp.d...
This function imports a .txt file, parses its content into structured sections and zettels, stores them in a dictionary with timestamps, and merges them into the provided library. It validates the file type, cleans the library, extracts data using helper methods, and handles diagnostics. Duplicates are checked, and the...
def import_txt_zk(self, library = None, file_path = None): '''Read txt file and save into memory''' # Clean out library if library == None: library = dict() # check file type if file_path == None: file_path = self.file_path if not file_path.lower().endswith('.txt'): print('Error: Wrong filetype in impor...
def externalCommand(command, dryRun=False): """Execute External Commands and return stdout and stderr.""" if not dryRun: command = shlex.split(command) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return proc.communicate() print('DRY_RUN: %s' % com...
The main task of the code is to retrieve the vtysh running configuration from a system (or use a dry-run local config if enabled), split it into lines, and parse specific sections like BGP router settings, prefix lists, and route maps into a structured format. This involves executing a command to fetch the configuratio...
def getConfig(self): """Get vtysh running config and parse it to dict format""" if not self.args.dryrun: vtyshProc = externalCommand("vtysh -c 'show running-config'") self.stdout = vtyshProc[0].decode('utf-8').split('\n') else: self._dryRunLocalConfig() ...
def __refreshConfig(self): """Refresh config from Switch""" if self.needRefresh: self.config = {} self.generateSonicDict() self.needRefresh = False def __executeCommand(self, cmd): """Execute command and set needRefresh to True""" print(cmd) ex...
This method deletes a VLAN member if specified in kwargs, or iteratively removes all tagged members of a VLAN from the configuration. It first refreshes the config, constructs a sudo command to delete the member, executes it, or loops through tagged_members to delete each recursively.
def _delMember(self, **kwargs): """Del Member if not present""" self.__refreshConfig() if 'member' in kwargs: cmd = "sudo config vlan member del %(vlanid)s %(member)s" % kwargs self.__executeCommand(cmd) else: for member in self.config.get(kwargs['vlan...
def __refreshConfig(self): """Refresh config from Switch""" if self.needRefresh: self.config = {} self.generateSonicDict() self.needRefresh = False def __executeCommand(self, cmd): """Execute command and set needRefresh to True""" print(cmd) ex...
This function removes a specified IP address from a VLAN's interface configuration. If an 'ip' argument is provided, it deletes that specific IP. If not, it iterates through all IPs associated with the VLAN and removes them individually. It uses system commands to execute the removal, ensuring network configuration upd...
def _delIP(self, **kwargs): """Del IP if not present""" self.__refreshConfig() if 'ip' in kwargs: cmd = "sudo config interface ip remove %(vlan)s %(ip)s" % kwargs self.__executeCommand(cmd) else: for delip in self.config.get(kwargs['vlan'], {}).get('ip...
def _addVlan(self, **kwargs): """Add Vlan if not present""" self.__refreshConfig() if kwargs['vlan'] not in self.config: cmd = "sudo config vlan add %(vlanid)s" % kwargs self.__executeCommand(cmd) def __refreshConfig(self): """Refresh config from Switch""" ...
This method adds a VLAN member if not already present. It ensures the VLAN exists via _addVlan(), refreshes configuration, checks if the member exists in tagged_members, and executes a sudo command to add it if missing.
def _addMember(self, **kwargs): """Add Member if not present""" self._addVlan(**kwargs) self.__refreshConfig() if kwargs['member'] not in self.config.get(kwargs['vlan'], {}).get('tagged_members', []): cmd = "sudo config vlan member add %(vlanid)s %(member)s" % kwargs ...
def _addVlan(self, **kwargs): """Add Vlan if not present""" self.__refreshConfig() if kwargs['vlan'] not in self.config: cmd = "sudo config vlan add %(vlanid)s" % kwargs self.__executeCommand(cmd) def __refreshConfig(self): """Refresh config from Switch""" ...
The function `_addIP` adds an IP address to a specified VLAN if it is not already present in the configuration. It first ensures the VLAN exists by calling `_addVlan`, refreshes the configuration, checks if the IP exists under the VLAN in the config, and if absent, executes a command to add the IP using `sudo`.
def _addIP(self, **kwargs): """Add IP if not present""" self._addVlan(**kwargs) self.__refreshConfig() if kwargs['ip'] not in self.config.get(kwargs['vlan'], {}).get('ips', []): cmd = "sudo config interface ip add %(vlan)s %(ip)s" % kwargs self.__executeCommand(cm...
def _delMember(self, **kwargs): """Del Member if not present""" self.__refreshConfig() if 'member' in kwargs: cmd = "sudo config vlan member del %(vlanid)s %(member)s" % kwargs self.__executeCommand(cmd) else: for member in self.config.get(kwargs['vlan...
The main task of the code is to delete a VLAN (Virtual Local Area Network) along with all its associated members and IP configurations. It first removes tagged members and IPs using helper methods, refreshes the configuration, and then executes a system command to delete the VLAN if it exists in the configuration.
def _delVlan(self, **kwargs): """Del Vlan if present. Del All Members, IPs too (required)""" # First we need to clean all IPs and tagged members from VLAN self._delMember(**kwargs) self._delIP(**kwargs) self.__refreshConfig() if kwargs['vlan'] in self.config: ...
def decimal(number): # number is list of bits return sum(number[i]*2**i for i in range(len(number))) def most_common(data): for line in data: line_list = list(line_generator(line)) try: line_sum = [line_list[i] + line_sum[i] for i in range(len(line_list))] ...
The code initializes an object to compute power consumption and gas ratings from binary data. It calculates gamma (most common bits), epsilon (least common bits), and their product (consumption). It also determines oxygen (O_rating) and CO₂ (CO2_rating) ratings using bit criteria, converting reversed binary strings to ...
def __init__(self, data): self._data = data self.gamma = decimal(self.most_common(data)[::-1]) self.epsilon = decimal(self.least_common(data)[::-1]) self.consumption = self.gamma*self.epsilon self.O_rating = decimal(self.bit_criteria_oxygen()[::-1]) self.CO2_rating = dec...
def Birthdate_isValid(self, readdata): try: try: Result = re.compile("([0-9]{2}\/[0-9]{2}\/[0-9]{4})") Birth = Result.findall(readdata) return Birth[0] except: Result = re.compile("([1-9]{4})") gender = self....
The main task of the code is to perform OCR on an image file to extract and validate specific information such as full name, gender, birthdate, and Aadhar number, then compile these results into a list for return.
def ocr_core(self,filename): text = pytesseract.image_to_string(filename) # print("***********\n",text) Birthdate_Result = self.Birthdate_isValid(text) AdharNO_Result = self.Adhar_no_isvalid(text) Full_Name = self.extract_Name(text) Gender = self.extract_Gender(text) ...
def cleanCpf(cpf): return ''.join([x for x in cpf if x.isdigit()]) def cpfLength(cpf): return len(cpf) == 11 def firstDigit(cpf): return digitOne(cpf[:9]) def secondDigit(cpf): return digitTwo(cpf[:10]) def equalNumbers(numbers): return numbers == numbers[::-1] def verifyDigits(first_digit, second_...
The code validates a CPF (Brazilian individual taxpayer registry) by cleaning the input, checking its length, ensuring it isn't composed of all identical digits, and verifying the two check digits using specific calculation rules. It returns True if all validation steps pass, otherwise False.
def cpfValidator(cpf): cpf = cleanCpf(cpf) if cpfLength(cpf): first_digit = firstDigit(cpf) second_digit = secondDigit(cpf) return (not equalNumbers(cpf)) and verifyDigits(first_digit, second_digit, cpf) return False
def get_category_vocab(dataset_dir,cv_name): category_vocab_file = open(os.path.join(dataset_dir, cv_name)) category_vocab = [i[:-1].strip('[]').split(', ') for i in category_vocab_file.readlines()] category_vocab_file.close() return category_vocab def get_label_delete (dataset_dir,label_name): labe...
The code iteratively enhances the coherence of a dataset by adding and optionally deleting seed words. It evaluates each candidate seed's impact on coherence through training runs, updating the label file if the new coherence improves. The process involves checking for root-based duplicates, running training scripts, a...
def seed_update(dataset_dir,start=0,num_seed=5,flag_delete=0): category_vocab=get_category_vocab(dataset_dir,'category_vocab_accept.txt') #category_vocab_std.txt label_delete=get_label_delete (dataset_dir,'label_names.txt') label_names=get_label_delete (dataset_dir,'label_names.txt') # label_names --> ...
def prepare_data(self): """ Used to prepare data """ self.get_data() defor_l0 = [] defor_l1 = [] defor_l2 = [] defor_f = [] times = [] for _, modal in self.dp.items(): defor_l0.append(modal[0]) defor_l1.append(modal[1]) defor_l2.appe...
The code's main task is to process data by preparing and calculating values, updating results, logging output, converting results into DataFrames, exporting sub-results, and returning the group identifier along with the processed data frame.
def run(self): """ Main processing :return: """ data = self.prepare_data() self.cal_data(data) self.cal_pressure() self.final_result.update({self.group: self.result}) logger.debug(json.dumps(self.final_result, indent=3)) res = pd.DataFrame.from_dict(self.final...
def create_main_frame(self): # Membuat frame utama aplikasi self.main_frame = ttk.Frame(self.paned_window, padding="10", style="TFrame") self.paned_window.add(self.main_frame) self.create_main_frame_content() def create_add_item_frame(self): # Membuat frame untuk menambahkan bara...
The code creates a horizontal PanedWindow as the main layout container in a GUI application. It adds multiple frames (main, add item, view stock, home page) to the paned window, configures grid layouts for resizing, centers the window, and adds a size grip for manual resizing. The task is to set up a responsive, multi-...
def create_paned_window(self): # Membuat PanedWindow sebagai dasar layout self.paned_window = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL) self.paned_window.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S)) self.create_main_frame() self.create_add_item_frame() se...
def setup_styles(self): # Menggunakan ttkthemes themed_style = ThemedStyle(self.root) themed_style.set_theme("clearlooks") # Ganti dengan tema yang kamu inginkan dari ttkthemes # Menggunakan ttkbootstrap style = Style('superhero') # Anda dapat memilih tema yang berbeda...
The code initializes a stock management application's GUI, setting up the main window with a title, icon, styles, menu bar, and layout. It initializes the database, loads initial data, updates stock displays, and prepares an edit dialog for user interactions.
def __init__(self, root): self.root = root self.root.title("Aplikasi Manajemen Stok Barang") self.root.iconbitmap('assets/favicon/logo_icon.ico') # Ganti dengan path ke ikon Anda self.setup_styles() self.create_menu_bar() self.create_paned_window() self.init_data...
def write_image(shape, text_filename): global n image = shape.image # ---get image "file" contents--- image_bytes = image.blob # ---make up a name for the file, e.g. 'image.jpg'--- image_filename = 'image{:03d}.{}'.format(n, image.ext) n += 1 with open(image_filename, 'wb') as fi: ...
This function recursively processes a shape hierarchy, handling groups by traversing nested shapes, extracting images when encountering picture shapes, and writing text from shapes containing textual content to a specified file.
def visitor(shape,text_filename): if shape.shape_type == MSO_SHAPE_TYPE.GROUP: for s in shape.shapes: visitor(s,text_filename) elif shape.shape_type == MSO_SHAPE_TYPE.PICTURE: write_image(shape,text_filename) elif hasattr(shape, "text"): write_text(shape)
def get_tunnels(): global api_count global tunneldict resp0 = requests.get( tunnels_url, headers=headers) api_count = api_count+1 data0 = json.loads(resp0.text) for i in data0: tunneldict[i['id']] = i['name'] def get_templates(): global api_count global Temp...
The main task of the code is to generate a WLAN configuration report by polling API data (tunnels, templates, site groups, WLAN details), compiling it into a CSV file with timestamped naming, and logging execution time and API call count. The script automates data retrieval, transformation into a structured DataFrame, ...
def main(): start_time = time.time() print(f"** Polling For WLAN Config...**") get_tunnels() get_templates() get_sitegroups() get_wlan_data() # print(json.dumps(WLAN_Array, indent=2)) df = pandas.DataFrame(WLAN_Array) new_file = '{}/wlan_tem...
def get_sitegroups(): global api_count global sitegroupdict resp0 = requests.get( org_sitegroups_url, headers=headers) api_count = api_count+1 data0 = json.loads(resp0.text) for i in data0: sitegroupdict[i['id']] = i['name'] def get_rftemplate(): global api_coun...
The main task of the code is to poll site details from APIs, compile the data into a structured report, and save it as a CSV file. It retrieves site groups, RF templates, alarm templates, and general data, then exports the aggregated information to a dated CSV file while logging the runtime and API call count.
def main(): start_time = time.time() print(f"** Polling For Site Details...**") get_sitegroups() get_rftemplate() get_alarmtemplate() get_data() # print(json.dumps(Site_Array, indent=2)) df = pandas.DataFrame(Site_Array) new_file = '{}/site_...
def predict_boxes( self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances] ): if not len(proposals): return [] proposal_deltas = predictions[1] num_prop_per_image = [len(p) for p in proposals] proposal_boxes = cat( [p.proposal_...
The code performs post-processing on model predictions to generate final object detection results. It extracts predicted boxes and scores from proposals, applies thresholding, non-max suppression (NMS), and selects top candidates per image using Fast R-CNN inference, returning refined detections based on specified para...
def inference(self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances]): boxes = self.predict_boxes(predictions, proposals) scores = self.predict_probs(predictions, proposals) image_shapes = [x.image_size for x in proposals] return fast_rcnn_inference( ...
def get_dataset(dataset_name): """ Wrapper for dataset selection. Args: dataset_name (str) : name of the dataset Returns: pd.Dataframe : predictors for the given dataset pd.Dataframe : prediction for the dataset """ if dataset_name == "boston": data, target = ge...
The code parses pipeline parameters by validating required keys, initializes dataset and target variables, sets up evaluator, normalisation, feature extraction, and regression components, converts regression parameters to lists for sequence handling, and constructs a pipeline of models using Compose. It returns the con...
def parse(self): """ Parses pipeline arguments and instanciates everything. Args: None Returns: Pipeline : this pipeline, after being parsed. """ for key in ["dataset", "evaluation", "normalisation", "feature_extraction", "regression", "evaluati...
def getPrevRunID(self, pipelineName): try: prev = self.spark.sql(f"select pipelineRunID from genie.log where id='{pipelineName}' order by start desc limit 1") if prev.count() >0: return prev.head()[0] else: raise Exception(f"No previous records...
The code executes a pipeline workflow, handling "start" or "restart" states. It initializes run metadata, retrieves previous runs if restarting, sets up thread pools, and initializes pipeline structures. It logs execution progress in a database, tracks success/failure status, and manages error handling. If failures occ...
def execute(self, runStatus, pipelineName, runID="", triggerType=""): try: start = datetime.now(self.tz) self.pipelineName = pipelineName self.pipelinerunid = uuid.uuid4() if runID=="" else runID #runStatus = self.getRunStatus(ru...
def update(self): """Read current values from all input registers.""" self._get_state() self._get_enabled() self._get_errors() self._get_warnings() self._get_coolant_in() self._get_coolant_out() self._get_oil_temp() self._get_helium_temp() ...
The code initializes a Compressor object to communicate with a Modbus TCP controller, establishing a connection using the provided IP address and port. It sets up attributes to track the compressor's state, power status, warnings, errors, temperature, pressure values, and device information. The `update()` method retri...
def __init__(self, ip_address=default_IP, port=default_port): """Create a Compressor object for communication with one Compressor Digital Panel controller. Opens a Modbus TCP connection to the Compressor Digital Panel controller at `ip_address`, and reads the current state. Args: ...
def _get_state(self): """Read the current state of the compressor.""" r = self._client.read_input_registers(self._operating_state_addr) if r.isError(): raise RuntimeError("Could not get current state") else: self._state = r.registers[0] def _get_errors(self): ...
The code's main task is to activate a compressor by sending an enable command to a register, waiting for it to start, checking its state, and raising errors if it fails to initialize properly. It includes error handling for failed commands and state validation, ensuring the compressor reaches an operational state (code...
def on(self): """Turn the compressor on.""" w = self._client.write_registers(self._enable_addr, 0x0001) if w.isError(): raise RuntimeError("Could not command compressor to turn on") else: sleep(self._enable_delay) self._get_state() # give i...
def _get_frequency(self): """Get the current frequency from the inverter""" r = self._read_registers(self._frequency_addr, count=2, unit=1) decoder = BinaryPayloadDecoder.fromRegisters(r.registers, byteorder=Endian.Big, wordorder=Endian.Big) result = decoder.decode_16bit_int() se...
The main task of the code is to retrieve updated values for frequency, current, voltage, and power from an inverter by calling four private methods. The `update` method orchestrates data collection for monitoring purposes, ensuring all relevant electrical parameters are refreshed and stored for further processing or di...
def update(self): """Get updated values for all monitor values from the inverter""" self._get_frequency() self._get_current() self._get_voltage() self._get_power()
def migrate_custom_config(config_file): # config_file = os.path.join(node_data_directory, 'sovrin_config.py') if not os.path.exists(config_file): return logger.info("Migrating custom config file : {}".format(config_file)) for line in fileinput.input(config_file, inplace=1): if 'domainT...
The main task of the code is to migrate data for multiple nodes by checking the existence of necessary directories, handling default paths if needed, and applying migration steps such as updating configurations, domain ledgers, hash stores, and states for each node's data directory.
def migrate_all(): config = getConfig() base_dir = config.baseDir nodes_data_dir = os.path.join(base_dir, config.nodeDataDir) if not os.path.exists(nodes_data_dir): # TODO: find a better way base_dir = '/home/sovrin/.sovrin' nodes_data_dir = os.path.join(base_dir, config.nodeData...
def get_args(): import argparse parser = argparse.ArgumentParser() difficulty_levels = ["easy", "medium", "hard", "expert"] total_pieces = [4, 16, 49, 49] diff_to_pieces = dict(zip(difficulty_levels, total_pieces)) mut_exclusive_group = parser.add_mutually_exclusive_group() mut_exclusive_gro...
The main task of the code is to initialize a jigsaw puzzle game by selecting a random image, determining the puzzle grid dimensions, and setting up the game window with scaled puzzle pieces using Tkinter. It retrieves configuration parameters, calculates piece layout, loads and splits the image, then launches the game ...
def main(): images = ["dogs.png", "confetti.png", "car-xmas.png", "santa.png", "monster-puzzle.png"] image_path = Path("img", random.choice(images)) total_pieces, show_bg_pic = get_args() pieces_per_row = int(sqrt(total_pieces)) print(f"Image path: {image_path}") print(f"Total pieces: {total_pie...
def check_puzzle_complete(pieces_on_canvas): completed = all([piece["solved"] for piece in pieces_on_canvas.values()]) return completed def show_confetti_animation(overlay_canvas, window): gif_path = "img/confetti.gif" frames = load_frames(gif_path) confetti_item = overlay_canvas.create_image(overl...
The function checks if a puzzle is completed. If so, it triggers a confetti animation after a 50ms delay and schedules a "play again" dialog to appear after 5 seconds, ensuring the celebration sequence before prompting user action.
def check_and_celebrate(overlay_canvas, window): if check_puzzle_complete(pieces_on_canvas=overlay_canvas.drag_data["pieces_on_canvas"]): print("Puzzle complete!") # Schedule the confetti animation to start after a short delay overlay_canvas.after(50, lambda: show_confetti_animation(overlay_...
def open_main_xml(self, txt): x = txt + '\n' self.open_xml(txt) self.os.write('\n') self.add_spaces() def print_keyword_and_advance(self): self.print_keyword_constant() self.advance() def get_token(self): return self.JackTokenizer.get_token() def print_identifier_...
This function compiles class variable declarations (static/field) by parsing type, variable names, and commas, generating corresponding XML structure with proper syntax handling for Jack language compilation.
def compile_class_var_dec(self) -> None: """Compiles a static declaration or a field declaration.""" # static|field type var_name (,var_name)* ; self.open_main_xml("classVarDec") self.print_keyword_and_advance() # static | field if self.get_token() in keyWords.keys(): ...
def open_main_xml(self, txt): x = txt + '\n' self.open_xml(txt) self.os.write('\n') self.add_spaces() def get_token(self): return self.JackTokenizer.get_token() def print_keyword_and_advance(self): self.print_keyword_constant() self.advance() def print_identifier_...
The main task of the code is to compile a parameter list into XML format, handling both existing types (keywords) and new types (identifiers), while parsing parameters separated by commas. It processes variable names, skips enclosing parentheses, and ensures correct token advancement for each parameter, including handl...
def compile_parameter_list(self) -> None: """Compiles a (possibly empty) parameter list, not including the enclosing "()" go until the one next to the end of the list. """ # ((type var_name) (,var_name)*)? # Your code goes here! self.open_main_xml("parameterList") ...
def open_main_xml(self, txt): x = txt + '\n' self.open_xml(txt) self.os.write('\n') self.add_spaces() def print_keyword_and_advance(self): self.print_keyword_constant() self.advance() def get_token(self): return self.JackTokenizer.get_token() def print_identifier_...
This function compiles a variable declaration statement by parsing field/static keywords, type identifiers, variable names, and comma-separated multiple variables, then generates corresponding XML tags with the parsed information as part of a compiler's intermediate representation.
def compile_var_dec(self) -> None: # field|static type car_name (,var_name)* ; self.open_main_xml("varDec") self.print_keyword_and_advance() # field|static if self.get_token() in keyWords.keys(): self.print_keyword_and_advance() # exist type else: self....
def get_token(self): return self.JackTokenizer.get_token() def print_keyword_and_advance(self): self.print_keyword_constant() self.advance() def print_identifier_and_advance(self): self.print_identifier() self.advance()
The code's main task is to identify if the current token is a keyword or an identifier, print it, and advance the token pointer. If the token matches a keyword, it prints the keyword; otherwise, it treats it as an identifier and prints it, then moves to the next token for further processing.
def print_var_type(self): if self.get_token() in keyWords.keys(): self.print_keyword_and_advance() # exist type else: self.print_identifier_and_advance()
def remove_slashes(self): flag, comment = False, '//' for row, line in enumerate(self.file): for ind, c in enumerate(line): if c == '"': flag = not flag if flag: # ignore what between " " continue if ind...
This code initializes a tokenizer by reading an input stream, processing it to remove comments and slashes, splitting it into lines, and preparing tokens for further processing.
def __init__(self, input_stream: typing.TextIO) -> None: """Opens the input stream and gets ready to tokenize it. Args: input_stream (typing.TextIO): input stream. """ self.pos = 0 self.file = [] self.tokens = [] input_lines = input_stream.read().spli...
def open_main_xml(self, txt): x = txt + '\n' self.open_xml(txt) self.os.write('\n') self.add_spaces() def print_keyword_and_advance(self): self.print_keyword_constant() self.advance() def print_identifier_and_advance(self): self.print_identifier() self.adv...
This function compiles a complete class by generating XML structure for class declarations. It processes class name, variables (field/static), and subroutines (method/function/constructor), advancing through tokens while printing keywords/symbols and calling recursive compilation methods for variables and subroutines, ...
def compile_class(self) -> None: """Compiles a complete class.""" # class class_name {class_var_dec* subroutine_dec*} self.open_main_xml("class") self.print_keyword_and_advance() # class self.print_identifier_and_advance() # class_name self.print_symbol_and_advance() #...
def parse_comments(item, gpt_comments): lines = gpt_comments.split('\n') since = 1 for line in lines: if not line.strip(): continue since = random.randint(since, 60) posted = pd.Timestamp(item['posted']) + pd.Timedelta(minutes=since) indent, user, text = re.match(r'^(\s*)([^:...
The code processes GPT-generated comments by parsing them, counts the number of comments, and saves the parsed comments list to a JSON file. It updates the input item with the comment count and stores the comments in a file path determined by the item's attributes, creating necessary directories.
def write_comments(item, gpt_comments): comments = [*parse_comments(item, gpt_comments)] item['comments'] = len(comments) write_json(get_comments_file(item, mkdir=True), comments)
def render_headline(rank, headline, slug, domain, user, points, comments, posted, personal=False, tutorial=False): return f'''<tr class="athing"> <td align="right" valign="top" class="title"><span class="rank">{rank}.</span></td> <td valign="top" class="votelinks"><center><a href="javascript:void(0)"><div ...
The code renders HTML pages from templates by replacing placeholders with dynamic content. It generates a main index.html using reversed headlines and creates individual comment pages for each headline, inserting escaped titles, rendered headlines, and formatted comments into respective templates.
def render_html(headlines): with open('index.template.html', 'r') as f: template = f.read() template = template.replace('$HERE', '\n'.join(render_headline(i + 1, **item) for i, item in enumerate(reversed(headlines)))) with open('index.html', 'w') as f: f.write(template) for ...
def correct_type_name(type_name) -> str: """ Edit asset type name to folder friendly legacy name :param str type_name: type name :return: legacy friendly name """ corrected_type = type_name.replace("Substance", "") if corrected_type == "IBL": corrected_type = "Environment" return...
The code creates a menu for selecting asset types to generate folders. It retrieves all asset types from the database, lists them with options for "All" and "Return", and processes user input to create folders for selected types or all types, exiting the loop when "Return" is chosen.
def create_folders(database) -> None: """ Draw meny for asset type selection for folder creation :param CommonDatabaseAccess database: reference to the database """ menu_title = " Select asset type to create folder" count = 1 menu_items = [] all_asset_types = database.get_all_types()...
def clear_console(): """Clears console view""" command = "clear" if os.name in ("nt", "dos"): # If Machine is running on Windows, use cls command = "cls" os.system(command) def create_folders(database) -> None: """ Draw meny for asset type selection for folder creation :param Co...
The main task of the code is to display a menu-driven interface for managing database operations. It presents 11 options for actions like creating folders, downloading images, generating reports, and transferring files. The loop processes user input, invoking corresponding functions based on selections, until the user ...
def main_menu(database) -> None: """ Draw main menu :param CommonDatabaseAccess database: reference to the database """ menu_title = " Select action" menu_items = [ "[1] Create folders.", "[2] Download all images.", "[3] Make all icons. Where Preview.ico do not exist.", ...
def predict(train, train_labels, test, test_labels, k): """ Runs the KNN algorithm on multiple test images :param train: train images :param train_labels: corresponding train labels :param test: test images :param test_labels: corresponding test labels :param k: int, the k parameter :return: 0 <= float <= 1, t...
The main task is to run a machine learning model on the MNIST dataset, splitting data into training and test sets, predicting labels using a model (likely k-NN), and evaluating accuracy. It prints prediction results and generates plots showing accuracy trends for varying k-values and sample sizes, analyzing model perfo...
def main(): """ The main function - runs the code of the programming assignment """ mnist = fetch_openml('mnist_784') data = mnist['data'] labels = mnist['target'] idx = np.random.RandomState(0).choice(70_000, 11_000) train = data[idx[:10_000], :].astype(int) train_labels = labels[idx[:10_000]] test = data...
def _get_edge_df(self, batches): self.batches = self._get_batches(self.df) edge_dict = {} source = [] target = [] edge_frequency = [] # execute functions as above looping through each list, finding all unique combinations in each list # and adding them to dict o...
The code processes a dataset to extract graph structures (edges/nodes), computes graph features like adjacency, betweenness centrality, clustering coefficients, and communities, then updates node dataframes with these metrics for network analysis.
def fit_transform(self): print('Getting edges and nodes..') self.edge_df = self._get_edge_df(self.df) self.node_df = self._get_node_df(self.edge_df) self.node_id_dic = self._get_node_id_dic(self.node_df) self.node_dic = self._get_node_dic(self.node_id_dic) self.edge_df = ...
def get_intersections(x0, y0, r0, x1, y1, r1, number_mode=False): # Returns either the number of intersections (number_mode = True) or the coordinates of intersections between two circles # circle 1: (x0, y0), radius r0 # circle 2: (x1, y1), radius r1 d=d_points(x1,y1,x0,y0) # non intersecting ...
The function `select_case` calculates a specific point based on the geometric relationships between three beacons, considering cases like intersections, containment, and special radius values. It handles scenarios with 0, 2, 4, or 6 intersections, adjusts beacon radii to resolve containment, and returns coordinates der...
def select_case(b1: beacon, b2: beacon, b3: beacon): #Function to treat all cases of beacon radiuses n_intersections=0 n_inter12=get_intersections(b1.x, b1.y, b1.d_2D, b2.x, b2.y, b2.d_2D,number_mode=True) n_inter13=get_intersections(b1.x,b1.y,b1.d_2D,b3.x,b3.y,b3.d_2D,number_mode=True) n_inter23=...
def camera_connect(): client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host_ip = '192.168.137.149' # Raspberry Pi IP port = 12345 client_socket.connect((host_ip, port)) data = b"" payload_size = struct.calcsize("Q") return client_socket, data, payload_size def fetch_image(c...
The function evaluates the error in motion vector (MV) positioning by comparing detected person coordinates from 50 camera frames with a given reference position (current_x, current_y). It connects to a camera, captures frames, detects persons, records their coordinates and the reference point, then compiles the data i...
def evaluate_mv_error(current_x,current_y): """Function to calculate the error of MV positioning""" client_socket, data, payload_size = camera_connect() dict={} for i in range(50): frame, data=fetch_image(client_socket=client_socket, data=data, payload_size=payload_size) pers...
def camera_connect(): client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host_ip = '192.168.137.149' # Raspberry Pi IP port = 12345 client_socket.connect((host_ip, port)) data = b"" payload_size = struct.calcsize("Q") return client_socket, data, payload_size def fetch_image(c...
This code performs real-time person detection from a camera feed, updating a shared data structure with detected positions. It continuously fetches images, identifies persons using a detection function, and optionally visualizes results. The loop terminates on pressing 'Q', closing the camera connection.
def mv_positioning(shared_data, plot=False): """Main function to run MV positioning""" client_socket, data, payload_size = camera_connect() while True: frame, data=fetch_image(client_socket=client_socket, data=data, payload_size=payload_size) persons=locate_now(frame,plot=plot) if sh...
def get_file_loader(entities_filename): version = get_document_version(entities_filename) print(f"Version detected: {version}") if version == 'new': return iter_entries_new elif version == 'old': return iter_entries_old else: raise Exception def join_elements(candidate): ...
The code extracts entities from a file based on minimum percentage/support thresholds and predicate filters, adding valid entities to a set. It handles language-specific processing (e.g., joining elements for Chinese) and writes results to an output file, printing the count of extracted entities.
def extract_entities(filename, predicates, output_filename, min_perc, min_sup, lang): always_valid = False if max(min_perc, min_sup) == -1: always_valid = True loader = get_file_loader(filename) candidate = set() for line_name, entities in loader(filename): valid = always_valid ...
def cycle5(value): # for ease of iterative counting if value > 0: if value <= 5: return value else: return cycle5(value-5) else: return cycle5(value+5) def cycle4(value): # for ease of iterative counting if value > 0: if value <= 4: return ...
The main task of the code is to encode specific data segments from a CSV file for transmission. It calculates data partitions, applies mutation-based row skipping using cyclic transformations, reads two distinct data blocks (p1 and p2) from the file, and combines them into an encoded output for sending. The mutations a...
def stage1_send(): #returns encoded data to send stage1 global data_size global node global itr part_mutation = [4,1,2,3,4] file_mutation = [3,4,1,2,3] for i in range(1,itr): part_mutation.insert(4, part_mutation.pop(0)) file_mutation[5-cycle5(i)] = cycle4(file_mutation[5-cycle5(...
def cycle5(value): # for ease of iterative counting if value > 0: if value <= 5: return value else: return cycle5(value-5) else: return cycle5(value+5) def cycle4(value): # for ease of iterative counting if value > 0: if value <= 4: return ...
The code processes and reorders data from multiple nodes by decoding portions of a CSV file using mutation arrays. It reads, slices, and combines data segments (decM, decm, R, pre_ret, ret, post_ret) into a transformed array 'wf', applies iterative mutations to restructure data order, and saves the updated data back to...
def recv(stage1_m, stage1_M, stage2): global data_size global node global itr part_size = int(data_size / 20) decodem_mut = [1,2,3,4,1] #end - i decodeM_mut = [2,3,4,1,2] #shift left wret_part_mut = [1,2,3,4,1] #sl wret_file_mut = [1,2,3,4,4] #e-i must be offset by 1 iteration retained i...
def score(self): return BlackJack.score_of_cards(self.cards_player), BlackJack.score_of_cards(self.cards_croupier) def test_stopped(self, verbose = False): player, croupier = self.score() if player < 0 or croupier < 0 or player == 100 or self.stopped == 2: if verbose: ...
The main task of the code is to simulate the croupier's turn in a card game (likely Blackjack). It checks the croupier's score: if ≤16, it draws a random card (1-12); otherwise, it stops. It then checks if the game should stop using `test_stopped()`, returning the win result if so. If verbose, it prints player and crou...
def play_croupier(self, verbose=False): player, croupier = self.score() if croupier <= 16: self.cards_croupier.append(self._rnd.randint(1,12)) else: self.stopped += 1 if self.test_stopped(verbose): return self.test_win() elif verbose: ...
def test_win(self): p1, p2, _, _ = self.score() if p1 > 0: return 1 if p2 > 0: return 2 return 0 def play1(self, pos_x:int, pos_y: int, verbose:bool =False): w = self.test_win() if w != 0: if verbose: print("Ended") return w...
The code automatically plays a move at position (pos_x, pos_y) in a game, checks if the game has ended, validates the move's position, executes play1 or play2 based on the last player, outputs the board state if verbose, and returns the game result.
def auto_play(self, pos_x:int, pos_y: int, verbose:bool =False): w = self.test_win() if w != 0: print("Ended") return w if self.state[pos_x][pos_y] == 0: if self.last_played in [0,2]: self.play1(pos_x, pos_y) elif self.last_played =...
def test_stopped(self, verbose = False): player, croupier = self.score() if player < 0 or croupier < 0 or player == 100 or self.stopped == 2: if verbose: print(self.cards_player, self.cards_croupier) print(self.score()) print("Finish: ", self.t...
The code implements a player's turn in a card game, handling strategies to stop, take a card, or double the bet. It updates the game state based on the chosen strategy, checks for stopping conditions, and proceeds to the croupier's turn or evaluates the win status. The function also manages bet adjustments and outputs ...
def play(self, strategy: int, verbose=False):#0 to stop, 1 to take and 2 to double, no separate if self.test_stopped(verbose): return self.test_win() if strategy == 0: #stop self.stopped += 1#player stop elif strategy == 1 or strategy == 2:#take or double self...
def get_latest_driver_version_for_chrome_version(): chrome_version = get_current_chrome_version() chrome_version_excluding_minor = chrome_version[0:chrome_version.rfind('.')] url = BASE_PATH + '/LATEST_RELEASE_' + chrome_version_excluding_minor resp = requests.get(url) driver_version = resp.text ...
The code downloads the latest Chrome WebDriver version compatible with the installed Chrome browser, if enabled in the config. It checks if the driver already exists locally; if not, it constructs the OS-specific download URL, fetches the file, and saves it to the specified location, providing progress updates.
def download_latest_chrome_driver(configfile): global config config = configfile driver_version = get_latest_driver_version_for_chrome_version() if not config['download_driver']: print('Downloading disabled in script configuration. exiting...') return if check_if_driver_already_exist...
def nu0(self): return self.env.initial_state_dist() def state_action_value_and_policy(self, mu, policy): """ Computes the regularized state-action value function while updating the policy """ Q = np.zeros((self.N_steps, self.S, self.A)) pi = np.zeros((self.N_s...
This function performs one iteration of an algorithm (MD-CURL/OMD-MFG) to update state-action distributions and policies in changing transition environments. It initializes parameters, updates value functions/policies based on the specified algorithm, estimates transitions/noise when unknown, and tracks objective funct...
def iteration(self, n_iterations, true_model, true_noise, P_model, algo): """ Computes one iteration of OMD with changing transitions true_model = if the dynamics are known but not necessarily the noise true_noise = if both dynamics and noise are known, therefore P is entirely known ...
def create_cells(self): #looping through number of specified rows and columns and creating cells to be addded to cells[][] matric for col in range(self.columns): column = [] for row in range(self.rows): column.append(Cell(self.window)) self.cells.appen...
This code initializes a maze object with specified dimensions and parameters, creating a grid of cells, setting up an entrance/exit, generating the maze structure using a random algorithm, and resetting visited cell tracking. It configures spatial properties, handles randomization via a seed, and triggers key maze gene...
def __init__(self, x1, y1, columns, rows, cell_size_x, cell_size_y, window, seed=None): self.x1 = x1 self.y1 = y1 self.rows = rows self.columns = columns self.cell_size_x = cell_size_x self.cell_sixe_y = cell_size_y self.window = window if seed != None: ...
def get_row_points(box, num_of_scanned_rows): space = (box[3] - box[1]) / num_of_scanned_rows row_points = list(drange(box[1], box[3], f'{space}')) final_row_points = list(np.rint(np.asarray(row_points)).astype(int)) return final_row_points def get_col_points(box, col_coefs): col_delta = box[2] - bo...
This function extracts specific data (e.g., 'Name' and 'click_target') from a screen image by defining cell regions within a location box. It calculates row and column coordinates, updates the screen if needed, and returns processed values using configured offsets and extraction parameters.
def get_location_data(self, rows=13, refresh_screen=False): y_range = get_row_points(self.config['locations_box'], rows) x_range = get_col_points(self.config['locations_box'], self.config['locations_box_columns']) cells = get_cells(x_range[0:2], y_range) if refresh_screen: s...
def get_row_points(box, num_of_scanned_rows): space = (box[3] - box[1]) / num_of_scanned_rows row_points = list(drange(box[1], box[3], f'{space}')) final_row_points = list(np.rint(np.asarray(row_points)).astype(int)) return final_row_points def get_col_points(box, col_coefs): col_delta = box[2] - bo...
This function extracts survey scan data from a screen image by defining a grid area, refreshing the screen if needed, and extracting specified columns (e.g., 'Locked', 'Ore', 'Quantity') as either values or boolean flags based on the 'extract_type' parameter, using predefined offsets and cell coordinates for accurate d...
def get_survey_scan_data(self, rows=6, refresh_screen=False, extract_type='values'): y_range = get_row_points(self.config['survey_scan_box'], rows) x_range = get_col_points(self.config['survey_scan_box'], self.config['survey_scan_box_columns']) cells = get_cells(x_range, y_range) if ref...
def batch_norm(layer, name): return tf.layers.batch_normalization(layer, name=name+"_batch_norm") def conv2d(layer, weights, biases, name, strides=[1,1,1,1], padding='SAME'): activs = tf.nn.conv2d(layer, weights, strides=strides, padding=padding, name=name+"_conv2d") activs = tf.nn.bias_add(activs, biases) ...
The code constructs a neural network with an initial convolutional layer, multiple residual blocks, and a final output layer. It applies batch normalization, convolutional operations, and global average pooling, using pre-defined weights/biases from `tensordict`. The network processes inputs through residual blocks, re...
def create(inputs, tensordict): layers = dict() normed = batch_norm(inputs, name='normed') init_weight, init_bias = tensordict['init'] res_layer = conv2d(normed, init_weight, init_bias, 'init_conv') layers['init'] = res_layer n_resblocks = tensordict['n_resblocks'] for i in range(n_resblock...
def divideArea(arrOfPoint, p1, p2): # Divide area of an array of points where separate between a line that lies on p1 p2 x1 = p1[0] y1 = p1[1] x2 = p2[0] y2 = p2[1] leftSidePoint = [] # Left(above) rightSidePoint = [] # Right(below) for i in range(len(arrOfPoint)): xp3 = arrOfP...
The function computes a convex hull segment by recursively determining the farthest point from a line formed by two given points (lp, rp) and constructing the hull either above or below this line, depending on the specified category. It removes redundant points, divides remaining points into regions, and combines recur...
def convexHullParticular(arrOfPoint, lp, rp, category): arrOfHullPoint=np.array([]) lp1 = lp.tolist() rp1 = rp.tolist() arrOfPoint = np.array([x for x in arrOfPoint if list(x) != lp1]) arrOfPoint = np.array([x for x in arrOfPoint if list(x) != rp1]) arrOfPointLeft, arrOfPointRight = divideArea(a...
def generateInfectionTree(graf): n = len(graf.vs) ## generate an initial random tree graf.es["tree"] = False det_vtxs = [ix for ix in range(n) if graf.vs[ix]["detected"]] n_det = len(det_vtxs) tree_vtxs = det_vtxs.copy() b = graf.subgraph([graf.vs[ix] for ix in det_vtxs]) paths...
The main task of the code is to perform Markov Chain Monte Carlo (MCMC) sampling to infer infection spread probabilities on a graph. It generates initial infection trees and sequences, iteratively updates permutations and frequencies, adjusts parameters like step size and acceptance rates, and converges to a stable dis...
def inferInfection(graf, q, **mcmc_params): ## generates an initial tree and initial sequence from the tree graf1 = graf.copy() graf2 = graf.copy() guess_inf1 = generateInfectionTree(graf1) perm1 = generateSeqFromTree(graf1, guess_inf1) outward1 = computeOutDegreeFromSeq(graf1, pe...
def countAllHist(graf, root, get_subtree_sz=True): n = len(graf.vs) if get_subtree_sz: countSubtreeSizes(graf, root) hist = [0] * n ntree = graf.vs[root]["subtree_size"] S = collections.deque([root]) ## queue of nodes to visit hist[root] = 0 tree_nodes = [] ...
The code generates a node ordering starting with a root node, then permutes remaining nodes, and iteratively swaps unmarked nodes with their last unmarked ancestor to create a structured traversal sequence. It uses subtree size counts and ancestor relationships to determine node positions, ensuring nodes appear after t...
def sampleOrdering(graf, root): n = len(graf.vs) mypi = [0] * n normalized_h = countAllHist(graf, root)[0] mypi[0] = choices(range(n), normalized_h)[0] countSubtreeSizes(graf, root=mypi[0]) remain_nodes = [i for i in list(range(n)) if i != mypi[0]] mypi[1:n] = np.rand...
def get_line_starts(s): """Return a list containing the start index of each line in s. The list also contains a sentinel index for the end of the string, so there will be one more element in the list than there are lines in the string """ starts = [0] for line in s.split('\n'): sta...
This code initializes an object to process a template file. It sets the absolute file path, adjusts Windows-style separators, reads the template content from a file if not provided, and prepares line starts and tokens for processing. The token generator is initialized, and the first token is advanced.
def __init__(self, filename, template=None): self.filename = os.path.abspath(filename) if sys.platform == 'win32': self.filename = self.filename.replace('\\', '/') if template is None: with open(filename) as f: self.template = f.read() else: ...
def if_emp_selected(): # just to check if a employee is selected or not - tries to access a value of emp_data try: temp = emp_data[0][0] return True except: return False def confirmation(operation): title = 'Employee {} Confirmation'.format(operation) ...
This function deletes a selected employee's records from the 'employee', 'salary', and 'username' tables after user confirmation. It checks if an employee is selected, prompts for confirmation, executes deletion queries, updates UI elements like a combo box and status label, and clears input fields.
def delete(): # think about cascade delete or deleting records in all tables individually? '''cascade delete wont work coz employee table is not parent table for salary,username tables''' # think about taking confirmation from user thru a message box or a new tkinter window specifically for that...
def advance(self): self.token_index += 1 if self.token_index < len(self.tokens): self.token = self.tokens[self.token_index] return self.token def expression(self): return self.binary_operation(self.term, (TT_PLUS, TT_MINUS))
The `factor` method parses expressions by handling three cases: unary operations (e.g., `+`, `-`), numbers (int/float), and parenthesized sub-expressions. It constructs an abstract syntax tree (AST) using nodes like `UnaryOperationNode`, `NumberNode`, or returns parsed expressions from parentheses. This function is par...
def factor(self): token = self.token if token.type in (TT_PLUS, TT_MINUS): self.advance() factor = self.factor() return UnaryOperationNode(token, factor) # ? elif token.type in [TT_INT, TT_FLOAT]: self.advance() return NumberNode(toke...
def read_from_csv_file(): with open(input_filename) as f: rows = f.read().splitlines() trainers_dict = init_dict() for row in rows: trainer = row.split(",")[0] num_usages = row.split(",")[1] trainers_dict[trainer] = num_usages return trainers_dict def convert_trainer2numb...
The main task of the code is to process CSV data by converting trainer information into numerical values, specifically modifying the entry with key 0 by removing main characters, and then generating a visual chart from the processed numerical data.
def main(): # create_demo_responses() trainers_dict = read_from_csv_file() numbers_dict = convert_trainer2number(trainers_dict) for k in numbers_dict.keys(): if k == 0: numbers_dict[k] = remove_main_characters_if_zero(numbers_dict[k]) break create_chart(numbers_dict)
def check_keydown_events(event , gsettings , screen , ship , bullets ) : if event.key == pygame.K_RIGHT : ship.moving_right = True elif event.key == pygame.K_LEFT : ship.moving_left = True elif event.key == pygame.K_SPACE : fire_bullets(gsettings,screen,ship,bullets) def check_keyup_...
The main task of the code is to handle user input events in a Pygame game. It processes keyboard presses (movement/shooting), mouse clicks (to start the game), and window-close requests. The function updates game state by calling specialized handlers for keydown/up events and checks if the play button is clicked, trigg...
def check_events(gsettings,screen,aliens,ship,bullets,stats,play_button,sb) : for event in pygame.event.get() : if event.type == pygame.QUIT : sys.exit() elif event.type == pygame.KEYDOWN : check_keydown_events(event,gsettings,screen,ship,bullets) elif event.type ==...
def check_fleet_edges(gsettings, aliens): for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(gsettings, aliens) break def ship_hit(gsettings, stats, screen, ship, aliens, bullets,sb): if stats.ships_left> 0: stats.ships_left -= 1 sb.init...
The function updates alien movement, checks for collisions between aliens and the ship, and verifies if aliens reach the screen bottom, triggering responses like ship damage or game over conditions.
def update_aliens(gsettings,ship,aliens,screen,stats,bullets,sb): check_fleet_edges(gsettings, aliens) aliens.update() if pygame.sprite.spritecollideany(ship,aliens): ship_hit(gsettings, stats, screen, ship, aliens, bullets,sb) check_aliens_bottom(gsettings, stats, screen, ship, aliens, bullets,...
def fill_node(self, node, source_rule, prob, leaves_prob, l_child, r_child): new_prob = prob + leaves_prob if source_rule not in node or new_prob > node[source_rule][0]: node[source_rule] = (new_prob, tuple(), l_child, r_child) def fill_node_unaries(self, node, source_rule, prob, leaves_prob...
This code implements a probabilistic CKY parser using a dynamic programming chart. It initializes terminal symbols with grammar rules or ML predictions, then iteratively combines non-terminal candidates to build parse trees. The main task is parsing input sentences into structured trees by applying context-free grammar...
def parse(self, sentence): lengh = len(sentence) chart = [[dict() for j in range(lengh + 1)] for i in range(lengh + 1)] # init if RUN_MODE == PURE_CKY_M: for idx in range(lengh): terminal_res = [prod for prod in self._grammar.productions(None, sentence[idx])...
def get_trapped_tigers(self): # reset trapped tigers self.tigers["trapped"] = [] # get the positions of tigers tigers = self.get_player_position(self, self.player_tiger) # temporarily change the player turn temp_player_turn = self.player_turn self.player_turn = ...
The main task of the code is to determine the game's end state by checking if all tigers are trapped (return 1), all goats are killed (return 2), or if goats have no valid moves (return 2). It evaluates trapped tigers, killed goats, and scans empty spaces for potential goat moves, using directional checks to validate p...
def is_gameover(self): # 2 means tiger won # 1 means goat won # 0 means game is not over yet directions = [ {"row": -1, "col": 0}, # up {"row": 1, "col": 0}, # down {"row": 0, "col": -1}, # left {"row": 0, "col": 1}, # right ] ...