dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def inrange(vk,vt): vkpos=vk.get_curr_pos() vtpos=vt.get_curr_pos() dist=mobility_model(vkpos[0],vtpos[0],vkpos[1],vtpos[1],vkpos[2],vtpos[2]) if dist<vt.radius: return 1 return 0 def get_transmission_rate(v1, v2,vehicles): bandwidth = 1e6 # 1 MHz bandwidth #snr = 10 # #trans...
The function calculates the offloading latency for a vehicle task by summing transmission delays between vehicles, incorporating direct or relay paths based on relay availability. It iterates through candidate vehicles, computes transmission rates, and combines results with primality checks and relay-specific time calc...
def off_latency(vehicles,vehicle_strategy, task_generated, Tavs,candidate_sn,candidate_relay,task_vehicle): sum=0 last=vehicle_strategy[-1] d_off_n_m=task_generated[0] for v_m in vehicle_strategy : if(v_m.id!=last.id and v_m.id!=task_vehicle.id): sum+=inrange(task_vehicle,v_m)*(d_off...
def run_command(directory, command): if get_OS() not in ["windows", "linux", "darwin"]: raise RuntimeError("Your operating system does not support it.") # Edited command for Linux and MacOS if get_OS() != "windows": if "chmod" not in command: command = command.replace("adb", "./a...
The main task of the code is to uninstall a selected Android application using ADB commands, handle error cases like device connection failures or invalid selections, and log uninstallation details to a database. It retrieves the chosen package name from a listbox, executes the uninstall command via ADB, updates the ap...
def uninstall_app(): global package_names global serial_number if not package_names: messagebox.showwarning( "No application selected", "Select your device or refresh app list.", ) else: package_name = design.app_list_listbox.get( design.app_li...
def setup_gui(): design.search_box.bind("<KeyRelease>", lambda event: Scankey(package_names, event)) design.refresh_devices_btn.config(command=list_devices) design.refresh_app_list_btn.config(command=list_apps) design.device_chose_cmb.bind("<<ComboboxSelected>>", modified_cmb) design.uninstall_app_b...
The main task of the code is to initialize a GUI application by setting up the interface, listing connected devices, granting execute permissions to 'adb' on non-Windows OS, loading data from a specified database, and launching the GUI event loop to display the application.
def main(): global root setup_gui() list_devices() if get_OS() != "windows": # adb file has been granted execute permission run_command(get_adb_folder(), "chmod +x adb") read_database(database_path, table_name) root.mainloop()
def spawnDots(window): dotList = [] dotMoveHistory = [] for i in range(100): # Need more automation to do more than 100 exact dots dotList.append(Dot(400, 0, window)) dotList[i].draw() dotMoveHistory.append([]) return (dotList, dotMoveHistory) def clear(window): for item in w...
The main task of the code is to simulate an evolutionary process where animated dots (represented as graphical elements) evolve over generations. It initializes a window, spawns dots with movement histories, iteratively clears the screen, generates new movement patterns, selects the "best" dots based on some criteria, ...
def main(): window = GraphWin('Dancing Dots', 800, 800) (dotList, dotMoveHistory) = spawnDots(window) # startNewWave(window, dotMoveHistory) # bestDotsIndices = findBestDots(dotList) # dotMoveHistory = cloneBestDots(bestDotsIndices, dotMoveHistory) for i in range(20): inp...
def parseXlsx(): # Inactives company Company.query.update({Company.active:False}) db.session.commit() workbook = openpyxl.load_workbook(os.path.join(config["flask"]["upload_folder"],"CHARM_CATALOGUE_DATA.xlsx"),data_only = True) # Adds maps maps_sheet = workbook["Maps"] for i in range(2,m...
This function handles a POST request at the 'api/manage/load' endpoint, authenticating the request and processing uploaded files. It accepts Excel files (.xlsx) for data parsing, images (via ACCEPT_IMAGE_EXTENDS) for image loading, and compressed archives (.zip/.tar.gz) for unpacking and parsing. Unsupported files trig...
def load(): """ POST endpoint api/manage/load Allow for for uploading of images and data, see README """ result = auth_token(request) if not result[0]: return result[1] if "file" not in request.files: return "No file found",status.HTTP_400_BAD_REQUEST file = request.fil...
def __beginning_line(self): ''' Returns True if there's only one character in current line ''' return True if len(self.linecontent) == 1 else False def __skip_unvalid_lines(self): ''' Check if next line is valid and skip it if it's not ''' while not self.__is_valid_li...
This function tokenizes input by identifying and categorizing elements like keywords, numbers, identifiers, and handling edge cases such as comments, quotes, and compound symbols, while managing indentation, whitespace, and syntax errors.
def __get_token(self): if self.__beginning_line(): self.__skip_unvalid_lines() if not self.current_atom: return self.current_atom = '' if not self.current_atom.isspace() else self.current_atom indents_dedents = self.__check_for_indents() ...
def __get_next_char(self): ''' Returns next char in the buffer ''' self.current_atom = self.text.read(1) self.linecontent += self.current_atom self.idx += 1 return self.current_atom def __get_token(self): if self.__beginning_line(): self.__skip_unvalid_lines()...
This method tokenizes input by repeatedly fetching characters and generating tokens, appending them to a list. It handles errors by capturing exceptions, logging error details (message, line content, position), and returning both the token list and error list.
def __get_tokens(self): tokens = [] errors = [] while self.__get_next_char(): try: token = self.__get_token() if not token: continue if type(token) == type(list()): for unique_token in token: ...
def at_least_one_node_has_packet(self): for node in self.nodes: if not node.empty(): return True return False def get_node_with_next_packet(self): non_empty_nodes = [node for node in self.nodes if not node.empty()] next_node = min(non_empty_nodes, key=lambda n...
This function processes packets in a network simulation by iterating through non-empty nodes, checking for collisions and carrier signal conflicts. It handles successful transmissions, carrier failures, and collisions by invoking appropriate methods, updating transmission counts, and ensuring packets adhere to simulati...
def poll_packets(self): # Run while there is at least one non-empty node. while self.at_least_one_node_has_packet(): # Get the transmitting node transmitting_node = self.get_node_with_next_packet() # Get the next packet next_packet = transmitting_node.next...
def generate_packets(self): for node in self.nodes: self.generate_packets_for_node(node) def poll_packets(self): # Run while there is at least one non-empty node. while self.at_least_one_node_has_packet(): # Get the transmitting node transmitting_node = self.g...
The code's main task is to generate packets, monitor incoming packets, and compute relevant metrics, likely for network analysis or data processing. It sequentially executes packet generation, polling, and metric calculation to handle and evaluate packet data efficiently.
def run(self): self.generate_packets() self.poll_packets() self.calculate_metrics()
def convert_to_tokens(exact): if exact in exact2tokenized: return exact2tokenized[exact] else: return tokenize(exact) def convert_to_pos(tokens): str_x = list2str(tokens) if str_x in tokenized2pos: return tokenized2pos[str_x] else: return postag(tokens) def convert_to...
The function processes a line by extracting the head (index 3) and tail (index 4), converting them into tokens, part-of-speech tags, and normalized content using stopword list (sw) and lemmatizer (ltz). It appends the processed head and tail content to the original line and returns the updated list.
def process(line, sw, ltz): head = line[3] head_tokens = convert_to_tokens(head) head_pos = convert_to_pos(head_tokens) head_content = convert_to_content(head_pos, sw, ltz) tail = line[4] tail_tokens = convert_to_tokens(tail) tail_pos = convert_to_pos(tail_tokens) tail_content = convert...
def preprocess_generations(args): input_file = args.input_file outfile_path = os.path.join(os.path.dirname(input_file), os.path.basename(input_file).split('.')[0] + "_gens.jsonl") outfile = open(outfile_path, 'w') references_list = get_reference_sentences('test.tsv') heads_relations = get_heads_a...
The main task of the code is to evaluate model performance on the ATOMIC2020 test set by parsing input files, preprocessing generations, calculating scores, and saving results in JSONL format. It aggregates model scores, formats them into tables, and outputs LaTeX/TSV tables with timestamps. The code handles multiple e...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--input_file', type=str, help='Results file on ATOMIC2020 test set') args = parser.parse_args() generations_file = preprocess_generations(args) input_file = generations_file expts = [ [input_file, os.path.basename(i...
def init_centroids(points, k): x_center = points['x'].mean() y_center = points['y'].mean() R = dist(x_center, y_center, points['x'][0], points['y'][0]) for i in range(len(points)): R = max(R, dist(x_center, y_center, points['x'][i], points['y'][i])) x_c, y_c = [], [] for i in range(k): ...
This code implements the K-means clustering algorithm. It initializes centroids, assigns data points to the nearest centroid, and iteratively updates centroids by recalculating their positions until convergence (no changes in centroids). The process repeats until centroids stabilize, returning final cluster assignments...
def kmeans(points, k): centroids = init_centroids(points, k) nearest_centroid_ids = nearest_centroids(points, centroids) prev_centroids = centroids centroids = recalculate_centroids(points, nearest_centroid_ids, centroids) while not centroids_equal(prev_centroids, centroids): nearest_centroi...
def init_centroids(points, k): x_center = points['x'].mean() y_center = points['y'].mean() R = dist(x_center, y_center, points['x'][0], points['y'][0]) for i in range(len(points)): R = max(R, dist(x_center, y_center, points['x'][i], points['y'][i])) x_c, y_c = [], [] for i in range(k): ...
This function implements the K-means clustering algorithm, visualizing each iteration step. It initializes centroids, assigns points to nearest centroids, and iteratively recalculates centroids until convergence. The process draws cluster assignments at each step, returning final cluster IDs and centroids once the algo...
def kmeans_step_draw(points, k): centroids = init_centroids(points, k) nearest_centroid_ids = nearest_centroids(points, centroids) step = 0 draw(points, nearest_centroid_ids, k, centroids, 'optimal k = ' + str(k) + ', step ' + str(step)) prev_centroids = centroids centroids = recalculate_centroi...
def validateNode(self, doc,layerName, node, idx): idxMap = [] self.layerMap(idx, idxMap) validIdxMap = True onNode = node for i in idxMap: if onNode.index() != i: validIdxMap = False break ...
This function handles layer visibility changes in Krita by updating UI settings, managing canvas blocks for invisible layers, and tracking layer state changes. It checks document/node validity, toggles drag/select modes based on user settings, and ensures visible layers are auto-selected when settings are enabled.
def layerDataChanged(self, idx, idx2, urole = []): doc = Krita.instance().activeDocument() if doc is None: return node = doc.activeNode() if (doc.fileName() != self.docName): self.docName = doc.fileName() self.layerChanges = {} ...
def parseCommandLineArgs(): global WEBAPP parser = argparse.ArgumentParser() parser.add_argument("--webapp", action="store_true") args = parser.parse_args() if args.webapp: WEBAPP = True def loadIndexOfIndex() -> dict[str, int]: """ Loads the index of index into memory. """ ...
The main task of the code is to initialize a search engine by loading essential data (inverted index, document mappings) from disk, parsing command-line arguments, and launching either a web-based or console-based query interface based on the `WEBAPP` flag. It manages global variables for index access and ensures prope...
def main(): global invertedIndexFilePointer global indexOfIndex global docIDtoURL parseCommandLineArgs() with open(CONFIG_FILE) as f: # Gets path of folder containing the indexes indexFolderPath = json.load(f)["INDEX_STORAGE"] # Load data needed for search engine into mem...
def __validate_api_key__(event): key = None try: key = event['headers']['api-key'] except: key = None valid_api_key:str = os.environ["API_KEY"] if valid_api_key and key != valid_api_key: return {'statusCode': 403, 'body': 'Invalid key'} return None def __get_http_m...
This Lambda function handles API requests by validating an API key, processing OPTIONS and POST methods, and returning appropriate responses. It checks the HTTP method, executes corresponding actions (OPTIONS/POST), or denies unauthorized methods with a 403 error.
def lambda_handler(event:any, context:any) -> any: response = __validate_api_key__(event) if response: return response http_method:str = __get_http_method__(event) if http_method == HTTP_METHOD.OPTIONS.value: options_response = __do_options__() AppLogger.debug(f"Returni...
def _get_no_grad_ctx_mgr(require_grad): """Returns a the `torch.no_grad` context manager for PyTorch version >= 0.4, or a no-op context manager otherwise. """ if not require_grad and float(torch.__version__[0:3]) >= 0.4: return torch.no_grad() return contextlib.suppress() def _compute_stati...
This function calculates the Fréchet Inception Distance (FID) between generated images (gen_imgs) and real images (path) using the InceptionV3 model. It computes activation statistics for both image sets, then calculates the FID via the distance between their mean and covariance statistics. Parameters include batch siz...
def calculate_fid_given_paths_torch(gen_imgs, path, require_grad=False, batch_size=50, cuda=True, dims=2048): """ Calculates the FID of two paths :param gen_imgs: The value range of gen_imgs should be (-1, 1). Just the output of tanh. :param path: a tensor of images :param batch_size: :param cud...
def get_total_iters(self) -> int: return len(self.train_dataloader) def forward(self, batch: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor: img = batch[0].to(device=self.device, dtype=torch.float32) mask = batch[1].to(device=self.device, dtype=torch.float32) out = self.model(img) ...
The main task of the code is to train a model using specified configurations, logging training progress, validating periodically, and saving the model. It initializes training parameters, iterates over epochs and batches, computes loss, updates metrics, logs intervals, adjusts learning rate, evaluates performance at se...
def train(self, train_cfg: dict) -> None: logger.info(f'Start training....................................................\n') epochs = int(train_cfg['epochs']) total_iters = self.get_total_iters() print_freq = int(train_cfg['print_freq'] * total_iters) val_freq = int(train_cfg['...
def _setup_env(self, cfg: dict) -> None: logger.info(f'Setting up the environment......................\n') expr_cfg = cfg['expr'] train_cfg = cfg['train'] models_cfg = cfg['models'] datasets_cfg = cfg['datasets'] optimizers_cfg = cfg['optimizers'] schedulers_cfg...
The code's main task is to train a model using the provided configuration, generate two submission files for test images: one from the final trained model and another from the best validation epoch model, and save them as CSV files for evaluation.
def run(self) -> None: self._setup_env(self.cfg) self.train(self.cfg['train']) test_img_dir = self._get_test_img_dir() # Generate submission file of model of after train. model = os.path.join(self.cwd, 'model.pth') submission_file_after_train = os.path.j...
def dS_staple(self, t, x, y, z, mu): tmp = np.zeros((3, 3), dtype='complex128') for nu in range(4): if nu != mu: #Determine required points for the calculation of the action start_txyz = [t, x, y, z] start_txyz[mu] += 1 ### st...
The code performs a Markov chain Monte Carlo (MCMC) sweep to generate lattice configurations using the Metropolis algorithm. It iterates over spacetime dimensions and directions, proposing new SU(3) matrices for each link, calculating the action change (dS), and accepting/rejecting updates based on the Metropolis crite...
def markov_chain_sweep(self, Ncfg, matrices, initial_cfg=0, save_name='', Nhits=10, action='W', Nu0_step='', Nu0_avg=10): ratio_accept = 0. matrices_length = len(matrices) if save_name: output = save_name + '/link_' + save_name + '_' #if tadpole improving, initialize...
def generateTreeBase(): treeBase = [] for n in range(3): agentPool = [] for i in range(3): agent = Agent() agent.individualsFitness, agent.individuals = generateAgents( undirected_graph) agent.pocket = agent.individuals[0] agent.poc...
The code initializes a hierarchical structure by sequentially generating a base, middle, and top component using a chain of dependent functions, returning these three elements as a tuple to form an initial population structure for further processing.
def initializePopulation(): base = generateTreeBase() middle = generateTreeMiddle(base) top = generateTreeTop(middle) return base, middle, top
def initializePopulation(): base = generateTreeBase() middle = generateTreeMiddle(base) top = generateTreeTop(middle) return base, middle, top def calculate_std(agent): agent.std = st.pstdev(agent.individualsFitness) return agent.std def lostDiversity(agent): current_std = st.pstdev(agent.in...
The code implements a genetic algorithm for community detection or optimization. It iteratively selects parents from different population layers (base, middle, top), performs crossover and mutation on their gene representations, and updates the population to improve the top group's fitness. The process repeats until th...
def M_Link(): base, middle, top = initializePopulation() count = 0 topScore = -1 while count < 5: parent1 = top.pocket calculate_std(top) if not lostDiversity(top): parent2Agent = rd.choice(middle) else: parent2Agent = rd.choice(rd.choice(base)) ...
def read_rom(self, rom): with open(rom, 'rb') as f: return f.read() def load(self, rom_data): self.init_memory() for i, val in enumerate(rom_data): self.memory[PC_START + i] = val def fetch(self): return self.memory[self.pc] << 8 | self.memory[self.pc + 1] def exe...
This code runs an emulator by fetching and executing opcodes from a ROM, managing timers (delay/sound), updating the display, and handling exit events. It loads ROM data, processes instructions in a loop, decrements timers at intervals, and checks for user quit requests to terminate the emulator gracefully.
def run(self, rom): rom_data = self.read_rom(rom) self.load(rom_data) running = True counter = time.time() while running: # Fetch opcode = self.fetch() # Decode and execute self.execute(opcode) # Update timers ...
def _create_matrix(cls, rows, columns, default=None): """Create a 2 dimensional matrix of length with an optional default.""" return [[default for _ in range(columns)] for _ in range(rows)] def _create_list(cls, length, default=None): """Create a list of length with an optional default.""" ...
The code calculates geomagnetic components (declination, inclination, total intensity) from geodetic coordinates, altitude, and time using spherical harmonics expansions. It converts input coordinates to spherical form, computes magnetic field vectors via recursive Legendre polynomials, adjusts coefficients for secular...
def calculate( # noqa: PLR0912,PLR0913,PLR0915 - Too many branches,Too many arguments,Too many statements self, glat, glon, alt, time, allow_date_outside_lifespan=False, raise_in_warning_zone=False, ): """Calculate the Magnetic Components from a latit...
def decimal_degrees_to_degrees_minutes_seconds(decimal_degrees): """Convert decimal degrees to degrees, minutes and seconds. >>> from pygeomag import decimal_degrees_to_degrees_minutes_seconds >>> decimal_degrees_to_degrees_minutes_seconds(45.7625) (45, 45, 45.0) """ degrees, decimal_minutes = ...
The function `pretty_print_degrees` converts decimal degrees into a human-readable string with degrees, minutes, and optionally seconds, specifying cardinal directions (N/S/E/W) based on latitude/longitude. It supports formatting options: using full words (e.g., "North") or abbreviations (e.g., "N"), including seconds,...
def pretty_print_degrees( decimal_degrees, is_latitude, show_seconds=False, full_words=False, number_of_digits=0, ): """Format decimal degrees into a human-readable string. :param float, int decimal_degrees: Decimal degrees you want converted :param bool is_latitude: True for latitude, ...
def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if event.type == pygame.MOUSEBUTTONDOWN: self.mouseClick = pygame.mouse.get_pos() if event.type == pygame.KEYDOWN: ...
The main task of the code is to update the game state by controlling the frame rate, handling events, rendering game elements (tiles and score), drawing visual boundaries, and updating the display with the current FPS. It also applies a decay effect to the `clickLimitSpacer` variable and refreshes the screen for real-t...
def update(self): self.clock.tick(FPS) self.events() self.fps = self.clock.get_fps() pygame.display.set_caption(f'{round(self.fps)}') self.clickLimitSpacer *= 0.9999 self.screen.fill('white') self.tileHandler() self.scoreBoard() #self.controls() ...
def prepare_train_dataloader(): train_df, vocab = data_manipulation(args.df_train) train_df_X, valid_df_X, train_df_y, valid_df_y = data_splitting(train_df) train_ds = PlantPathologyDataset(train_df_X, train_df_y, 'train',) valid_ds = PlantPathologyDataset(valid_df_X, valid_df_y, 'val',) i...
The function `prepare_dataloader` selects and returns a specific data loader based on the input `mode` parameter. If `mode` is 'train', it prepares a training data loader; if 'pytorch', it prepares a PyTorch-compatible test data loader; otherwise, it prepares non-PyTorch data. The main task is to dynamically route to t...
def prepare_dataloader(mode = args.mode): if mode == 'train': return prepare_train_dataloader() elif mode =='pytorch': return prepare_test_dataloader() else: return prepare_nonpytorch_data()
def _run(self, variable): """ Display summary statistics and visualizations for a variable if verbose=True. Parameters: - variable: Name of the variable. """ if self.verbose: print( colored(f'-'*85, 'magenta', attrs=['bold']), '\n', ...
This code performs A/B testing on specified variables by applying statistical tests (t-test for normal data, Mann-Whitney U-test for non-normal data) to determine significant differences between groups. It iterates through test variables, checks normality and variance, selects appropriate tests, and compiles results in...
def apply(self, verbose: bool = True) -> pd.DataFrame: """ Apply A/B Testing on the specified variables. Parameters: - verbose: Boolean flag indicating whether to display verbose output (default is True). Returns: - DataFrame containing the A/B Testing results. ...
def title(): print("SALES DATA IMPORTER\n") def menu(): print("COMMAND MENU") print('view\t - View all sales') print('add\t\t - Add sales') print('import - Import sales from file') print("menu\t - Show menu") print('exit\t - Exit program') print() def view(): total = 0 print('\...
The code defines a main function that runs a command-driven program, allowing users to view sales data, add new sales, access the menu, or exit. It processes user input in a loop, executing corresponding functions based on commands like 'view', 'add', 'menu', or 'exit', and terminates with 'Bye!' upon exiting.
def main(): title() menu() command = input('Command: ') loop = True while loop: if command == 'view': view() elif command == 'add': add_sale() elif command == 'import': print('lol no') elif command == 'menu': m...
def weight_bias_init_Nlayers(Size_of_nlayers_lst): """ A function that initializes the weights for each layer of the neural network and also initiates a bias. These will be adjusted later by the neural network. Inputs: -Size_of_nlayers_lst: a list of size n that contains the initial value for each neuron in...
The function trains a neural network with multiple hidden layers using k-fold cross-validation on a given dataframe. It initializes weights and biases, performs forward and backward propagation over specified epochs, updates parameters using the learning rate, and evaluates model performance on test folds. Outputs incl...
def train_NN(Dataframe, epoch, learning_rate, layer_neurons): """ The culminating function of this module. This function accepts a dataframe, a response column, an epoch value, and a learning rate. It crunches the dataframe and calculates the final weight each variable should be given and the final bias. Used f...
def weight_bias_init_Nlayers(Size_of_nlayers_lst): """ A function that initializes the weights for each layer of the neural network and also initiates a bias. These will be adjusted later by the neural network. Inputs: -Size_of_nlayers_lst: a list of size n that contains the initial value for each neuron in...
The function `train_NN_final_model` trains a multi-layer neural network using forward and backward propagation. It initializes weights and biases, iterates over epochs to adjust parameters via gradient descent, computes training costs (SSE), and evaluates test errors. Early stopping occurs if test error increases or fl...
def train_NN_final_model(X,Y, epoch, learning_rate, X_test, Y_test, layer_neuron ): ''' The culminating function of this module. Used to compute final weights. Inputs: -X: Observations that NN is training on -Y: Predictions for the observations that the NN is Training on -epoch: Th...
def eol(self): return self.index >= len(self.toks) def consume(self): res = self.peek() self.index += 1 return res def consume_specific(self, char): if self.peek() != char: self.print_error("Expected token '{}'".format(char)) return self.consume() def parse_la...
This function parses a line of assembly code into VLIW instructions. It processes tokens, handles labels, directives, and comments, then constructs a VLIWInstruction object if valid instructions are found, appending it to a global list and updating the program counter.
def parse_line(self, line): global vliw_insn line = line.strip() line = line.expandtabs() end = line.find('#') if end >= 0: line = line[:end] self.toks = line.split() self.index = 0 insns = [] while not self.eol(): t = ...
def _get_repo_release(self): """ Get a GitHub release based on the tag name of the workflow release event """ if self.repo.release: return self.repo.release if not self.repo.ref or not self.repo.ref.startswith('refs/tags/'): raise ValueError('Git ref is n...
The main task of the code is to upload two assets— the letter of application and a zipped public folder—to a GitHub release, then create a comment with download links. It checks if the git provider is not 'local', retrieves the release, uploads the letter as Markdown, zips the public folder if it exists, and adds a com...
def _create_release_assets(self, letter_path: str): """ Uploads the assets of the release to currently only github Uploaded assets are: * Letter of application * Zip of your public folder """ if self.git_provider == 'local': return release =...
def _get_job_source_from_folder(self) -> list[tuple[str, str, str | None]]: """ Get the job from a specific folder """ job_posting_path = normalize_path( self.repo.path, str(self._get_gitcha_config().job_posting_folder)) items = job_posting_path.glob('*.md') ...
This function generates a Markdown letter of application from job data, saving it to a temporary directory. It handles multiple job entries, creates release assets if specified, and outputs the result to stdout or returns the content. It retrieves job title/description from environment variables, validates inputs, and ...
def create_letter_of_application(self, create_release_assets: bool, stdout: bool = True) -> str | None: """ Creates the letter of application in a temp directory as a Markdown file Args: create_release_assets (bool): Create release assets from the output stdout (bool, op...
def get_latest_block_number(self): return self.client.w3.eth.block_number def log_event(self, topic): event_name = self.all_events.get(topic) logger.info(f"Event: {event_name}") def request_received(self, data: bytes): return self.decode_request_received(data) def request_receive(self, b...
The code listens for blockchain events by fetching logs between specified block ranges. It processes logs with specific topics (e.g., RR, VFS), extracts data like request IDs and addresses, and triggers actions such as `request_received` and `request_receive`. It continuously updates the block range, sleeps when no new...
def listen(self): while True: if self.from_block >= self.to_block: time.sleep(12) self.to_block = self.get_latest_block_number() continue logs = self.client.get_logs( self.all_contracts, self.from_block, self.to_block, ...
def get_forms(url): try: r = s.get(url) except Exception as e: print(e) exit() if (r.status_code == 404): print("URL Error") exit() soup = bs(r.content, "html.parser") return soup.find_all("form") def get_form_info(form): info = {} try: info["a...
The code scans a URL for SQL injection vulnerabilities by testing form inputs with special characters, submitting test data via POST/GET requests, and checking responses for signs of exploitation. It detects forms, iterates through inputs, injects test payloads, and reports vulnerability if detected.
def scan_url(url): vuln = False forms = get_forms(url) print("Detected {} forms on {}".format(len(forms), url)) for form in forms: form_info = get_form_info(form) for i in "\"'": data = {} names = [] for input_tag in form_info["inputs"]: ...
def cookies(cookie): try: name, value = cookie.split("=") s.cookies.set(name=name, value=value) except: print("Error setting cookies...") exit() def scan_url(url): vuln = False forms = get_forms(url) print("Detected {} forms on {}".format(len(forms), url)) for for...
The code parses command-line arguments for a URL scanner, validates request methods (GET/POST), handles cookies, and saves scan results to an output file. It checks input validity, processes the URL, and executes scanning with specified parameters.
def main(): global request_type, s parser = argparse.ArgumentParser() parser.add_argument("-o", default="outfile", help="output file, if not specified outfile will be used") parser.add_argument("-X", default="GET", h...
def search_entry_changed(self, event): search_pattern = self.search_entry.get() self.position_list.delete(0, END) self.text_preview.delete("1.0", "end") self.image_view.update_image(self.get_image_path(None)) self.filename_label.configure(text="") self.row_count_label.con...
This code initializes a GUI interface for an image viewer/inspector, setting up a sidebar with search functionality, a position list, and a back button, alongside an image preview area, metadata display (folder name, filename, row/column counts), and a text preview panel. The layout uses grid configurations for respons...
def __init__(self, parent, controller): self.controller = controller CTkFrame.__init__(self, parent) self.grid_rowconfigure((1, 2, 3), weight=1) self.grid_columnconfigure((1, 2 ,3), weight=1) self.sidebar_frame = CTkFrame(self, width=200, corner_radius=0, fg_color='#202020') ...
def refresh_folder_list(self): self.list_list.delete(0, END) folders = folder_opts.get_folders() if folders is not None: folders.sort() for folder in folders: self.list_list.insert(END, folder) def open_folder_command(self, controller): if hasattr(...
This code initializes a GUI sidebar with buttons for folder management. It sets up "OPEN," "CREATE FOLDER," "REMOVE FOLDER," and "EXIT" buttons, each linked to specific commands. The sidebar is styled with consistent colors, fonts, and layout, using CustomTkinter (CTk) components. The `__init__` method configures the U...
def __init__(self, parent, controller): self.controller = controller CTkListPage.__init__(self, parent) self.list_label_text("Folder List") self.refresh_folder_list() self.open_folder_button = CTkButton(self.sidebar_frame, text=" OPEN", corner_radi...
def get_cmake_toolchain_settings(config): settings = [] if config.os == "Windows" and config.generator != "ninja": settings += [ "-A", "Win32" if config.arch == "x86" else config.arch, ] if config.toolchain_file != "": settings += [ "-DCMAKE_TOOLCHAIN_FILE=" +...
The function constructs a CMake configure command with options like verbose output, build type, package manager settings, and compiler paths. It dynamically adds flags for vcpkg triplet and Boost paths on AppVeyor, specifies Ninja generator for Windows, and appends the source directory. The command adapts to configurat...
def get_cmake_configure_command(config): command = [ "cmake", "-DCMAKE_VERBOSE_MAKEFILE=TRUE", "-DCMAKE_EXPORT_COMPILE_COMMANDS=TRUE", "-DCMAKE_CONFIGURATION_TYPES=" + config.build_type, "-DCMAKE_BUILD_TYPE=" + config.build_type, "-DEXP_PKG_MGR=" + config.pkg_mgr, ...
def print_step(title): print() print("**************************************************") print("**** {}".format(title)) print("**************************************************") print() def get_cmake_configure_command(config): command = [ "cmake", "-DCMAKE_VERBOSE_MAKEFILE=TR...
The code's main task is to configure a project using CMake by generating and executing a configuration command based on the provided configuration. It prints a step message, retrieves the CMake command via `get_cmake_configure_command`, and runs it with `log_check_call` to handle logging and error checking during the c...
def configure(config): print_step("Configuring Project") cmake_configure_command = get_cmake_configure_command(config) log_check_call(cmake_configure_command)
def print_step(title): print() print("**************************************************") print("**** {}".format(title)) print("**************************************************") print() def get_default_toolchain_file(config): if config.pkg_mgr != "vcpkg": return "" try: i...
The main task of the code is to initialize a build environment by configuring directories, checking package manager versions, and setting up the environment based on the provided configuration parameters. It constructs a build directory path, prints configuration details, verifies toolchains, ensures the build director...
def initialize(config): print_step("Initializing") config.this_dir = os.path.dirname(os.path.realpath(__file__)) config.build_dir = os.path.join(config.this_dir, "out", "build", "py-{}-{}-{}-{}-{}-{}".format( config.pkg_mgr, config.generator, ("win" if config.os == "Windows" else "li...
def _validate_inputs( file_path: Optional[str], blob_url: Optional[str], language: Optional[str], auto_detect_source_language: Optional[bool], ): if not file_path and not blob_url: raise ValueError("Either file_path or blob_url must be provided.") if lang...
This method performs continuous speech recognition on audio from a local file or Azure Blob Storage, returning transcribed text. It supports language auto-detection (with configurable supported languages) and speaker diarization. Input validation ensures proper parameters, and the transcription is handled by either fil...
def transcribe_speech_from_file_continuous( self, file_path: Optional[str] = None, blob_url: Optional[str] = None, language: Optional[str] = None, auto_detect_source_language: Optional[bool] = False, auto_detect_supported_languages: Optional[List[str]] = None, sou...
def traverse(self, node): print(len(node.children), node.max_children) while len(node.children) == node.max_children: node = self.best_ucb(node) if node.terminal: return node else: return node.unvisited_child() def rollout(self, node): termina...
This code performs a Monte Carlo Tree Search (MCTS) within a time limit. It repeatedly traverses the tree to a leaf node, simulates outcomes (rollout), updates node values via backpropagation, and finally selects the best child node as the optimal move.
def search(self): start_time = time.time() while (time.time() - start_time) < self.max_time: leaf = self.traverse(self.root) sim_reward = self.rollout(leaf) self.backpropogate(leaf, sim_reward) return self.best_child(self.root)
def availablePositions(self): postions = [] for i in range(3): for j in range(3): if self.board[i,j] == 0: postions.append((i,j)) return postions def updateBoard(self, position): self.board[position] = self.pSymbol self.pSymbol = -...
This code simulates a game between two players for a specified number of rounds. It alternates turns, allowing each player to choose a move based on available positions. After each move, it checks for a win/draw, rewards players if a terminal state is reached, and resets the game state. The loop continues until the set...
def playWithBot(self, rounds=100): for i in range(rounds): if i%1000 == 0: print(f"Round: {i}") while not self.isOver: # Player 1 turn positions = self.availablePositions() p1_action = self.p1.actionChoice(positions, self.bo...
def encode_img(img1, img2): img1_pixels = img1.load() img2_pixels = img2.load() cover_up = Image.new('RGB', (img1.width, img1.height), 'black') cover_up_pixels = cover_up.load() for x in range(0, cover_up.width): for y in range(0, cover_up.height): br, bg, bb = img1_pixels[x, y] ar, ag, ab = ...
This code implements a Streamlit-based steganography tool for encoding/decoding data in images. Users can choose to encode (hide text/images within images) or decode (extract hidden data). It supports hiding text in images, embedding images within images, and extracting both text and images from steganographic outputs....
def main(): # Streamlit UI try: option = st.selectbox( 'Choose an action', ('Encode', 'Decode')) # Ask the user to choose either encode or decode if option == 'Encode': uploaded_file = st.file_uploader( "Choose a cover image", key='cover_image') # Input a...
def create_grid(self): grid = [[QPushButton(self) for j in range(self.game.get_size())] for i in range(self.game.get_size())] for i in range(self.game.get_size()): for j in range(self.game.get_size()): grid[i][j].move(j * int(self.w/self.game.get_size()), 200 + i * int(self.w...
This code initializes a main game window for "The Twelve game," setting its size, title, icon, and creating a game instance. It adds UI elements like info and difficulty buttons, a score label, and connects them to functions. Styles are loaded, and the window's grid, buttons, and score are refreshed to display initial ...
def __init__(self): super(MainWindow, self).__init__() self.h = 700 self.w = 500 self.setWindowTitle("The Twelve game") self.setWindowIcon(QtGui.QIcon("resources/main_ico.png")) self.setFixedHeight(self.h) self.setFixedWidth(self.w) self.game = Game() ...
def isOnlyinRow(puz_no, poss_coord): for coord in poss_dict[puz_no]: if coord != poss_coord and coord[0] == poss_coord[0] or isAnyConflict(puz_no, poss_coord): return False else: continue return True def isOnlyinCol(puz_no, poss_coord): for coord in poss_dict[puz_no]: if ...
This function identifies and solves Sudoku cells with only one possible candidate in their row, column, or box. It updates the puzzle grid, tracks solved cells, and eliminates possibilities from other candidates. If guessing is enabled, it records elimination dependencies.
def onlyOnes(): global amt_solved, new_elims for p_no in poss_dict: for pd_coord in poss_dict[p_no]: if isOnlyinRow(p_no, pd_coord) or isOnlyinCol(p_no, pd_coord) or isOnlyinBox(p_no, pd_coord): num_dict[p_no].append(pd_coord) puzzle_list[pd_coord[0]][pd_coord...
def isOnlyinRow(self, puz_no, poss_coord, check_dict): for coord in check_dict[puz_no]: if coord != poss_coord and coord[0] == poss_coord[0] or self.isAnyConflict(puz_no, poss_coord) and check_dict is not self.num_dict: return False else: continue return True def ...
This function checks for initial conflicts in a Sudoku puzzle by verifying if each number is unique in its row, column, and 3x3 box. If duplicates are found, it prints the conflicting number and coordinate, then raises a ValueError to indicate invalid input.
def check_initial_conflict(self): for no in self.num_dict: for coord in self.num_dict[no]: if self.isOnlyinRow(no, coord, self.num_dict) or self.isOnlyinCol(no, coord, self.num_dict) or self.isOnlyinBox(no, coord, self.num_dict): pass else: ...
def isOnlyinRow(self, puz_no, poss_coord, check_dict): for coord in check_dict[puz_no]: if coord != poss_coord and coord[0] == poss_coord[0] or self.isAnyConflict(puz_no, poss_coord) and check_dict is not self.num_dict: return False else: continue return True def ...
This method identifies and places numbers in a Sudoku puzzle that are the only possible candidates in their row, column, or 3x3 box. It updates the puzzle grid, tracks solved coordinates, and eliminates those candidates from other cells' possibilities. It also records eliminations for tracking dependencies if guessing ...
def onlyOnes(self): for p_no in self.poss_dict: for pd_coord in self.poss_dict[p_no]: if self.isOnlyinRow(p_no, pd_coord, self.poss_dict) or self.isOnlyinCol(p_no, pd_coord, self.poss_dict) or self.isOnlyinBox(p_no, pd_coord, self.poss_dict): self.num_dict[p_no].a...
def isOnlyinRow(puz_no, poss_coord): for coord in poss_dict[puz_no]: if coord != poss_coord and coord[0] == poss_coord[0] or isAnyConflict(puz_no, poss_coord): return False else: continue return True def isOnlyinCol(puz_no, poss_coord): for coord in poss_dict[puz_no]: if ...
This function identifies cells where a number is the only possible candidate in its row, column, or 3x3 box. It updates the puzzle grid, tracks solved cells, and removes that number from other cells' possibilities in the same row/column/box, aiding Sudoku solving through constraint propagation.
def onlyOnes(): global amt_solved, new_elims for p_no in poss_dict: for pd_coord in poss_dict[p_no]: if isOnlyinRow(p_no, pd_coord) or isOnlyinCol(p_no, pd_coord) or isOnlyinBox(p_no, pd_coord): num_dict[p_no].append(pd_coord) puzzle_list[pd_coord[0]][pd_coor...
def clearpuzzle(): global loadbool, clearbool, amt_solved, numberofentries, num_dict, numbers, solver_solved, newNum_dict, solved_coords, new_elims, guessSets, guessAmt, guessDependElim, isGuess, setExhausted, poss_dict, puzzle_list if numberofentries > 0: clear = messagebox.askyesno("New Puzzle","Are y...
This function loads a specific Sudoku example based on the input 'exno', clears the current puzzle, confirms user intent for the hardest puzzle (exno=9), initializes UI buttons with example numbers, populates coordinate mappings, and prepares the puzzle state for solving by updating display elements.
def loadexample(exno): global clearbool, num_dict, numbers, loadbool, numberofentries clearpuzzle() if clearbool or numberofentries == 0: if exno == 9: sure = messagebox.askokcancel("\"World's Hardest Sudoku\"","This one will take a few minutes to solve.") if exno != 9 or sure: ...
def isAnyConflict(puz_number2, coord_tuple2): if isInputConflict(puz_number2, coord_tuple2) == 1: return True if isInputConflict(puz_number2, coord_tuple2) == 2: return True elif isInputConflict(puz_number2, coord_tuple2) == 3: return True return False def onlyOnes(): gl...
The code attempts to solve a Sudoku puzzle by checking for conflicts in rows, columns, and 3x3 boxes to eliminate possibilities, iteratively updating the puzzle until no new eliminations occur or a maximum iteration limit is reached. It enforces a minimum of 17 entries for a unique solution and uses guessing if direct ...
def attemptsolve(): global numberofentries, num_dict, amt_solved, solver_solved, newNum_dict, new_elims, guessSets, guessAmt, guessDependElim, isGuess, setExhausted, poss_dict if numberofentries < 17: errmessage = messagebox.showerror("Not Enough Information", "There must be at least 17 entries for...
def isAnyConflict(self, puz_number2, coord_tuple2): if self.isInputConflict(puz_number2, coord_tuple2) == 1: return True if self.isInputConflict(puz_number2, coord_tuple2) == 2: return True elif self.isInputConflict(puz_number2, coord_tuple2) == 3: re...
The code solves a Sudoku puzzle by iteratively eliminating invalid possibilities for numbers in each cell based on row, column, and 3x3 box conflicts. It tracks solved coordinates, initializes potential positions, and applies heuristics like "only ones" and direct conflict elimination. If no progress is made, it resort...
def attempt_solve(self): # Keep list of coordinates for which the number in that coordinate is solved. for num in self.num_dict: for scrd in self.num_dict[num]: if scrd not in self.solved_coords: self.solved_coords.append(scrd) # Number of starting...
def action_translate(self, update_trie=True): src = self.languages_in.currentText() dest = self.languages_out.currentText() text = self.text_in.toPlainText() if text == "": return elif src == dest: self.text_out.setText(text) else: src...
This code initializes a GUI application with translation features. It sets up the main window, connects buttons to actions (translate, save, load, swap, clear), configures language selection dropdowns, enables event filtering for input text, and initializes autocomplete functionality by loading language-specific data f...
def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setup_ui(self) self.setWindowIcon(QtGui.QIcon("./icons/trans.png")) self.translate_button.clicked.connect(lambda: self.action_translate()) self.save_button.clicked.connect(lambda: self...
def insert(root, value): if root is None: return TreeNode(value) if value <= root.value: # Handle duplicates by appending to the right subtree root.left = insert(root.left, value) else: root.right = insert(root.right, value) return root def in_order_traversal(root, arr): if ...
The code performs three tasks: (1) constructs a Binary Search Tree (BST) by inserting each element from the input array and prints the in-order traversal after each insertion, (2) converts the original array into a min heap using a heap-building function, and (3) visualizes the min heap as a binary tree. The BST and mi...
def minHeapSort(arr): # Build a Binary Search Tree (BST) and display it root = None for value in arr: root = insert(root, value) in_order_list = [] in_order_traversal(root, in_order_list) # print("BST after inserting", value, ":") print(binarytree.build(in_order_list)...
def get_frame(self): """ Returns a rescaled image (244x419) of game. :return: window_image_rescaled (np.array): A numpy array of an image of the Clash Royale window """ window_dimensions = self.get_window_dimensions() screenshot = cv2.cvtColor(np.asarray(ui.screenshot())...
The code's main task is to return the current state of the Clash Royale arena by aggregating field data, elixir count, card information, and available choices into an ordered dictionary. It retrieves a game frame, processes it to extract field details, predicts elixir levels, and generates choice and card data, compili...
def get_state(self): """ Returns the current state of the Clash Royale arena. :return: state (dict): A dictionary containing data about the field, elixir-count, card, choices relevant to the current state of the game """ frame = self.get_frame() field_data = sel...
def remove_leading_whitespace(query, tokens): whitespace = collect_characters(query, string.whitespace) return query[len(whitespace):] def remove_word(query, tokens): word = collect_characters(query, string.ascii_letters + "_.*" + string.digits) if word == "NULL": ...
The main task of the code is to tokenize an input query string into individual elements such as keywords ("IS NOT", "IS", "!="), operators ((),;=><), identifiers, numbers, strings, and punctuation, while skipping whitespace. It processes the query character-by-character, using conditional checks to identify and extract...
def tokenize(query): tokens = [] while query: old_query = query if query[0:6] == "IS NOT": tokens.append(query[0:6]) query = query[6:] continue if query[0] in string.whitespace: query = remove_leading_whitespace(query, tokens) ...
def begin_deferred(self): """ Begins a transaction and handles setting it up """ self.database = deepcopy(_ALL_DATABASES[self.filename]) def lockable(self, command): """ Sees if the element can be locked :param command: The type of the query we want to perform ...
The code processes SQL statements by tokenizing them, validating syntax (e.g., semicolon), and executing commands like BEGIN/COMMIT/ROLLBACK for transactions, CREATE/DROP for DDL, and INSERT/SELECT/UPDATE/DELETE for DML. It interacts with a database object, manages auto-commit mode, and returns query results as tuples ...
def execute(self, statement): """ Takes a SQL statement. Returns a list of tuples (empty unless select statement with rows to return). """ tokens = tokenize(statement) result = None if tokens[-1] != ";": raise QueryError("Query missing ';' at t...
def inbounds(self, x: int, y: int) -> bool: """Check if two coordinates are within the boundaries of the board. Args: x (int): Row on the board y (int): Column on the board Returns: bool: True if the coordinates are inbounds, otherwise False """ return (x >= 0) and (x < self.rows) and ...
This function moves an entity from coordinates (x, y) to (xf, yf) on a grid, ensuring the move is valid by verifying the entity's current position exists, the target is free, and both coordinates are inbounds. It updates the grid state, removes the entity from its old location, and records its new position in tracking ...
def move(self, x: int, y: int, xf: int, yf: int): """Move an entity from (x, y) to (xf, yf). The entity must exist on the board at (x, y) already, and (xf, yf) must be a free space on the board, and both coordinates must be valid, inbound coordinates. Args: x (int): Row on the board of the entity ...
def get_derivative( function, phi, alpha, x_prime, sym_dict, data_dictionary, initial_struct, NUM_ATOMS, UNIQUE_IND, epsilon=0.01, ): """calculates numerical derivative of the chi squared with respect to the stepsize. Args: functions: list of callable optimiz...
The function performs a Wolfe line search to determine the optimal step size (alpha) for descent in optimization, ensuring the strong Wolfe conditions (Armijo and curvature). It iteratively evaluates the objective function and its derivative, adjusting alpha to satisfy the conditions. If unsuccessful, it invokes a zoom...
def wolfe_line_search( function, phi_0, x_prime, sym_dict, dist_test_dict, struct, NUM_ATOMS, UNIQUE_IND, epsilon=0.01, max_iter=10, c1=0.0001, c2=0.9, ): """Line search function to find the optimal step size along a descent path. Uses algorithm described in Wrigh...
def check_sysfs(): if not os.path.exists(f"{INTERLEAVE_WEIGHT_DIR}/node/node0/interleave_weight"): print(f"error: sysfs not found at {INTERLEAVE_WEIGHT_DIR}") sys.exit(-1) def check_root_perm(): if os.geteuid() != 0: print("error: bwactl.py can only be executed with root permission.") ...
The main task of the code is to analyze system memory bandwidth using MLC (Memory Latency Checker) results, either from a provided file or by executing MLC directly. It processes the output to generate a bandwidth matrix, calculates a ratio matrix based on NUMA node topology, and displays the results. The script also h...
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--mlc-file", type=str, required=False, help="Pass mlc result from file instead of running it", ) parser.add_argument( "--lstopo-file", type=str, required=False, help="Pass...
def run_whisper(self, path): eprint("Running Whisper...") return self.whisper_model.transcribe(path) def run_gentle(self, path, text): eprint("Running Gentle...") with tempfile.NamedTemporaryFile() as f: f.write(text.encode()) f.flush() cmd = f'curl -...
The main task of the code is to transcribe audio from a given path by first validating the file's existence, using Whisper for initial transcription, aligning words with Gentle, and returning the structured result as an itree. It resolves the path, checks validity, converts to string, runs Whisper for text, then Gentle...
def transcribe(self, path: any): path = Path(path).resolve() if not path.exists(): raise Exception(f"Path does not exist: {path}") path = str(path) whisper_output = self.run_whisper(path) text = whisper_output["text"] gentle_output = self.run_gentle(path, te...
def __draw_background(self): self.screen.fill((255, 255, 255)) map_position = (self.__margin, self.__margin) self.screen.blit(self.__img_bg, map_position) def __draw_buttons(self): rects = [] for button in self.__buttons: rects.append(button.draw(self.screen)) ...
The main task of the code is to render a game screen by drawing background, buttons, targets, and moving elements (kiri). It updates the display with specific regions (`rects`) for efficiency, using `pygame.display.update()` unless a full flip is required. The method handles conditional redraws of elements and returns ...
def __on_render(self, pre_rects): rects = [] self.__draw_background() rects.extend(self.__draw_buttons()) rects.append(self.__draw_target()) rects.append(self.__draw_kiri()) # kiri get into the box if equal_pos(self.start, self.stop) and not self.__kiri.moving: ...
def on_init(self): "init the game" pygame.init() logo = pygame.image.load(SOURCES.logo) pygame.display.set_icon(logo) pygame.display.set_caption("kiri walk game") self.screen = pygame.display.set_mode(self.__window_size) self.__draw_background() self.__dra...
The code defines the main game loop that initializes the game, processes events, updates game logic, renders graphics with optimized redraws, maintains a consistent frame rate using a clock, and cleans up resources when the game ends.
def on_run(self): "run the game" self.on_init() clock = pygame.time.Clock() pre_rects = [] while (self._running): for event in pygame.event.get(): self.__on_event(event) self.__on_loop() pre_rects = self.__on_render(pre_rects) ...
def denoise_text(text): text = strip_html(text) text = remove_between_square_brackets(text) return text def remove_special_characters(text, remove_digits=True): pattern = r'[^a-zA-z0-9\s]' if not remove_digits else r'[^a-zA-z\s]' text = re.sub(pattern, '', text) return text def normalize(words):...
The code processes input text by denoising, expanding contractions, removing special characters, tokenizing, normalizing (e.g., lowercasing), and lemmatizing words, then returns the cleaned, lemmatized text as a space-separated string.
def normalize_and_lemmaize(input): sample = denoise_text(input) sample = contractions.fix(sample) sample = remove_special_characters(sample) words = nltk.word_tokenize(sample) words = normalize(words) lemmas = lemmatize(words) return ' '.join(lemmas)
def preprocess(product_ratings): product_ratings.drop(['reviews_doRecommend', 'reviews_didPurchase', 'categories', 'reviews_date', 'manufacturer', 'categories', 'brand', 'reviews_text', 'reviews_title', 'reviews_userCity', 'reviews_userProvince', 'user_sentiment', 'id'], axis=1, inplace=True) prod_rat...
The code recommends products to a user based on collaborative filtering using SVD on their review ratings, then adjusts recommendations with product sentiment scores, returning top 5 items with highest positive sentiment percentages.
def rcmd(username): username = username.lower() data_in = pd.read_csv('datasets/sample30.csv') data_in['reviews_username'] = data_in['reviews_username'].str.lower() if username not in data_in['reviews_username'].unique(): return('Sorry! User not Found!!! ') data = preprocess(data_in) ...
def rf_weights(X, Y, DecisionTreeRegressor, Xeval=None, min_impurity_decrease=0, min_mrss_grid=[0], min_samples_leaf_factor=0.1, num_trees=1000, criterion="local_linear_grad", random_state=None): weight_list = [] n = len(Y...
The function estimates the derivative of a fitted model `fhat` using a local polynomial approach with random forest weights. It computes influence weights via a swapped feature matrix, performs cross-validation to select optimal penalty parameters, and applies penalized local polynomial regression to derive the derivat...
def derivative_estimate(X, Y, fhat, d=0, degree=2, train_ind=None, pen_grid=np.array([0]), min_mrss_grid=np.array([0]), random_state=None): if min_mrss_grid is None: min_mrss_grid = [np.mean((Y[train_ind]-fhat[train_ind])**2)] v = np.eye(1, np.shape(X)[1], d) # The swapped version is required beca...
def prepare_mail_args(self): """Prepare email arguments before sending.""" subject = self.get_formatted_subject() html_content, plain_text_content = self.prepare_mail_text() from_email = self.get_from_email() recipient_list = self.get_recipient_list() files = self.get_fil...
The main task of the code is to send an email with HTML content and attachments using the EmailMultiAlternatives class. It prepares email arguments, attaches HTML and files, sends the email, and returns True on success or False on failure (e.g., HTTPError), while logging errors and triggering success/failure callbacks.
def send(self) -> bool: """Send email. Returns: True: if it succeeded False: if it failed """ email_args = self.prepare_mail_args() html_message = email_args.pop("html_message") files = email_args.pop("files") mail = EmailMultiAlternativ...
def _marble_in_cell(self, left=None, top=None) -> bool: """Returns true if the selected cell has a marble in it, otherwise False is returned. By default, this method will use the current selected cell to define left and top. Default arguments `left` and `top` can be changed to specify a differen...
The code's main task is to handle user input for selecting Kuba game cells via mouse clicks, process directional key inputs to move marbles, update the game board state, and render the board along with turn and capture information in real-time using Pygame.
def play(self) -> None: """Start playing Kuba.""" while self._running: self._board.update_board() for event in pygame.event.get(): if event.type == pygame.QUIT: self._running = False if event.type == pygame.MOUSEBUTTONDOWN: ...
def getOptionsDirectDerived(ciType, attribute, mapDirection, columnsObj): ##print("getOptionsDirectDerived rel method") options = [] parent = getParenthoodByCI(ciType.strip(), mapDirection, columnsObj) cis = getCITypesByParent(parent, columnsObj, mapDirection) for ci in cis: options.append({"condition": ci, "at...
This function processes a mapTypeDetails string to construct a structured mapTypeObject, determining its type (concatenation, derived, direct, skip, or list) based on input patterns. It handles values, relations, attributes, and lists, including recursive calls for nested structures, and returns the mapped object with ...
def getMaptype(mapTypeDetails, name, endpoint, datatype, direction, columnsObj, required, dataformat, *target_attr): ##print("getMaptype method") mapTypeObject = {} if "values:" in mapTypeDetails: values = mapTypeDetails.replace("values:", " ").strip().split("*") mapTypeObject["mapType"] = "concatenation" mapT...
def getColNumberByName(name, sheetName): colnumber = 0 sheet = workbook.sheet_by_name(sheetName.strip()) for colnum in range(sheet.ncols): name = name.replace('\n', ' ').replace('\r', '').strip() columnHeader = sheet.cell(0, colnum).value.replace('\n', ' ').replace('\r', '') if name in columnHeader: colnum...
The code processes a spreadsheet to map relationships between source and target systems, applying filters and mappings. It identifies parent-child CI relationships, handles reference objects, and constructs structured relationship mappings with attributes, endpoints, and exceptions for specific targets like ESL or OMI....
def processRelationshipsSheet(sheetName, sheetID, sourceSys, integration, mappingRootObj, columnsObj, targets, excludeTarget): # print("processing rel method") sheet = workbook.sheet_by_name(sheetName.strip()) mapBySource = {} mapObj = {} mapObj["map"] = [] findMappingSourceSysRoot = next((item for item ...
def getListOptions(source, sourceColumn, sourceValueColumn, targetValueColumn, sheetName, mapDirection, attribute, excludeTarget, preLoadedValues): # print("getListOptions rel method") options = [] if len(preLoadedValues) > 0: # Exception ESL list items not in sheets for item in preLoadedValues: values...
This function processes mapping details based on the 'detailsKey' parameter, structuring options, relations, values, formulas, and conditions into a dictionary. It handles nested data formats, exceptions, and dynamic value generation, returning a categorized 'mapTypeDetails' dictionary for configuration mapping.
def getMaptypeDetails(mappingItem, itemName, detailsKey, details, direction, columnsObj, name, endpoint, datatype, required, dataformat): mapTypeDetails = {} if detailsKey == "options": options = [] optionsDetails = details[1].split(",") # Exception ESL non sheet values if "{" in details[1]: mapping...
def getColNumberByName(name, sheetName): colnumber = 0 sheet = workbook.sheet_by_name(sheetName.strip()) for colnum in range(sheet.ncols): name = name.replace('\n', ' ').replace('\r', '').strip() columnHeader = sheet.cell(0, colnum).value.replace('\n', ' ').replace('\r', '') if name in columnHeader: colnum...
The function processes an Excel sheet to map attributes from a source system to target systems. It applies filters based on sheet and target directions, extracts column data, and constructs mapping objects with attributes like name, data type, and target details. It handles calculations, duplicates, and ensures correct...
def processSheet(sheetName, sheetID, sourceSys, integration, mappingRootObj, columnsObj, targets): ##print("processing attr method") sheet = workbook.sheet_by_name(sheetName.strip()) mapBySource = {} mapObj = {} mapObj["map"] = [] findMappingSourceSysRoot = next((item for item in mappingRootObj if item["source"] ...
def part2_1(): data = genfromtxt( os.getcwd() + '\ex2data2.txt', delimiter = ',' ) plot( data ) pyplot.show() def part2_2(): data = genfromtxt( os.getcwd() + '\ex2data2.txt', delimiter = ',' ) X = mapFeature( data[:, 0], data[:, 1] ) def part2_3(): data = genfromtxt( os.getcwd() + '\ex2data2.txt', delimi...
The main task of the code is to execute four subtasks (part2_1 to part2_4) sequentially after configuring print settings for precision and line width. It likely organizes a multi-part computational workflow, where each part handles distinct operations, possibly for data analysis, visualization, or algorithm execution, ...
def main(): set_printoptions(precision=6, linewidth=200) part2_1() part2_2() part2_3() part2_4()
def featureNormalizeVect(X): mu = mean(X, axis=0) sigma = std(X, axis=0, ddof=1) norm_data = (X - mu)/sigma return norm_data, mu, sigma def computeCostVect(X, y, theta): """Compute cost, vectorized version""" m = len(y) term = hypo(X, theta) - y return (term.T.dot(term) / (2 * m))[0, 0...
The main task of the code is to perform linear regression with gradient descent on housing data, testing different learning rates (0.01, 0.03, 0.1, 0.3, 1) to optimize model parameters (theta). It normalizes features, computes initial cost, iteratively updates theta, and predicts house prices for a test case (1650 sq f...
def part2_2(): data = genfromtxt(os.getcwd() + "\ex1data2.txt", delimiter=',') X = data[:, 0:2] y = data[:, 2:3] m = shape(X)[0] n = shape(X)[1] X, mu, sigma = featureNormalizeVect(X) X = c_[ones((m, 1)), X] alphas = [0.01, 0.03, 0.1, 0.3, 1] iters = 1500 for alpha in alphas: ...
def randInitializeWeights(L_in, L_out): e = 0.12 w = random.random((L_out, L_in + 1)) * 2 * e - e return w def recodeLabel( y, k ): m = len(y) out = zeros( ( k, m ) ) for i in range(0, m): out[y[i]-1, i] = 1 return out def paramUnroll( nn_params, input_layer_size, hidden_layer_size, num_labels ): theta1_ele...
This code trains a neural network with one hidden layer on the ex4data1 dataset using gradient descent. It loads data, initializes weights, computes cost and gradients, optimizes parameters via fmin_cg, and evaluates accuracy by comparing predicted labels to actual labels, printing the percentage of correct predictions...
def part2_6(): mat = scipy.io.loadmat( str(os.getcwd()) + "/ex4data1.mat" ) X, y = mat['X'], mat['y'] m, n = shape(X) input_layer_size = 400 hidden_layer_size = 25 num_labels = 10 lamda = 1.0 theta1 = randInitializeWeights( 400, 25 ) theta2 = randInitializeWeights( 25, 10 ) yk = recodeLabel(...
def part2_1(): data = genfromtxt(os.getcwd() + "\ex1data2.txt", delimiter = ',') n = shape(data)[1] print(n) X, y = data[:, 0:n-1], data[:,n-1 : n] m = shape(X)[0] y = y.reshape(m, 1) # norm_data, mu, sigma = featureNormalizeLoop(X) norm_data, mu, sigma = featureNormalizeVect(X) nor...
The main task of the code is to sequentially execute three sub-functions—part2_1(), part2_2(), and part2_3()—within the main() function. This structure organizes and triggers specific operations or tasks defined in each sub-function, likely as part of a modular program or project.
def main(): part2_1() part2_2() part2_3()
def costFunc(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lamda): return NeuralNetCostFunc(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lamda)[0] def randomInitWeights(L_in, L_out): epsilon = 0.12 # Ideally epsilon = sqrt(6) / (L_in + ...
The code loads a dataset and pre-trained neural network weights, computes the cost function with regularization, initializes random weights, and evaluates model accuracy. It uses a neural network with 400 input, 25 hidden, and 10 output units to classify data, applying regularization (λ=3) during optimization and verif...
def main(): mat = scipy.io.loadmat(str(getcwd()) + "/ex4data1.mat") X, y = mat['X'], mat['y'] input_layer_size, hidden_layer_size, num_labels = 400, 25, 10 mat = scipy.io.loadmat(str(getcwd()) + "/ex4weights.mat") theta1, theta2 = mat['Theta1'], mat['Theta2'] nn_params = array([theta1.T.reshap...
def debugInitializeWeights(fan_out, fan_in): num_elements = fan_out * (1+fan_in) w = array([sin(x) / 10 for x in range(1, num_elements+1)]) w = w.reshape( 1+fan_in, fan_out ).T return w def mod( length, divisor ): dividend = array([x for x in range(1, length+1)]) divisor = array([divisor for x in range(1, length...
This code verifies the correctness of gradient computations in a neural network by comparing the analytical gradient (from nnCostFunction) with a numerical gradient (computed via finite differences). It initializes a small neural network with random weights, generates synthetic data, computes both gradients, and calcul...
def checkNNGradients( lamda = 0.0 ): input_layer_size = 3 hidden_layer_size = 5 num_labels = 3 m = 5 theta1 = debugInitializeWeights( hidden_layer_size, input_layer_size ) theta2 = debugInitializeWeights( num_labels, hidden_layer_size ) X = debugInitializeWeights( m, input_layer_size - 1 ) y = 1 + m...
def debugInitWeights(fan_out, fan_in): w = zeros((fan_out, fan_in+1)) w =[sin(x)/10 for x in range(1, w.size+1)] return asarray(w).reshape(fan_out, fan_in+1) def NeuralNetCostFunc(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lamda): m, n = shape(X) J = 0 K = num_labels ...
This function checks the correctness of gradient computation in a neural network by comparing analytical gradients (from backpropagation) with numerical gradients. It initializes network parameters, computes cost and gradients via the NeuralNetCostFunc, calculates numerical gradients, and prints the relative difference...
def gradChecking(lamda = None): if lamda == None: lamda = 0 input_layer_size = 3 hidden_layer_size = 5 num_labels = 3 m = 5 X = debugInitWeights(m, input_layer_size - 1) y = asarray([1 + (i % num_labels) for i in range(0, m)]).reshape(m, 1) theta1 = debugInitWeights(hidden_laye...
def make_move(self): """ Finds and plays the best move """ try: with open('rnd.pickle','rb') as rnd: i = pickle.load(rnd) i = 1 + i except: i = 0 with open('rnd.pickle','wb') as rnd: pickle.dump(i,rnd) ...
The main task of the code is to execute a specified number of self-play games. It retrieves the number of games from `pathField`, iterates through each game, updates the game count in `pathField1`, makes moves until the game ends, and triggers a new game upon completion. If no input is provided, it exits early. The loo...
def selfplay(self): x = self.pathField.text() if x == '': print('no games') return else: self.itr = 1 while self.itr <= int(x): while not self.board.is_game_over(): self.pathField1.setText('#games played: '+ str(...
def drawBoard(self): """ Draw a chess board for the starting position and then redraw it for every move. """ self.svgBoard = self.board._repr_svg_().encode("UTF-8") self.svgDrawBoard = self.svgWidget.load(self.svgBoard) return self.svgDrawBoard def make_move(self): ...
This method handles left mouse clicks to enable chess piece movement by selecting a piece and target square. It converts mouse coordinates to chess board positions, checks if the move is legal, updates the board state, tracks the last move, increments a move counter, and redraws the board. It also checks for game over ...
def mousePressEvent(self, event): """ Handles the left mouse click and enables moving the chess pieces by first clicking on the chess piece and then on the target square. """ if not self.board.is_game_over(): if event.x() <= self.boardSize and event.y() <= self.board...
def __insert_cust(self, route, index, customer): new_route = copy.deepcopy(route) new_route.insert(index, customer) return new_route def __update_time(self, route, i): if i == 0: route[i]["vehicle_ready_time"] = 0 else: route[i]["vehicle_ready_time"] = r...
The code implements a routing algorithm for vehicle routing problems, constructing routes by inserting customers based on time windows and feasibility checks, then optimizing via large neighborhood search (LNS) to improve the initial solution. It iteratively builds routes starting with the earliest available customer, ...
def routing(self): all_id = self.customers.keys() remaining_id = set(all_id) served_id = [] while len(remaining_id) != 0: remaining_custs = {id: self.customers[id] for id in remaining_id} # New route route = [] # Choose an initial customer ...
def __data_point_fits_in_cluster_and_isnt_clustered(self, data_point, index_data_point, centroid): return (self.datapoint_fits_in_cluster(data_point, centroid) and (not self.__data_point_already_in_cluster[index_data_point])) def __include_data_point_in_cluster(self, data_point, index_data_point, index_centroid...
This code assigns each data point to the most suitable cluster by checking its fit with existing centroids. If a data point doesn't fit any cluster, a new cluster is created. The algorithm iterates through all data points and centroids, updating cluster memberships dynamically. It returns the final list of clusters aft...
def __clustering_algorithm(self, dataset_list, centroids): for index_data_point, data_point in enumerate(dataset_list): for index_centroid, centroid in enumerate(centroids): if self.__data_point_fits_in_cluster_and_isnt_clustered(data_point, index_data_point, centroid): ...
def is_nan(val): # check if the value is NaN (np.isnan didn't work for varied input types) # yes, this is confusing. return val != val def get_data(values, activity, prev_data, f): if activity == "batting": page_values = batting_data(values, prev_data) elif activity == "bowling": pag...
The main task of the code is to parse specific HTML tables containing "Innings by innings list" data, extract and clean row values, validate them against predefined formats, append valid rows to a DataFrame, and return the updated DataFrame along with flags indicating parsing success and data append status. It handles ...
def parse_page(df, html, activity, f, last_row, can_append, data_types): global prev_data idx = get_idx[activity] format_str = f"{f}_{activity}" for table in html.css("table.engineTable"): # There are a few table.engineTable in the page. We want the one that has the match if table.select...
def getpage(page_num, f, activity): from_cache = False format_id = format_lookup[f] url = f"https://stats.espncricinfo.com/ci/engine/stats/index.html?class={format_id};filter=advanced;orderby=start;page={page_num};size=200;template=results;type={activity};view=innings" try: print(url) ...
The code scrapes sports statistics data for batting, bowling, and team activities across different formats. It processes HTML pages, converts data to specified types, caches results, and saves them as pickle/CSV files. It handles pagination, skips incomplete pages, and manages errors like unknown team codes, ensuring s...
def scrape_pages(): for activity in ( "batting", "bowling", "team", ): if activity == "batting": data_types = { "mins": "Int32", "bf": "Int32", "4s": "Int32", "6s": "Int32", "sr": float, ...
def continue_scenario(self, text, state, user_id): steps = SCENARIO[state.scenario_name]['steps'] step = steps[state.step_name] handlers = getattr(handler, step['handler']) if handlers(text=text, context=state.context): next_step = steps[step['next_step']] self.s...
This method processes VkBot events by checking if they are new messages. It extracts user ID and text, retrieves the user's state, and either continues an existing scenario or determines intent from the text. If no intent matches, it sends a default response.
def on_event(self, event): if event.type != VkBotEventType.MESSAGE_NEW: log_obj.info('I dont know how to work with this event %s', event.type) return user_id = event.object.message['from_id'] text = event.message.text state = UserState.get(user_id=str(user_id)) ...
def generator_128_to_64(self, image): with tf.variable_scope("generator"): return self.g_128_to_64(image) def generator_64_to_128(self, image, d6): with tf.variable_scope("generator"): return self.g_64_to_128(image, d6) def generator_128_to_256(self, d128): with tf.variab...
This code constructs a multi-scale GAN model for image generation, defining placeholders, generators, discriminators, and loss functions. It processes input images at different resolutions (64x64, 128x128, 256x256), generates fake images, computes adversarial and L1 losses, and organizes trainable variables for optimiz...
def build_model(self, size, phase): self.real_data = tf.placeholder(tf.float32, [self.batch_size, size, size, self.input_c_dim + self.output_c_dim], name='real_A_and_B_images') self.real_B_256 = self.real_data[:, :, :, :self.input_c_dim] self.real_B_128 = tf.imag...
def hop_count(self, src, dest, boats_reduced=True): #unweight the water paths if Jack still has a boat card if (boats_reduced) and (len(self.boat_cards) < 2): self.set_travel_weight(BOAT_MOVE, 1) shortest = nx.shortest_path_length(self.graph, source=src, target=dest, weight=...
The code identifies the closest target to the current position by calculating distances between self.pos and each target in self.targets. It updates the best_option and best_distance variables iteratively, then sets self.active_target to the closest target. If no valid target is found (best_option remains 0), it logs a...
def choose_closest_target(self): best_distance = 10000000 best_option = 0 for option in self.targets: d = self.hop_count(self.pos, option) if d < best_distance: best_option = option best_distance = d if bes...
def print(self, *msg): if (self.output_func == None): print(*msg) else: self.output_func(TEXT_MSG, *msg) self.log_to_file(*msg) def turn_count(self): return len(self.path_used) def godmode_print(self, *msg): if (self.godmode): self.print(*msg) ...
The code's main task is to display the current game status by printing tracked elements (crimes, clues, positions), remaining cards for each category, moves left, and hidden path/targets. It updates the game state UI/console with player progress, resource counts, and debug information via `print` and `godmode_print` me...
def status(self): self.print() self.print("Crimes: ", self.crimes) self.print("Clues: ", self.clues) self.print("ipos: ", self.ipos) self.print("Coach cards: ", 2 - len(self.coach_cards)) self.print("Alley cards: ", 2 - len(self.alley_cards)) self.print("Boat card...
def print(self, *msg): if (self.output_func == None): print(*msg) else: self.output_func(TEXT_MSG, *msg) self.log_to_file(*msg) def is_loc_adjacent(self, loc): loc_good = False for num in range(0,3): if nx.shortest_path_length(self.graph, sourc...
The code validates a list of locations for clue search by checking if they are not crime sites and adjacent to an "ipos." It prevents movement during the search, iterates through positions, and appends a clue to the list if a location is in the "path_used," then breaks the loop. If invalid, it returns early with error ...
def clue_search(self, pos_list): # Set flag to prevent players from moving after they started searching for clues self.it_is_jacks_turn = True for loc in pos_list: if loc in self.crimes: self.print("\033[1m", loc, "\033[0m is a crime location. Please enter a...
def rate_nodes(self): self.node_safety = {} self.max_safety = 0 for loc, (x, y) in positions: if 'c' not in loc: self.node_safety[loc] = self.location_safety_rating(loc) if self.node_safety[loc] > self.max_safety: self.max_safety =...
The code initializes a game environment by setting up a graph with weighted edges for pathfinding, configuring game state variables (e.g., targets, clues, movement flags), and assigning safety-based weights to edges for investigator movement. It prepares the graph for strategic decision-making by differentiating betwee...
def __init__(self, g, ipos): self.file = open('whitehall.log', 'w') self.graph = g self.ipos = ipos self.godmode = False self.win = None self.pos = 0 self.it_is_jacks_turn = False self.game_in_progress = False self.targets = [] sel...
def hop_count(self, src, dest, boats_reduced=True): #unweight the water paths if Jack still has a boat card if (boats_reduced) and (len(self.boat_cards) < 2): self.set_travel_weight(BOAT_MOVE, 1) shortest = nx.shortest_path_length(self.graph, source=src, target=dest, weight=...
This code poisons or unpoisons investigators based on their proximity to Jack's position. It checks if investigators can be reached in ≤2 moves, then marks them as poisoned, calling poison_location() for each. If already poisoned, it reverses the effect. The is_poison list tracks affected investigators, with debug prin...
def poison_investigators(self, adjust): if not hasattr(self, "is_poison"): self.is_poison = [] if len(self.is_poison) == 0: for num in range (0, 3): # Only poison if the investigator crossing can be reached by Jack in less than 3 moves if self.hop...
def set_travel_weight(self, transport_type, weight): #self.godmode_print("set_travel_weight:", transport_type, weight) for u, v in self.graph.out_edges(): if self.graph.edges[u, v]['transport'] == transport_type: self.graph.edges[u, v]['weight'] = weight self....
The function determines a valid coach path for Jack by temporarily poisoning water and alley routes to prevent boat use, evaluating random shortest paths while avoiding the active target, and selecting a path with acceptable cost based on remaining turns. It restores original weights if Jack has insufficient cards for ...
def pick_a_coach_path(self): # compute shortest path without any poisoned paths since Jack can move through investigators using a coach # but... Jack cannot take a boat at the same time, so poison the water routes self.set_travel_weight(BOAT_MOVE, POISON) self.set_travel_weight(...
def investigator_distance(self, num): # Find the vertex belonging to the `num` ivestigator v = self.ipos[num] distance = nx.shortest_path_length(self.graph, source=v, target=self.pos, weight='i_weight') return distance def godmode_print(self, *msg): if (self.godmode): ...
The function determines if Jack should use a coach card by evaluating proximity to investigators, average distance, and movement options. It checks if investigators are too close, Jack is on a clue, or free edges are limited, deciding to return True if conditions suggest using a coach card to avoid being cornered.
def consider_coach_move(self): ret = False if len(self.coach_cards) < 2: closest = 100 average = 0 dist = [0, 0, 0] # Find how far away each investigator is from Jack for num in range(0,3): dist[num] = self.investi...
def poison_investigators(self, adjust): if not hasattr(self, "is_poison"): self.is_poison = [] if len(self.is_poison) == 0: for num in range (0, 3): # Only poison if the investigator crossing can be reached by Jack in less than 3 moves if self.hop...
This function checks if a move from 'src' to 'dest' is possible with a safety weight of 1, temporarily applying poison effects to travel weights, calculating the shortest path, and restoring original weights if card counts are insufficient. It returns True if the path weight equals 1, indicating a valid move.
def normal_move_possible(self, src, dest): ret = False self.poison_investigators(POISON) self.set_travel_weight(BOAT_MOVE, POISON) self.set_travel_weight(ALLEY_MOVE, POISON) v1 = src v2 = dest path_weight = nx.shortest_path_length(self.graph, source=v1, t...
def poison_investigators(self, adjust): if not hasattr(self, "is_poison"): self.is_poison = [] if len(self.is_poison) == 0: for num in range (0, 3): # Only poison if the investigator crossing can be reached by Jack in less than 3 moves if self.hop...
The main task of the code is to determine the optimal path for an entity (e.g., Jack) to reach a target location in a graph, considering weighted safety constraints, potential blockages, and movement types (normal, coach, boat, alley). It calculates shortest paths, handles trapping scenarios, adjusts for poisoned/deter...
def pick_a_path_helper(self, deterrent): move_type = NORMAL_MOVE # Poison the position of the investigators (i.e. add weights) # TODO: if getting close to the end of the round and still have coach cards, maybe don't poison inspector paths and if one is chosen, use a coach? self.poison_i...
def parse_args(): parser = ArgumentParser() parser.add_argument("-s", "--since", required=True) parser.add_argument("output") return parser.parse_args() def read_pgpass(): credentials = defaultdict(dict) with open(os.path.expanduser("~/.pgpass")) as fh: for line in fh: hostna...
The main task of the code is to process data from a PostgreSQL database (dndb) and store statistics in an SQLite database (statsdb) for each month starting from a specified date. It iterates through months, calling functions to record "orphan" and "adopt" actions, track commits, and updates the start date to the next m...
def main(): args = parse_args() start = date_parse(args.since) statsdb = sqlite3.connect(args.output) pg_credentials = read_pgpass() dndb_conn = psycopg2.connect( dbname=DN_DB, user=DN_USER, password=pg_credentials[DN_DB][DN_USER], host=DN_HOST, ) dndb = dndb_...
def parse_arguments_from_cmd(self): parser = argparse.ArgumentParser() parser.add_argument("--from", help="Departure city") parser.add_argument("--to", nargs='+', help="Destination city") try: args, unknown = parser.parse_known_args() args_dict = vars(args) ...
This code parses command-line arguments to retrieve departure and arrival cities, fetches primary airports for these cities, and determines the cheapest flight between them. If valid airports and flight data are found, it prints the destination city and price. Otherwise, it outputs error messages from the airport or fl...
def start(self): cities = self.parse_arguments_from_cmd() airports_response = self.get_main_airport_of_city(cities["from"], cities["to"]) if airports_response["data"]: departure_airport, arrival_airports = airports_response["data"] cheapest_flight = self.get_best_flight_...