dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def initialise(db): cursor = db.cursor() # Blocks cursor.execute('''CREATE TABLE IF NOT EXISTS blocks( block_index INTEGER UNIQUE, block_hash TEXT UNIQUE, block_time INTEGER, PRIMARY KEY (block_index, block_hash)) ...
The code synchronizes a database with the Bitcoin blockchain by processing blocks and transactions. It handles blockchain reorganizations, parses transactions, checks for asset conservation, and manages the mempool. It ensures the database stays updated with the latest blocks, rolls back on reorgs, and periodically sna...
def follow (db): cursor = db.cursor() # Initialise. initialise(db) # Get index of last block. try: block_index = util.last_block(db)['block_index'] + 1 # Reparse all transactions if minor version has changed. minor_version = cursor.execute('PRAGMA user_version').fetchall()...
def random_initialize_center(self, pixels): num_samples, dim = pixels.shape centroids = np.zeros((self.k, dim)) index = np.array(random.sample(range(0, num_samples), self.k)) for i in range(self.k): centroids[i] = pixels[index[i]] return centroids def update_cluster_l...
The main task of the code is to perform K-means clustering on input pixel data. It initializes centroids randomly, iteratively updates cluster labels and centroids until convergence or max iterations, and returns the final centroids and cluster assignments. The code includes checks for insufficient data, iteration coun...
def forward(self, pixels): if pixels.shape[0] <= self.k: print("The number of k is too big!") return random.seed(555) tic = time.time() centroids = self.random_initialize_center(pixels) count = 0 for _ in range(self.max_i...
def random_initialize_center(self, pixels): num_samples, dim = pixels.shape centroids = np.zeros((self.k, dim)) index = np.array(random.sample(range(0, num_samples), self.k)) for i in range(self.k): centroids[i] = pixels[index[i]] return centroids def update_cluster_l...
This code implements K-means clustering on input pixel data. It initializes centroids randomly, iteratively updates cluster assignments and centroids, and terminates when convergence or max iterations are reached. The function returns final centroids and cluster labels while printing iteration count, loss values, and e...
def forward(self, pixels): if pixels.shape[0] <= self.k: print("The number of k is too big!") return random.seed(555) tic = time.time() centroids = self.random_initialize_center(pixels) cluster_labels = np.zeros((pixels.shape[0],...
def countLines(self): """returns the number of the lines in the file """ return len(self.__getLines__()) def countWords(self): """returns the number of the words in the file """ return len(self.__getWords__()) def countUniqueWords(self): """returns list of the unique words in the...
The main task of the code is to generate a formatted string summarizing results from multiple file analysis functions in the Statistics class, including line counts, word statistics, sentence lengths, popular words, color instances, and other metrics, combining them into a structured output for display or reporting.
def ToString(self): """returns a string with the results of all file analysis functions offered by the Statistics class. """ string = f"{self.start}Number of lines:{self.end} {self.countLines()}\n\n" \ f"{self.start}Number of Words:{self.end} {self.countWords()}\n\n" \ ...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--tweet_csv_file", type=str, required=True, ) parser.add_argument( "--device", type=str, choices=["cpu", "gpu"], default="cpu", ) args = parser.parse_args() retu...
The code trains a CNN model for sentiment analysis on Twitter data, loads and splits the dataset, trains the network with GPU support if available, evaluates on test data, and saves the model and training metrics. It also plots training accuracy and loss curves.
def main(): args = parse_args() twitter_csv_path = args.tweet_csv_file device_type = args.device use_bert = False shuffle = False train_data, dev_data, test_data = load_twitter_data(twitter_csv_path, test_split_percent=0.1, val_split_percent=0.2, overfit=True, shuffle=shuffle, use_bert=use_bert,...
def set_seed(args): """Set seed for reproducibility.""" if args.rand_seed: args.seed = np.random.randint(100) logger.info(f"New seed: {args.seed}") random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(...
The main task of this code is to perform cross-lingual query pretraining using a pre-trained language model. It parses configuration arguments, initializes training settings, loads a model and tokenizer, prepares multilingual datasets, and executes training/evaluation with distributed GPU support. The code prioritizes ...
def main(): parser = HfArgumentParser(PretrainingArguments) if sys.argv[1].endswith(".json"): args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))[0] else: args = parser.parse_args_into_dataclasses()[0] args.data_language_pairs = args.data_language_pairs.split(";") ...
def connect(paramaters_dict): """ Create a connection to the database and establish a cursor to run the queries. """ # connect try: conn = psycopg2.connect(**paramaters_dict) print("Connection to databse {} is established.".format(paramaters_dict['database'])) except psycopg2...
The main task of the code is to execute an ETL pipeline's "T" (Transformation) and "L" (Loading) stages by connecting to a database, processing song and log files, handling exceptions during data distribution, and measuring execution time. It initializes a database connection, processes data files, closes connections, ...
def main(): # initiate measure processing time startTime = datetime.now() """ 1 - Establish the connection to database. 2 - Runs the "T" and "L" part of the ETL pipeline. 3 - Ends the cursor and closes the connection. """ # connection conn, cur = connect(db_parameters_l...
def forwardPass(self): self.a[0] = self.x_train.reshape(-1, self.batchSize) for l in range(self.L - 1): self.z[l] = self.W(l) @ self.a[l] + self.b(l)[:, np.newaxis] self.a[l + 1] = self.sigma(self.z[l]) def backwardPass(self, arg='L'): if arg == 'L': self.delt...
The code performs a differentiation task by executing a forward pass, a backward pass focused on the loss term 'L', and then computes gradients. This is typical in neural network training to calculate parameter updates based on the loss function.
def diffL(self): self.forwardPass() self.backwardPass('L') self.grad()
def forwardPass(self): self.a[0] = self.x_train.reshape(-1, self.batchSize) for l in range(self.L - 1): self.z[l] = self.W(l) @ self.a[l] + self.b(l)[:, np.newaxis] self.a[l + 1] = self.sigma(self.z[l]) def backwardPass(self, arg='L'): if arg == 'L': self.delt...
The code performs differentiation for 'F' by executing a forward pass, a backward pass targeting 'F', and then applying the computed gradients. This process is typical in neural networks for updating model parameters during training.
def diffF(self): self.forwardPass() self.backwardPass('F') self.grad()
def init_grid(): # resetting for new simulation grid.clear() free_particles.clear() growth.clear() global dentric_height dentric_height = 1 grid.append(np.ones(col_size, dtype=int)) for j in range(col_size): growth.add((0, j)) for i in range(row_size - 1): grid.app...
The main task of the code is to generate multiple material samples by simulating crystal growth through particle movement. It initializes grids, fills them with random squares, grows crystals until reaching a target size, saves results to files, and estimates remaining simulation time (ETA) using average per-sample dur...
def main(): times = [] for k in range(desired_samples): t_0 = time.time() init_grid() N = int(concentration * working_volume) for i in range(N): fill_random_square() while dentric_height < desired_crystal_size: move_particles() print_gri...
def is_divisible_by_2(num): """ Taking input in the string form and comparing the last digit of string py:function:: Args: num(str) : string is given as parameter return: Bool: 'true' if last digit divisible by 2 """ if num[-1] in ("0", "2", "4", "6", "8"): return...
The code processes a list of numbers, validating they are positive and non-zero. It checks each number's divisibility by 2, 3, 4, 5, 6, 7, 8, and 9, compiling a list of divisors. If any divisors are found, it prints the number with the list; otherwise, it indicates the number isn't divisible by any. The function raises...
def function(): a = user_input.split(",") for num in a: if int(num) < 0: raise Exception("Number cannot be less than zero") if int(num) == 0: raise Exception("Number cannot be equal to zero") reqresult = "" count = 0 if is_divisible_by_2(num): ...
def get_q_value(self, state, move): """ Method to retrieve Q-value based on the state-action pair :param state: State of the game whose Q-value needs to be extracted :param move: Action done on the state :return: Q-value of the given state-action pair """ # Conver...
The code trains a robot using Q-Learning by updating Q-values for state-action pairs. It iterates through valid moves, calculates previous and next Q-values, and adjusts the Q-table with the reward and maximum future Q-value from the next state. The method enhances the agent's decision-making by learning optimal moves ...
def train(self, valid_moves, reward, player, game): """ Method to train the robot of the game using Q-Learning :param valid_moves: a list of possible moves on the board :param reward: reward based on the current status of the board :param player: ID of the player to train ...
def calculate_priority(ally_dict, enemy_dict, initial_enemies, block_dict): """ The lower the priority the better """ print(ally_dict) # Return the worst possible priority if the game can't be won if not can_win(ally_dict, enemy_dict): return PriorityEntry(math.inf) # Find the min ...
The code implements a best-first search algorithm to find a winning path in a game scenario. It explores states by prioritizing them using a calculated priority, starting from initial ally/enemy configurations. The algorithm tracks visited states to avoid cycles, generates next possible states, and adds them to a prior...
def best_first_search(ally_dict, enemy_dict, block_dict): visited = [] path = [(ally_dict, enemy_dict)] initial_enemies = len(enemy_dict) frontier = PriorityQueue() priority = calculate_priority(ally_dict, enemy_dict, initial_enemies, block_dict) frontier.put((0, priority, ally_dict, enemy_dict...
def calculate_priority(ally_dict, enemy_dict, initial_enemies, block_dict): """ Return a number indicating the priority of reaching this current state of the game. The lower the priority the more favourable this state is. """ # Return the worst possible priority if the game can't be won anymore ...
The function `best_first_search` implements a greedy best-first search algorithm to find a path from the initial state to a winning state in a game-like scenario. It uses a priority queue to explore states based on their calculated priority, avoiding revisits via a `visited` list. The search generates next states, eval...
def best_first_search(ally_dict, enemy_dict, block_dict): """ Search for a solution for the problem using greedy best first search and return a path of the states to reach at each time until the final winning state is reached. """ visited = [] path = [(ally_dict, enemy_dict)] n_enemie...
def read_file(data): """ Return the 3 dictionaries containing the refined data of the coordinates and type of each token and blocks on the board. """ ally_dict = defaultdict(list) enemy_dict = defaultdict(list) block_dict = defaultdict(list) # Keep track of the amount of each token ty...
The main task of the code is to solve a single-player RoPaSci 360 game board configuration by loading JSON input data, parsing token/block positions, executing a best-first search to find a solution path, and reconstructing/visualizing the sequence of token movements (slides/swings) through state transitions. It proces...
def main(): """ The main entry point of the program which control the main flow of the simulation of the single player RoPaSci 360 game. """ # Read the data from the given json file and load them into a dictionary try: with open(sys.argv[1]) as file: data = json.load(file) ...
def display_board(): for i in range(0, 9, 3): print("| " + board_simple[i] + " | " + board_simple[i + 1] + " | " + board_simple[i + 2] + " | ") print("-------------") print("=============================") def set_pc_symbol(): global player_symbol, pc_symbol symbol = None while symb...
This code implements a Tic Tac Toe game where a computer plays against a user. It alternates turns, with the computer choosing moves via the `pc_move()` function and the user inputting their moves. The game checks for a win or tie after each move, displaying the board and announcing results like "AI wins!", "You've won...
def tic_tac_toe(): global turn print("========= WELCOME TO TIC TAC TOE ===========\n") display_board() set_pc_symbol() while True: if not (turn % 2): pc_position = pc_move() if pc_position == -1: print("It's a tie!") break ...
def check_bootloader_files(self): """ Checks if the required bootloader files exist in the specified file paths. Die if any of the files are missing. """ if not os.path.isfile(self.flash_writer_image): die(f"Missing flash writer image: {self.flash_writer_image}") ...
The main task of the code is to write bootloader components (flashWriter, bl2, fip) to a board via QSPI or eMMC. It checks required files, waits for device readiness via serial communication, flashes the flash writer, and then programs the bootloader using the selected storage interface. Progress updates are provided t...
def write_bootloader(self): """Write bootloader (flashWriter, bl2, fip images) to board.""" self.check_bootloader_files() # Wait for device to be ready to receive image. print("Please power on board. Make sure boot2 is strapped.") with tqdm(total=1) as progress_bar: ...
def argparse_and_override_defaults(self): """ Sets up the argument parser before parsing the command line arguments and setting FlashUtil vars. Returns: argparse.ArgumentParser: The argument parser. """ argparser = argparse.ArgumentParser( descri...
This code initializes a flashing utility by setting default image paths, parsing command-line arguments, and determining which images to flash based on user-specified flags (--bootloader, --rootfs, --full). It configures serial ports and triggers flashing operations for bootloader components or the root filesystem, wit...
def __init__(self): self.__script_dir = os.getcwd() self.flash_writer_image = f"{self.__script_dir}/{FLASH_WRITER_FILE_DEFAULT}" self.bl2_image = f"{self.__script_dir}/{BL2_FILE_DEFAULT}" self.fip_image = f"{self.__script_dir}/{FIP_FILE_DEFAULT}" self.rootfs_image = f"{self.__sc...
def _get_annotation_files(file_path): # Path can be a directory containing all files or a directory containing multiple files if file_path is None: return [] annotation_files = [] if os.path.isfile(file_path): annotation_files = [file_path] elif os.path.isdir(file_path): anno...
The code converts COCO-format JSON annotations into a list of BoundingBox objects. It reads annotation files, extracts categories, images, and bounding box data, then maps each annotation to a BoundingBox with coordinates, class labels, image metadata, and confidence scores (if detected). The output is a list of these ...
def coco2bb(path, bb_type=BBType.GROUND_TRUTH): ret = [] # Get annotation files in the path annotation_files = _get_annotation_files(path) # Loop through each file for file_path in annotation_files: if not is_coco_format(file_path): continue with open(file_path, "r") as ...
def _to_tanh_space(self, x): """ Convert a batch of tensors to tanh-space. :param x: the batch of tensors, of dimension [B x C x H x W] :return: the batch of tensors in tanh-space, of the same dimension """ return to_tanh_space(x, self.box) def _optimize(self, model, opt...
This code generates adversarial examples by perturbing inputs in tanh-space using an Adam optimizer. It performs binary search on scale constants to minimize perturbation norms while ensuring model misclassification. The process iteratively optimizes perturbations, checks attack success, and adjusts bounds for scale co...
def __call__(self, model, inputs, targets, to_numpy=False): """ Produce adversarial examples for ``inputs``. :param model: the model to attack :type model: nn.Module :param inputs: the original images tensor, of dimension [B x C x H x W]. ``inputs`` can be on eith...
def moments(p,q,payoffp,payoffq): #binary events p = p q = q a = payoffp b = payoffq mean = p*a**1 + q*b**1 var = p*a**2 + q*b**2 skew = p*a**3 + q*b**3 kurt = p*a**4 + q*b**4 M5 = p*a**5 + q*b**5 array = (mean,var,skew,kurt,M5) return array def Kelly(prob_p, payoff_p, ...
The main task of the code is to compute and print statistical moments, Kelly criterion values, and related approximations for given probabilities and payoffs. It calculates moments (x), the exact Kelly fraction, an approximate Kelly value using moments, and the ratio of the first two moment components, returning no exp...
def main(p,q,payoffp,payoffq): x = moments(p,q,payoffp,payoffq) print(x) print(Kelly(p,payoffp,q,payoffq)) print((Kellyapprox(x[0],x[1],x[2],x[3]))) print(x[0]/x[1]) return
def order_connections_boxes(self): sorted_boxes = sorted(self.remote_hosts_data.items(), key=lambda box: box[1].hostname) i = 0 for _, box in sorted_boxes: box.update(i) i += 1 self.root.after(50, self.order_connections_boxes) def start_server(self): t1 =...
The code initializes a Tkinter GUI window with specific configurations, sets up data structures for managing connections and a queue, and starts a server and queue listener to handle remote host interactions, all within a main event loop for the application.
def __init__(self): # Window init and config self.root = tk.Tk() self.root.title("Plots Available") self.root.geometry(f"300x300-{screen_width - 310}+0") self.root.configure(background='#181818') self.root.columnconfigure(1, weight=2) # Additional Data se...
def new_match(*, p1: str = None, p2: str = None) -> Match: """ Creates a new Tic-Tac-Toe match with user-specified parameters. This method essentially plays a game of Tic-Tac-Tow in order to retrieve all the data for a new Match object that is returned. :param p1: The username of player 1 (optiona...
(The main task of the code is to enable a user to play a Tic-Tac-Toe game, log each match into a database, and allow rematches. It initializes a match, logs it, and repeatedly creates new matches with the same players if the user requests a rematch, demonstrating how utilities from the package can be integrated to buil...
def play() -> None: """ Allows users to play a Tic-Tac-Toe match and log it in the database. This function is just an example of how all the utilities this package provides can be used in tandem to create a Tic-Tac-Toe game. """ match = new_match() log_match(match) while wants_rematch()...
def _check_keydown_events(self,event): """ Respond to key press. """ if event.key == pygame.K_RIGHT: # Move the ship to right. # self.ship.rect.x += 1 self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True ...
This function processes user input events in a Pygame application. It checks for quit requests, keyboard key presses/releases, and mouse clicks. When a mouse button is pressed, it retrieves the mouse position and triggers the play button check method. The function delegates specific event handling to separate methods f...
def _check_events(self): # wathc for keyboard and mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYU...
def _check_fleet_edges(self): """ Respond apporpriately if any aliens have reached an edge. """ for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """ Respond to the ship being hit by a...
This function updates the positions of all aliens in the fleet, checks if the fleet has reached the screen edge (to adjust direction), detects collisions between the player's ship and aliens (triggering a ship hit response), and checks if any aliens have reached the bottom of the screen (likely triggering game-over log...
def _update_aliens(self): """ Update the positions of all aliens in the fleet. """ """ Check if the fleet is at edge then update the position of all aliens in the fleet""" self._check_fleet_edges() self.aliens.update() # Look for alien-ship collisions if pygame.sprite.sp...
def _check_events(self): # wathc for keyboard and mouse events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYU...
The code runs the game's main loop, continuously checking for events, updating game elements (ship, bullets, aliens) if the game is active, and rendering the screen to create real-time gameplay.
def run_game(self): """Start the main loop for the game""" while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen()
def busted(hand): if score(hand) > 55: return True else: return False def show_hand(hand: Card): stringofCards = "" for card in hand: stringofCards += card.rank + " " return stringofCards def score(hand: Card) -> int: sum = 0 for card in hand: if card.rank ==...
The function `play_turn` manages a single turn in a card game, allowing the player to hit or stay. It checks for player busts, draws cards from the shoe, and lets the dealer play until their score meets or exceeds the player's. It then compares hands to determine the winner, considering busts and draws, and returns upd...
def play_turn(player_hand, dealer_hand, shoe) -> tuple: print("Hit or stay?") choice = input() player_busted = busted(player_hand) while (player_busted == False and choice == "hit"): player_hand.append(shoe.draw()) print("Player hand: " + show_hand(player_hand)) print("Player s...
def _add_video_url(self, url: str) -> None: logger.debug(f'Added video URL: {url}') self._video_urls.append(url) def _save_media(self, edge: Edge) -> None: media_info_url = ('https://i.instagram.com/api/v1/media/' f'{edge["node"]["id"]}/info/') if self._is_saved...
This function processes a collection of edges to save media content. It handles GraphVideo by extracting shortcodes for URLs, GraphImage via _save_media, and GraphSidecar by recursively processing child edges. It uses parent_edge to resolve missing shortcodes and saves comments if enabled. Errors arise from unknown typ...
def _save_stuff(self, edges: Collection[Edge], parent_edge: Edge | None = None) -> None: for edge in edges: if edge['node']['__typename'] == 'GraphVideo': try: shortcode = edge['node']['shortcode'] except KeyError as e: if paren...
def _get_rate_limited( self, url: str, *, return_json: bool = True, params: Mapping[str, str] | None = None, cast_to: Type[T] | None = None) -> T | requests.Response: # pylint: disable=unused-argument with self._session.get(url, params=par...
The code processes Instagram user data by fetching profile information, downloading the profile picture if not already saved, collecting video URLs from highlights and media posts, paginating through media content, and using yt-dlp to download videos while checking for existing downloads and handling failures. It saves...
def process(self) -> None: with chdir(self._output_dir): self._get_rate_limited(f'https://www.instagram.com/{self._username}/', return_json=False) r = self._get_rate_limited('https://i.instagram.com/api/v1/users/web_profile_info/', ...
def send_message(self, message, environment): environment.broadcast_message(f"{self.name}: {message}") print(f"{self.name}: {message}") def generate_response(self, prompt, role="user", max_retries=3, retry_delay=5): retries = 0 while retries < max_retries: try: ...
The code simulates a collaborative town-building process where an agent interacts with an environment by sending messages, parsing user commands (e.g., take, put, trade), and executing actions like inventory management, item examination, and agent communication. The agent cycles through turn-based interactions, generat...
def build_town(self, environment): print(f"Agent {self.name} is initiating the town-building process.") self.send_message("Mayor: Let's start building our new town together!", environment) self.send_message(""" This process will extract your r...
def createTables(): q="""CREATE TABLE tiles ( zoom_level integer, tile_column integer, tile_row integer, tile_data blob); CREATE TABLE metadata (name text, value text); CREATE UNIQUE INDEX name on metadata (name); CREATE UNIQUE INDEX tile_inde...
This code converts SAS tiles to an MBTiles SQLite format by creating a database, populating it with tiles from a directory, and adding metadata like zoom levels and tile format. It handles command-line arguments for input directory and maximum zoom, then processes tiles into a structured MBTiles file for geographic dat...
def main(): print("sas tiles to mbtiles converter (c)sae762 aka LLIAMAH v0.1 2021") print("Usage: "+sys.argv[0]+" <dirname> <maximum zoom>") global dbname global conn global cursor global metaData if len(sys.argv) < 2: exit(); if len(sys.argv) > 2: maxZoom=int(sys.argv[2]...
def read_teams_from_file(filename): teams = [] with open(filename) as csvfile: reader = csv.DictReader(csvfile) for row in reader: team = row team["rating"] = int(team["rating"]) teams.append(team) return teams def simulate_tournaments(teams, N=1000): ...
The code's main task is to run a tournament simulation by reading team data from a file, simulating multiple tournaments to calculate each team's winning probability, and then printing the results. It validates input, processes the file, performs simulations, and outputs the chances of each team winning.
def main(): if len(sys.argv) != 2: sys.exit("Usage: python tournament.py FILENAME") teams = read_teams_from_file(sys.argv[1]) counts = simulate_tournaments(teams) print_chances_of_winning(counts, teams)
def dense(n_hidden, activation='relu', init_stddev=0.1, init_mean=0.0, seed=None): """ Helper function for configuring `keras.layers.Dense` """ kernel_initializer = RandomNormal(mean=init_mean, stddev=init_stddev, seed=seed) bias_initializer = RandomNormal(mean=init_mean, stddev=...
The code defines a Keras-based Graph Convolutional Network (GCN) for graph classification. It constructs a 3-layer GCN with dense layers applied to graph-adjacency matrix-feature products, followed by global average pooling and a softmax classifier. The model supports regularization via custom loss functions and includ...
def keras_gcn(config): """ Keras GCN for graph classification """ d = config['d'] init_stddev = config['init_stddev'] L1 = config['L1'] L2 = config['L2'] L3 = config['L3'] N = config['N'] num_classes = config['num_classes'] batch_size = config['batch_size'] reg_list = con...
def keras_gcn(config): """ Keras GCN for graph classification """ d = config['d'] init_stddev = config['init_stddev'] L1 = config['L1'] L2 = config['L2'] L3 = config['L3'] N = config['N'] num_classes = config['num_classes'] batch_size = config['batch_size'] reg_list = con...
The function `run_train` partitions data into train/val/test sets using provided indices, initializes and trains a GCN model if `train=True`, loads the model weights from a save path, evaluates the model on all splits using human data, and returns the trained model along with evaluation metrics (AUC or other specified ...
def run_train(config, data, inds, save_path, human_data, metric='AUC', train=True): """ Sets splitter. Partitions train/val/test. Loads model from config. Trains and evals. Returns model and eval metrics. """ train_inds = inds["train_inds"] val_inds = inds["val_inds"] test_inds = inds["t...
def point(self, root, left, right): if left != None: root.l = left left.p = root if right != None: root.r = right right.p = root def update_balance(self, node): if node == None: return lh = self.height(node.l) rh = self...
This code inserts a new root node into a tree structure, updating balance factors, depths, and generating codes. It checks if the tree is empty, then sets the root, connects it to left/right nodes, updates balances/depths, and generates codes. However, the else clause redundantly overwrites the root regardless of initi...
def insert(self, root, rootl, rootr): if self.root == None: self.root = root self.point(root, rootl, rootr) self.update_balance(rootl) self.update_balance(rootr) self.update_depth(self.root) self.get_codes(self.root) else: ...
def createEscrow(self): try: self.holdingAddress = self.api.get_new_addresses(count=None,checksum=True)['addresses'][0] except iota.adapter.BadApiResponse as e: logging.warning("Bad response from server retrying.") return self.createEscrow() return self.holdin...
The main task of the code is to initiate a CLI-based escrow process by creating a holding address, configuring collateral and fee parameters, waiting for a deposit address input, monitoring conditions, and finalizing the escrow once conditions are met. It manages deposit requests, enforces delays, and ensures proper es...
def startCli(self,collateral,fee=0,delay=120,deposit=None): #Create holding address self.createEscrow() self.fee=fee self.collateral=collateral #Wait for a deposit address to be entered if self.requestDeposit(collateral,deposit,delay): while not self.checkCond...
def dTdV(T, Ta, x, V): return (Ua * (Ta - T) + neg_r_a(T, x) *(-1) * delHr(T))/FA0/(CPA + x*delCp) def dTadV(T, Ta, x, V) : return Ua * (T - Ta)/m_cool/cp_cool def dxdV(T, Ta, x, V): return neg_r_a(T, x)/FA0
The code defines a system of ordinary differential equations (ODEs) where the function `diff_eq` computes the time derivatives of three state variables (y[0], y[1], y[2]) at a given time `t`. It returns a list of three derivatives calculated using the functions `dTdV`, `dTadV`, and `dxdV`, which likely represent the ra...
def diff_eq(t, y): return [dTdV(y[0], y[1], y[2], t), dTadV(y[0], y[1], y[2], t), dxdV(y[0], y[1], y[2], t)]
def parse_arguments(self): """ Returns the parsed arguments from the command line """ description = self.name if self.__doc__ is not None: description += " - " description += self.__doc__ arg_parser = argparse.ArgumentParser(prog=self.name, description=descriptio...
This code initializes a Spark context with optional profiling, runs a job using SQLContext, manages accumulators for metrics, and cleans up resources. It parses arguments, configures Spark, executes the job via `run_job`, displays profiling data if enabled, then stops the Spark context.
def run(self): self.args = self.parse_arguments() conf = SparkConf() if self.args.spark_profiler: conf = conf.set("spark.python.profile", "true") sc = SparkContext( appName=self.name, conf=conf) sqlc = SQLContext(sparkContext=sc) se...
def isKnown(word): return word in word_freq.keys() def findSuggestions(word): global begin_part begin_part = time.time() word_splits = generateSplits(word) one_char_errors = genCommonErrors(word_splits) two_char_errors = one_char_errors for new_word in one_char_errors: if new_word ...
This code updates a global 'word' variable based on keyboard events. It handles backspace to remove characters, processes space/enter to print the word, check if it's known, and fetch suggestions, then resets 'word'. Otherwise, it appends typed characters to 'word' and triggers a guessWord function for real-time sugges...
def update_suggestions(event): global word # needs to update the internal 'word' if a backspace key is found if event.keycode == 855638143: # the keycode for backspace word = word[:len(word)-1] elif event.char == ' ' or event.keycode == 603979789: #If a space or enter key is detected word is p...
def population_generation(self): """ Generate the initial population and calculate the fitness of each individual :return: - """ for _ in range(self.population_size): individual = [] nlayers = random.randint(2, self.maxnlayers) for _ in range(n...
The main task of the code is to execute a Genetic Algorithm by iterating through generations, generating initial populations, applying selection, crossover, and mutation operations, implementing elitism, checking for convergence, and storing fitness results. It tracks the best individuals and fitness metrics while evol...
def exec(self): """ Execute for each generation the Genetic Algorithm phases :return: - """ print("Generating initial population...") self.population_generation() for generation in range(self.generations): print("Generation " + str(generation) + " popu...
def get_days_of_month(month, year): match month: case 1: return 31 case 3: return 31 case 5: return 31 case 7: return 31 case 8: return 31 case 10: return 31 case 12: return 31...
The function `automated_main` validates a given month and year, retrieves the number of days in the month and the starting day of the week, then displays the calendar for that month without user input. It checks inputs for correct type and valid ranges, handling errors by printing messages and exiting if invalid.
def automated_main(month, year): """ runs same functions as main without user input """ if type(month) != type(0): print("Error: invalid month") return if month < 1 or month > 12: print("Error: invalid month") return if type(year) != type(0): print("Error: invalid...
def load_board(): with open("saved_board.json", "r") as board_file: json_string = board_file.read() board = json.loads(json_string) return board def check_is_filled(board): # Ensures that the board is in a playable state. # Checks for win condition of all values filled. for i in ...
The main task of the code is to load a Sudoku board from a saved file, display it, and allow user interaction to check possible moves, save progress, or get guesses until the board is filled. It provides a basic interface for playing or analyzing a Sudoku puzzle.
def main(): # Get the filename only if you wish to convert the original test array files. # Otherwise simply call sudoku.load_board and the last saved game will be # loaded, the saved games are always stored as ./saved.board.json # filename = get_filename() # board = convert_array(filename) bo...
def test_cases(): """ for automation of test cases """ print("\n Test case 1:") automated_main(1, 1753) print("\n Test case 2:") automated_main(2, 1753) print("\n Test case 3:") automated_main(1, 1754) print("\n Test case 4:") automated_main(2, 1756) print("\n Test case 5:") ...
The main task of the code is to validate user input for a month (1-12) and year (≥1753), compute the number of days in the selected month and its starting day of the week, then display the calendar for that month using the `display_month` function. The code includes test case execution and input validation loops to ens...
def main(): # fuction call to execute test cases test_cases() # fuction call to execute test cases month = 0 reenter = True while reenter: month = int(input("Please enter the desired month (1-12): ")) if 1 <= month <= 12: reenter = False year = 0 while year <...
def snap(self): """Snap a picture and save it to disk.""" img_name = "opencv_frame_{}.png".format(int(time.time())) img_file = "{}/{}".format(self.file_path, img_name) cv2.imwrite(img_file, self.frame) print("{} written!".format(img_name)) self.session_captured.append(im...
This code captures video from a camera, processes each frame by flipping it, converting to grayscale, detecting faces, and streaming the result. It handles keyboard inputs (ESC to exit, SPACE to snap images) and releases resources upon completion.
def capture(self): self.session_captured = [] video_capture = cv2.VideoCapture(self.camera) while True: # Captures video_capture frame by frame video_ok, this_frame = video_capture.read() if video_ok: (x, y, w, h) = (0, 0, 960, 720) ...
def clear_screen(): subprocess.run(['clear']) def currently_running_stacks(print_to_stdout=True): rep = subprocess.run(['docker', 'stack', 'ls'], capture_output=True, encoding=ENCODING) if print_to_stdout: print('Currently running stacks:') e...
This code defines a menu-driven interface for managing stack operations, allowing users to check service health, upgrade, start, remove, or exit. It loops, displaying options and executing corresponding functions based on user input, utilizing stack-related operations like updating or stopping stacks.
def menu(): while True: clear_screen() stacks = currently_running_stacks() print('\n') print('What do you want to do?') print('#######################') print('0) Check service health') print('1) Upgrade all stacks') print('2) Start stack') pri...
def get_var_list_from_file(): var_list = copy.deepcopy(VAR_LIST) if os.path.isfile(BASH_FILE): print(f'Getting variables from environment file {BASH_FILE}') with open(BASH_FILE, 'r') as f: for key, value in key_value_generator(f): var_list[key] = value # Check...
The main task of the code is to manage environment variables by reading them from a file, optionally allowing user-modification, creating associated files/folders, and writing updated variables back to disk. It performs sanity checks, displays the variable list, prompts for changes, applies modifications if confirmed, ...
def main(): common.sanity_checks() var_list = get_var_list_from_file() print_var_list(var_list) if input('Would you like to re-set some environment variables?' ' (y/n) ').strip() == 'y': var_list = reset_some_values(var_list) create_files_and_folders(var_list) write_env_vars...
def generate_vectors_from_pdf(): for root,dirs,files in os.walk("./data"): for file in files: if file.endswith(".pdf"): print(file) loader = PDFMinerLoader(os.path.join(root,file)) documents = loader.load() text_splitter = RecursiveCharacterTextSplitter(c...
The code's main task is to process a user-uploaded PDF by generating vectors, loading a model, and enabling interactive Q&A. It copies the PDF to a folder, extracts vectors, loads a model, then repeatedly prompts the user for questions, providing answers and metadata from the PDF using the model.
def functional_main(): # take pdf filepath from cli pdf_save_folder = "./data" pdf_path = input("Enter the path to the pdf file: ") shutil.copy(pdf_path, pdf_save_folder) print("File uploaded successfully") print("==============================================================") print("Gener...
def point_selection(mouse, keys, user_input, splines, type, pygame): previous_input = user_input.previous_input # Check for click start if mouse.left_click and not previous_input.mouse.left_click: look_for_point(mouse.pos, splines, type, user_input) elif mouse.left_click and previous_input.mouse...
The function `switch_on_selection_mode` determines the user's selection mode (control points, endpoints, segments, or splines) and delegates interaction handling to the appropriate selection logic function, enabling users to manipulate specific parts of splines in a graphical application.
def switch_on_selection_mode(mouse, keys, user_input, splines, pygame): if user_input.selection_mode == SelectionMode.control_points: point_selection(mouse, keys, user_input, splines, "control", pygame) if user_input.selection_mode == SelectionMode.end_points: point_selection(mouse, keys, user_i...
def handle_add(mouse, keys, user_input, splines, pygame): previous_input = user_input.previous_input # Check for click start if mouse.left_click and not previous_input.mouse.left_click: look_for_point(mouse.pos, splines, "end", user_input) add_segment(splines,user_input, mouse.pos) elif...
This function determines the active edit mode from user input and delegates operations to corresponding handlers: adding, selecting, or deleting splines. It routes tasks to handle_add, switch_on_selection_mode, or handle_delete based on EditMode enum values, enabling interactive spline editing via mouse and keyboard in...
def switch_on_edit_mode(mouse, keys, user_input, splines, pygame): if user_input.edit_mode == EditMode.Add: handle_add(mouse, keys, user_input, splines, pygame) elif user_input.edit_mode == EditMode.Select: switch_on_selection_mode(mouse, keys, user_input, splines, pygame) elif user_input.ed...
def switch_on_edit_mode(mouse, keys, user_input, splines, pygame): if user_input.edit_mode == EditMode.Add: handle_add(mouse, keys, user_input, splines, pygame) elif user_input.edit_mode == EditMode.Select: switch_on_selection_mode(mouse, keys, user_input, splines, pygame) elif user_input.ed...
This function processes user inputs to switch between different modes (edit, selection, print) in a graphical application. It checks for key releases, particularly the 'P' key, to trigger a print operation. The code handles input events, updates mode states, and executes actions like printing splines to the window base...
def branch_input(mouse, keys, user_input, splines, pygame, window): switch_on_edit_mode(mouse, keys, user_input, splines, pygame) set_selection_mode(keys, user_input, pygame) set_edit_mode(keys, user_input, pygame) set_print_mode(keys, user_input, pygame) if keys.released == pygame.K_p: exec...
def parse_mouse(user_input): mouse = InputObject() mouse.pos = user_input.current_input.get("cursor position") mouse.left_click = user_input.current_input.get("cursor click")[0] mouse.middle_click = user_input.current_input.get("cursor click")[1] mouse.right_click = user_input.current_input.get("cur...
This function processes user input in a pygame application by parsing mouse and keyboard events, checking hotkeys, branching input logic for spline manipulation, applying snapping rules to spline geometry, and storing previous input states for tracking changes.
def handle_user_input(pygame, user_input, window, splines, math): mouse = parse_mouse(user_input) keys = parse_keyboard(user_input) check_hot_key_toggle(window, keys, pygame) branch_input(mouse, keys, user_input, splines, pygame, window) snap_spline_start_to_ends(splines) snap_control_to_opposin...
def find_node_forwards(nodes : List[node], node_type : node) -> int: """ Helper function to find index of certain node from the front of the given list """ if isinstance(nodes[0],node_type): return 0 else: return 1 + find_node_forwards(nodes[1:],node_type) def fill_condition(nodes :...
This function determines the correct position for an 'einde_zolang_node' by identifying the end node in a list, then recursively constructs a modified node list with calculated indices to enable loop execution. It processes nodes to ensure proper backward reference for loop control structures, adjusting node positions ...
def fill_end_condition(nodes : List[node], node_type : node, end_node_type : node) -> List[node]: """ Reverse of above function to fill the row number of the einde_zolang_node because it needs to go back to the zolang to implement loops """ if len(nodes) <=1: return nodes *head, a = nodes ...
def logger_write(self, model, s): """ Thread sender_handler write logs to logger/send_logger.txt Thread ack_handler write logs to logger/ack_logger.txt :param model: model == 's', called by send_handler, model == 'a', called by ack_handler :param s: log content :return: ...
The main task of the code is to retransmit the oldest unACKed TCP segment (at self.send_base) by retrieving it from the buffer queue, disabling sampling if needed, doubling the timeout interval, restarting the timer, sending the segment, and clearing retransmission counters. This implements TCP's retransmission mechani...
def retransmit(self): """ In TCP, retransmit the unACKed segment with the smallest sequence number, which is actually the self.send_base :return: """ self.logger_write('s', "Retransmit: Retransmit tcp_seg {seq_num}".format( seq_num=self.get_send_base())) ...
def logger_write(self, model, s): """ Thread sender_handler write logs to logger/send_logger.txt Thread ack_handler write logs to logger/ack_logger.txt :param model: model == 's', called by send_handler, model == 'a', called by ack_handler :param s: log content :return: ...
The main task of the code is to handle ACK packets from the server by parsing headers, checking for FIN signals to terminate the thread, managing duplicate ACKs for fast retransmission, updating send window parameters (send_base, boundary), clearing acknowledged buffer segments, adjusting timeout intervals based on sam...
def ack_worker(self): """ Handle ACKs from the server. :return: """ # Blocking here, waiting for packets from the server data_recv = self.client_socket.recv(20) if data_recv: # 1. extracting header and ACK, FIN bit from the header header...
def get_boundary(self): with self.window_lock: return self.boundary def get_send_base(self): with self.window_lock: return self.send_base def logger_write(self, model, s): """ Thread sender_handler write logs to logger/send_logger.txt Thread ack_handler wr...
The main task of the code is to transmit data in segments using TCP over UDP by reading from a file, generating TCP segments, managing sequence numbers, handling retransmissions, and sending packets. It checks for file transmission completion to send a FIN packet, updates window parameters, manages timers, and ensures ...
def send_worker(self): """ Send the next segment in the window. Each time after a packet was sent, check if there's retransmission. :return: """ while (self.next_seq_num + self.MSS) % self.UN_4BYTES_MOD <= self.get_boundary() and \ self.is_fin == 0: ...
def send_worker(self): """ Send the next segment in the window. Each time after a packet was sent, check if there's retransmission. :return: """ while (self.next_seq_num + self.MSS) % self.UN_4BYTES_MOD <= self.get_boundary() and \ self.is_fin == 0: ...
The main task of the code is to handle packet sending and retransmission. It runs in a loop, invoking `send_worker()` to send data and checking for timeouts or duplicate acknowledgments to trigger `retransmit()`. The process continues until all buffered data is sent and transmission is complete, ensuring reliable data ...
def send_handler(self): """ Thread send_handler works on this method. It calls self.send_worker() and self.retransmit() to be mainly responsible for packets sending and retransmission. :return: """ print("Send Handler starts") while self.is_fin == 0 or not self.b...
def shape_cannot_be_placed(self, shape): '''Determines whether a shape can successfully be placed.''' for block in shape.blocks: if (block.column_position < 0 or block.column_position >= self.num_columns or block.row_position < 0 or ...
This function handles the downward movement of a falling shape in a game (e.g., Tetris). It attempts to lower the shape by one row, checks if it can be placed, and either settles it or reverses the move if collision occurs. If the shape cannot be placed even after reversing, the game ends. The function returns True to ...
def let_shape_fall(self): '''What happens during every `tick`. Also what happens when the user hits down arrow.''' if self.falling_shape: self.falling_shape.lower_shape_by_one_row() if self.shape_cannot_be_placed(self.falling_shape): self.falling_shape.raise_shap...
def shape_cannot_be_placed(self, shape): '''Determines whether a shape can successfully be placed.''' for block in shape.blocks: if (block.column_position < 0 or block.column_position >= self.num_columns or block.row_position < 0 or ...
This function handles dropping a falling shape to the bottom of the game grid. It moves the shape down row by row until it can no longer descend, then attempts to place it. If placement fails (collision), the game ends; otherwise, the shape is settled into its final position.
def drop_shape(self): '''When you hit the enter arrow and the piece goes all the way down.''' if self.falling_shape: while not self.shape_cannot_be_placed(self.falling_shape): self.falling_shape.lower_shape_by_one_row() self.falling_shape.raise_shape_by_one_row()...
def makedir_exist_ok(dirpath): """ Python2 support for os.makedirs(.., exist_ok=True) """ try: os.makedirs(dirpath) except OSError as e: if e.errno == errno.EEXIST: pass else: raise def check_integrity(fpath, md5=None): if not os.path.isfile(fpath)...
The main task of the code is to download a file from a specified URL and save it to a given directory, verifying its integrity via MD5 checksum if provided. It handles retries for failed downloads, switches from HTTPS to HTTP if necessary, and ensures the file is correctly saved without redundant downloads.
def download_url(url, root, filename=None, md5=None): """Download a file from a url and place it in root. Args: url (str): URL to download file from root (str): Directory to place downloaded file in filename (str, optional): Name to save the file under. If None, use the basename of the U...
def makedir_exist_ok(dirpath): """ Python2 support for os.makedirs(.., exist_ok=True) """ try: os.makedirs(dirpath) except OSError as e: if e.errno == errno.EEXIST: pass else: raise def check_integrity(fpath, md5=None): if not os.path.isfile(fpath)...
This function downloads a Google Drive file using its ID and saves it to a specified directory. It handles authentication tokens, verifies file integrity via MD5 checksum if provided, and avoids re-downloading verified files.
def download_file_from_google_drive(file_id, root, filename=None, md5=None): """Download a Google Drive file from and place it in root. Args: file_id (str): id of file to be downloaded root (str): Directory to place downloaded file in filename (str, optional): Name to save the file unde...
def wait_page_loading(self, page_size): for _ in range(self.n_retries): try: return self.wait_elements( self.RESULTS_LIST_ITEM, page_size, ) except TimeoutException: self.refresh() raise TimeoutException( ...
The code parses data from a web subpage by navigating through multiple pages, extracting scheme-based results, and aggregating them into a list of reactions. It calculates required pages, iterates through each, collects data, handles pagination, and returns the compiled results while cleaning up navigation history.
def parse_subpage(self, page_size): self.wait_page_loading(1) subpage_source = self.get_page_source() subpage_url = '/'.join( self.get_current_url().split('/')[:-1], ) scheme = subpage_source.find( self.RESULTS_LIST_ITEM[1], ) conditions_n...
def wait_page_loading(self, page_size): for _ in range(self.n_retries): try: return self.wait_elements( self.RESULTS_LIST_ITEM, page_size, ) except TimeoutException: self.refresh() raise TimeoutException( ...
The code parses web page elements by iterating through a specified number of pages, checking for 'view all' buttons to handle dropdowns or subpages. It aggregates reactions by either parsing dropdown content or subpages based on the presence of SVG icons, ensuring dynamic data collection from web elements.
def parse(self, page_size, subpage_size): reactions = [] for scheme_idx in range(page_size): self.wait_page_loading(page_size) main_page_source = self.get_page_source() scheme = main_page_source.find_all( self.RESULTS_LIST_ITEM[1], )[scheme...
def open_handles(self, out_dir): self.handle = dict() path_to_mutations = os.path.join(out_dir, "mutations.tsv") path_to_nucl_freqs = os.path.join(out_dir, "expected_mutations.tsv") self.handle["mut"] = open(path_to_mutations, "w") self.handle["freq"] = open(path_to_nucl_freqs...
This code initializes an object for analyzing genetic mutation spectra using a phylogenetic tree and genomic state data. It validates input paths, configures codon annotation and state parameters, loads the tree structure, calculates key metrics like maximum leaf distance, sets mutation types (synonymous, etc.), and pr...
def __init__( self, path_to_tree, path_to_states, out_dir, gcode=2, db_mode="dict", path_to_db=None, rewrite_db=None, use_proba=False, proba_cutoff=0.01, use_phylocoef=False, syn=False, syn_c=False, syn4f=False, derive_spectra=True, path_to_rates=None, cat_c...
def whoseTurn(self, state: State) -> GameConstant: # round genap -> P1 # round ganjil -> P2 if (state.round % 2 != 0): return GameConstant.PLAYER1 else: return GameConstant.PLAYER2 def listNearbyShape(self, state: State, position: Tuple[int, int], playing: GameCon...
The main task of the code is to evaluate the score of a given shape (player or enemy) around a specific position on the board by counting consecutive pieces in all directions. It calculates streaks of the current player's and enemy's shapes, applies weighted multipliers (20/200 for player, 20/150 for enemy) based on st...
def shapeEvaluate(self, state: State, position: Tuple[int, int], shape: ShapeConstant) -> int: playing = self.whoseTurn(state) if playing == GameConstant.PLAYER1: enemy = GameConstant.PLAYER2 else: enemy = GameConstant.PLAYER1 #playing adalah pemain yang sedang t...
def whoseTurn(self, state: State) -> GameConstant: # round genap -> P1 # round ganjil -> P2 if (state.round % 2 != 0): return GameConstant.PLAYER1 else: return GameConstant.PLAYER2 def listNearbyColor(self, state: State, position: Tuple[int, int], playing: GameCon...
The function evaluates the potential of placing a piece at a given position by calculating the value of consecutive same-colored pieces (streaks) in all directions. It identifies streaks for the current player and opponent, applies multipliers (10x or 150x for player's 3-streak, 10x or 50x for opponent's 3-streak), and...
def colorEvaluate(self, state: State, position: Tuple[int, int], color: ColorConstant) -> int: playing = self.whoseTurn(state) if playing == GameConstant.PLAYER1: enemy = GameConstant.PLAYER2 else: enemy = GameConstant.PLAYER1 #playing adalah pemain yang sedang t...
def getPossibleMoves(self, board: Board) -> list: # menentukan posisi-posisi yang bisa ditempati possibleMoves = [] totalColumn = board.col totalRow = board.row for x in range (0, totalColumn, 1): # 0,1,2,3,4,5,6 for y in range (totalRow-1, -1, -1): # 5,4,3,2,1,0 ...
This code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a game. It evaluates board states recursively, considering terminal conditions (win, draw, depth limit) and heuristic values. For maximizing/minimizing players, it explores possible moves, updates scores, and prunes sub...
def minimax(self, board: Board, depth: int, alpha: int, beta: int, maximizingPlayer: bool) -> tuple[int,int]: possibleMoves = self.getPossibleMoves(board) iswin = is_win(board) # basis if (depth == 0 or iswin or is_full(board)): if iswin: if (iswin[0] == GameC...
def whoseTurn(self, state: State) -> GameConstant: # round genap -> P1 # round ganjil -> P2 if (state.round % 2 != 0): return GameConstant.PLAYER1 else: return GameConstant.PLAYER2 def getPossibleMoves(self, state: State) -> list: # menentukan posisi-posis...
The code implements a steepest hill climbing algorithm to select the optimal move in a turn-based game. It determines the current player's shape and color, evaluates heuristic values for all possible moves, identifies the move with the highest heuristic value, and returns it as the next action. The function prioritizes...
def steepestHC(self, state: State, playing: GameConstant) -> Tuple[int,int]: playing = self.whoseTurn(state) if (playing == GameConstant.PLAYER1): shape = GameConstant.PLAYER1_SHAPE color = GameConstant.PLAYER1_COLOR else: shape = GameConstant.PLAYER2_SHAPE...
def getSmallestNeighborIndex(img, row, col): """ Parameters : img - image row - row index of pixel col - col index of pixel Returns : The location of the smallest 4-connected neighbour of pixel at location [row,col] """ min_row_id = -1 min...
The main task is to implement the Minimum Following watershed segmentation algorithm to identify cell boundaries. This involves defining 4-connected neighbor checks, detecting regional minima, and iteratively propagating minima for segmentation. The code tests these functions on a sample image, applies them to a real c...
def part2(final): # Implement Minimum Following watershed segmentation to find the boundaries of the cells we detected in part 1. # TO - DO: Finish functions is_4connected(row, col, row_id, col_id), getRegionalMinima(img) and iterativeMinFollowing(img, markers) # =============== DO NOT EDIT ANY OF THE COD...
def is_aligned(self): return self.__is_aligned def get_length(self): # NOTE: If collection is empty, 0 should be returned as length, not an exception. # NOTE: AttributeError is not really a good choice if unaligned, maybe use GeneralException? if self.__molseq_list: # empty list evaluate...
This function removes columns containing only gaps from an aligned molecular sequence collection, returning a new MolSeqCollection object with those columns deleted. It checks alignment validity, identifies gap-only columns, and iteratively removes them from each sequence using 0-based indexing before constructing a ne...
def delete_gap_only_columns(self): """ :return: a MolSeqCollection object with gap_only_columns deleted """ if self.is_aligned(): if self.get_length() > 0: # gap_only_cols: 1-based indexing gap_only_cols = self.get_gap_only_columns() ...
def get_profile_form(self): form_kwargs = {"instance": self.object.profile} if self.request.method == "POST": form_kwargs["data"] = self.request.POST form_kwargs["files"] = self.request.FILES return ProfileChangeForm(**form_kwargs) def form_valid(self, user_form, profile_...
This code handles a POST request by retrieving an object, validating two forms (user and profile), and returning either a valid response with the forms or an invalid one if errors occur.
def post(self, request, *args, **kwargs): self.object = self.get_object() user_form = self.get_form() profile_form = self.get_profile_form() if user_form.is_valid() and profile_form.is_valid(): return self.form_valid(user_form, profile_form) else: return s...
def add_bais(X): # get the dimension N, D = X.shape Y = np.ones((N, D + 1)) Y[:,:-1] = X return Y def split(dataset, train_y, folds=2): """ this function will split the dataset into number of *folds* :param dataset: set data points (during computation we use feature vectors) :param t...
The code performs a linear regression analysis on the 'mfeat-pix.txt' dataset, varying the number of PCA components (k) from 1 to 100. For each k, it transforms data using PCA, adds a bias term, splits the dataset into training and testing folds, trains a model, and evaluates mean squared error (MSE) and misclassificat...
def main(): # do a linear regression on feature of number k filename = "mfeat-pix.txt" data = np.loadtxt(filename) results = [] nfeatures = range(1, 101) for k in nfeatures: pca = PCA(n_components=k) data_pca = pca.fit_transform(data) train = add_bais(data_pca) ...
def _common_dtype(self, x, y): dtype = np.find_common_type([x.dtype, y.dtype], []) if x.dtype != dtype: x = x.astype(dtype) if y.dtype != dtype: y = y.astype(dtype) return x, y def findExtrema_simple(self, t, s): """ Finds extrema and zero-crossings. Input: ...
The function performs Empirical Mode Decomposition (EMD) on a signal `S`, decomposing it into Intrinsic Mode Functions (IMFs) up to `maxImf` iterations. It returns IMFs in a dictionary, along with metadata: extrema counts per IMF, iteration numbers, and computational time. The decomposition iteratively extracts IMFs by...
def emd(self, S, timeLine=None, maxImf=None): """ Performs Emerical Mode Decomposition on signal S. The decomposition is limited to maxImf imf. No limitation as default. Returns IMF functions in dic format. IMF = {0:imf0, 1:imf1...}. Input: --------- S: Signa...
def get_required_files( path: str, valid_formats: list = [".jpg", ".jpeg", ".jp2", ".png", ".bmp", ".tiff", ".tif"], ): """ This function determines number of iteration required. From the give path, it calculates number of images present Right now we support the image formats which are in [".jp...
The function `get_sample_variations` generates scene, light, camera, and image parameter variations for rendering. It uses default configurations or a provided config file to create specified numbers of variations, handling background images and file paths. It returns tuples of parameters for rendering different variat...
def get_sample_variations( image_path, image_name=None, bg_path=None, config_file=None, number_of_variations_required: int = 1, ): check_path_exists(image_path) # background images if config_file == None: files = get_required_files(image_path) all_files = files * 1 ...
def get_transitions_by_query(client=None, query=None, location=None): next_page_starts_at = 0 available_results = True with open(file=location, mode='w') as exported_results: csv_writer = csv.writer(exported_results, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) headers = ["ID"...
(The function reads JQL queries from a file, executes each query using a Jira client to retrieve transitions, exports results to a specified location, and handles errors by logging issues and terminating with appropriate exit codes. It processes each line of the JQL file sequentially, ensuring proper session closure af...
def query_jira_by_file(client=None, jql=None): try: with open(jql, 'r') as jql_queries: lines = [line.rstrip() for line in jql_queries] for line in lines: get_transitions_by_query(client=client, query=line, location=get_export_file_path()) close_jira_session...
def dump_env_vars(prefix, pattern=None): if pattern is not None: match = lambda s: re.search(pattern, s) else: match = lambda s: True for name in sorted(os.environ): if name.startswith(prefix) and match(name): perr("- {0}: {1!r}".format(name, os.environ[name])) def list_a...
The main task of the code is to determine which code topics are affected in an AppVeyor CI build. It checks if the build is a pull request (PR) to identify affected files, then maps these to relevant topics. If not a PR, all topics are considered affected. Finally, it prepares an environment for these topics and return...
def run_from_appveyor(): perr("Environment variables (excerpt):") dump_env_vars('APPVEYOR_', '(PULL|REPO)') if not os.environ.get('APPVEYOR_PULL_REQUEST_HEAD_COMMIT'): # Not a PR build, test everything affected = dict.fromkeys(ALL_TOPICS, True) else: affected_files = list_appveyo...
def dump_env_vars(prefix, pattern=None): if pattern is not None: match = lambda s: re.search(pattern, s) else: match = lambda s: True for name in sorted(os.environ): if name.startswith(prefix) and match(name): perr("- {0}: {1!r}".format(name, os.environ[name])) def list_g...
This function determines affected topics based on GitHub event type and modified files in a PR, then prepares environment variables for testing. It checks if the event is a pull request to selectively test only relevant topics, ensuring efficient CI/CD workflows by avoiding unnecessary tests.
def run_from_github(): perr("Environment variables (excerpt):") dump_env_vars('GITHUB_', '(REPOSITORY|ACTOR|SHA|REF|HEAD_REF|BASE_REF|EVENT_NAME)') if os.environ['GITHUB_EVENT_NAME'] != 'pull_request': # Not a PR build, test everything affected = dict.fromkeys(ALL_TOPICS, True) else: ...
def dump_env_vars(prefix, pattern=None): if pattern is not None: match = lambda s: re.search(pattern, s) else: match = lambda s: True for name in sorted(os.environ): if name.startswith(prefix) and match(name): perr("- {0}: {1!r}".format(name, os.environ[name])) def get_tr...
The main task of the code is to determine which code topics (modules) require testing based on Travis CI environment variables and commit descriptions. It checks if the build is on the official Apache Arrow master branch, skips tests if the commit message includes [skip travis], forces full testing with [force ci], or ...
def run_from_travis(): perr("Environment variables (excerpt):") dump_env_vars('TRAVIS_', '(BRANCH|COMMIT|PULL)') if (os.environ['TRAVIS_REPO_SLUG'] == 'apache/arrow' and os.environ['TRAVIS_BRANCH'] == 'master' and os.environ['TRAVIS_EVENT_TYPE'] != 'pull_request'): # Never sk...
def count_weights_only(net): n_weights = 0 for name, module in net.named_modules(): if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear): n_weights += module.weight.numel() return n_weights def get_loader(n_params, arch, n_d_dependency): if n_d_dependency == -1: ...
The main task of the code is to train and evaluate neural networks (specifically `resnet50`) under various hyperparameter configurations (potential, dependency, cross-entropy penalty) using multiple seeds for reproducibility. It determines optimal learning rates via a learning rate finder, trains models, and saves init...
def main(potential, n_d_dependency, xent_penalty, pretrained, results_folder): n_seeds = 10 arch_list = ['resnet50'] # ['cornet-rt']#['cornet-s']#['shufflenet_v2_x0_5', 'shufflenet_v2_x1_0']# ['efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3', 'resnet18', 'resnet34'] # ['sh...
def count_weights_only(net): n_weights = 0 for name, module in net.named_modules(): if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear): n_weights += module.weight.numel() return n_weights def get_loader(n_params, arch, n_d_dependency): if n_d_dependency == -1: ...
The main task of the code is to evaluate multiple neural network architectures (e.g., ShuffleNet, EfficientNet, CORnet) under varying hyperparameters (potential, dependency, cross-entropy penalty) by training them with optimal learning rates, tracking training failures, and recording accuracy statistics across 10 seeds...
def main(potential, n_d_dependency, xent_penalty, pretrained, results_folder): n_seeds = 10 arch_list = ['shufflenet_v2_x0_5', 'shufflenet_v2_x1_0', 'efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3', 'resnet18', 'resnet34', 'cornet-s', 'cornet-rt'] exit_codes = dict...
def standard_normal_cdf(x): return (1 + erf(x / math.sqrt(2))) / 2 def get_potential(potential): if potential == 'negative_entropy': return md_utils.NegativeEntropy() elif 'norm' in potential: return md_utils.Pnorm(float(potential.split('-norm')[0])) else: raise NotImplementedErr...
The code computes correlation matrices with varying power parameters, generates Cholesky decompositions on GPU, and evaluates multiple potential functions (2-norm, negative entropy, 3-norm) across different dependency scales. It runs simulations for diverse data dimensions and correlation structures, testing statistica...
def main(corr_scale): for corr_power in [2, 1]: n_seeds = 30 D_max = int(2e4) dist = 1 / (1 + np.abs(np.arange(-D_max, D_max + 1) / corr_scale) ** corr_power) dist = dist * np.power(-np.ones(2 * D_max + 1), np.arange(-D_max, D_max + 1)) n_points = 10 D_range = np.log...
def find_arch_to_rerun(old_log_path): arch_rerun = [] if old_log_path is not None and os.path.isfile(old_log_path): print(f'LOADING OLD PATH AT {old_log_path}', flush=True) with open(old_log_path, 'r') as f: text = f.read() results = text.split('RUN SUMMARY\n\n\n')[1].split('...
The code evaluates RNN architectures (100/1000 units) by pre-training, fine-tuning with learning rate optimization, and tracking accuracy. It reruns failed architectures, saves weights, and logs performance metrics (exit codes, accuracy thresholds) across 10 seeds, using parameters like potential, dependency strength, ...
def main(potential, n_d_dependency, xent_penalty, pretrained, results_folder): n_seeds = 10 arch_list = [100, 1000] exit_codes = dict() n_bad_accuracy = defaultdict(int) n_very_bad_accuracy = defaultdict(int) arch_to_rerun = find_arch_to_rerun() print(F'ARCH TO RERUN {arch_to_rerun}',...
def register_read(self, addr): """ Read a register """ data = bytearray() data.extend(b'\xcc\x01\x00\xf8') data.append(addr) data.append(0xcd) self._port.write(data) _header, payload = self.read_packet_type(0xF6) assert payload[0] == addr ...
This function waits for specific bits (wanted_bits) to be set in a status register (address 0x6) within a given maximum time (max_time). It continuously reads the status, checks for errors and timeouts, and returns once the desired bits are detected. If the bits are not set before the timeout, the function will raise a...
def _wait_status_set(self, wanted_bits, max_time): """ Wait for wanted_bits bits to be set in status register """ start = time.monotonic() while True: status = self.register_read(0x6) self._check_timeout(start, max_time) self._check_error(stat...
def get_king(self, black_or_white): """ Retrieve the King object from the piece roster dictionary in _board. :param black_or_white: Indicates whether to access the black or white roster, can be 'WHITE' or 'BLACK' :return: King object from the relevant dictionary specified by the paramete...
This function checks if a move places the opponent's king in check by validating movement rules, ensuring the current piece doesn't capture the opponent's king, and verifying no opposing piece can immediately capture the current player's king. It returns True if valid, False otherwise.
def check_for_check(self, destination, origin, current_piece): """ Check the destination square to make sure that the requested move does not place the opponent's King piece in check. :param destination: The square the current player's piece is moving to as 'letter + num' :param ...
def get_game_state(self): """ Retrieve the current game state stored as one of ChessVar's data members. Can be any of the following strings: "WHITE_WON", "BLACK_WON", "TIE", or "UNFINISHED". Takes no parameters and returns whichever of the strings above that are the current setting. ...
This function validates and executes a white piece's move on a chessboard, checking for legal moves, capturing opposing pieces if the move doesn't expose the white king to check, updating piece locations, removing captured pieces, and switching turns. It returns True for legal moves or False for invalid ones, ensuring ...
def set_white_piece_location(self, origin, destination): """ Collaborate with ChessVar's make_move() method in order to move pieces around the board. :param origin: The square from which the piece is moving. :param destination: The square to which the piece is going. :ret...
def get_game_state(self): """ Retrieve the current game state stored as one of ChessVar's data members. Can be any of the following strings: "WHITE_WON", "BLACK_WON", "TIE", or "UNFINISHED". Takes no parameters and returns whichever of the strings above that are the current setting. ...
This function validates and executes a black piece's move in a chess variant, checking legality (e.g., bounds, captures, check), updating the board, removing captured pieces, and switching turns to White if valid. It returns True for legal moves, False otherwise, while handling game state transitions and turn progressi...
def set_black_piece_location(self, origin, destination): """ Collaborate with ChessVar's make_move() method in order to move pieces around the board. :param origin: The square from which the piece is moving. :param destination: The square to which the piece is going. :ret...
def _make_frequency_dict(self, text): freq = {} for char in text: if (char not in freq): freq[char] = 0 freq[char] += 1 return freq def _make_heap(self, frequency): for key in frequency: node = TreeNode(key, frequency[key]) ...
The main task of the code is to encode input text using Huffman compression. It constructs a frequency dictionary, builds a priority heap, merges nodes into a Huffman tree, generates a codebook, and encodes the text into a byte array. The function also associates the file extension with the decodebook and returns the c...
def _encode_file(self, text, file_extension): freq = self._make_frequency_dict(text) self._make_heap(freq) self._merge_nodes() self._create_codebook() self.decodebook['ext'] = file_extension encoded_text = self._get_encoded_text(text) byte_array = self._get_byte_a...
def _divide_blocks(self, imgArr): blocks = [] for i in range(0, imgArr.shape[0], self.block_size): for j in range(0, imgArr.shape[1], self.block_size): block = imgArr[i:i+self.block_size, j:j+self.block_size] blocks.append(block) blocks = np.array(blo...
The code performs image compression via vector quantization by dividing the input image into blocks, creating a codebook of representative vectors, encoding the blocks using the codebook, and decoding them to reconstruct the compressed image.
def vector_quantize(self, imgArr): blocks = self._divide_blocks(imgArr) codeBook = self._quantize(blocks) encoded = self._encode(blocks, codeBook) decoded = self._decode(encoded) return decoded
def _symbol_exists(self, x): node = self.parent if (node.right and node.right.symbol == 'nyt'): if (node.left.symbol == x): return node.left node = node.right while (node.right != None): if (node.right.symbol == x): return node....
This function encodes a symbol 'x' using a dynamic tree structure. If 'x' is not in the tree, it appends a NYT code and the symbol's code, then adds 'x' to the tree. If 'x' exists, it appends the existing code and increments the tree node's count. The encoded text is built incrementally, with intermediate results print...
def _encode_text(self, x): node = self._symbol_exists(x) if (node == None): txt = self._assign_nyt_code() + self.cmdict[x] self.encoded_text += txt print(txt) self._add_to_tree(x) else: txt = self._assign_code(x) self.encode...
def insert_person(person, c): c.execute("select * from person where name IS ?", (person.name,)) res = c.fetchone() if res is None: c.execute("insert into person(born, died, name) values (?, ?, ?)", (person.born, person.died, person.name)) return c.lastrowid else: if person.born i...
This function inserts data about prints, their compositions, editions, voices, and authors into a database. It processes each print by inserting related entities (composition, edition, voices) and their authors, linking them through foreign keys. Author IDs are collected, used to establish relationships, and then reset...
def insert_to_db(prints, conn): c = conn.cursor() com_author_ids = [] ed_author_ids = [] for p in prints: for person in p.edition.composition.authors: com_author_ids.append(int(insert_person(person, c))) for person in p.edition.authors: ed_author_ids.append(int(in...
def _run_encoder(self, batch): src, src_lengths = batch.src if isinstance(batch.src, tuple) \ else (batch.src, None) history, history_lengths = batch.history if isinstance(batch.history, tuple) else (batch.history, None) enc_states, memory_bank, src_lengths = self.mo...
This function performs translation using random sampling at each decoding step as an alternative to beam search. It initializes encoder states, generates sequences by sampling from the model's output distribution with configurable temperature, and manages attention mechanisms. The implementation handles training specif...
def _translate_random_sampling( self, batch, src_vocabs, max_length, min_length=0, sampling_temp=1.0, keep_topk=-1, return_attention=False, training=False): """Alternative to beam search. Do random sampli...
def _run_encoder(self, batch): src, src_lengths = batch.src if isinstance(batch.src, tuple) \ else (batch.src, None) history, history_lengths = batch.history if isinstance(batch.history, tuple) else (batch.history, None) enc_states, memory_bank, src_lengths = self.mo...
This function performs beam search decoding for neural machine translation, generating hypotheses for a batch of source sequences. It initializes the encoder, prepares beam search components, and iteratively decodes using the decoder, accumulating scores and attention. The results include predictions, scores, and atten...
def _translate_batch( self, batch, src_vocabs, max_length, min_length=0, n_best=1, return_attention=False, training=False): # TODO: support these blacklisted features. assert not self.dump_beam # (0)...
def fetch_user_by_username(username): url = lookup_username_url.format(username) response = requests.get(url, auth=bearer_oauth) if response.status_code != 200: raise Exception(response.status_code, response.text) json_res = response.json() return json_res['data'] def fetch_following(user_id...
The main task of the code is to extract and structure Twitter user data, including a target user's posts, their following relationships, and user profiles. It aggregates user information, retrieves tweets for the user and their followers, maps following connections, and returns cleaned dataframes for posts, user vertic...
def extract_twitter_data(username): users_list = [] user = fetch_user_by_username(username) user_following = fetch_following(user['id']) users_list.append(user) users_list.extend(user_following) users_to_search = list(map(lambda x: x['username'], users_list)) posts_df = get_user_tweets(us...
def extract_twitter_data(username): users_list = [] user = fetch_user_by_username(username) user_following = fetch_following(user['id']) users_list.append(user) users_list.extend(user_following) users_to_search = list(map(lambda x: x['username'], users_list)) posts_df = get_user_tweets(us...
The function `analyse_tweets` extracts Twitter data (posts, following, users) for a given username, formats it with timestamps and identifiers, uploads structured data to S3 buckets for Comprehend (sentiment analysis) and Tigergraph (graph processing), then initiates a targeted sentiment analysis job on the uploaded da...
def analyse_tweets(username, request_id): date = datetime.now().strftime("%m-%d-%y") tag = "{}-{}".format(date, username) twitter_data = extract_twitter_data(username) posts = twitter_data['posts'] posts['line_id'] = posts.index.map(lambda x: '{}-{}'.format(x, tag)) # used for mapping entities ...
def eventhandler(self): """ Handles all user input and custom userevents. eventhandler() -> none """ for event in pygame.event.get(): if event.type == pygame.QUIT: #Quit event exit() if event.type == ASTROID_SPAWN: #Astroid spawn event self.spawn_astroid() if event.type == RESPAWN_PLAYER1 or...
The main task of the code is to process game logic for each frame by handling events, updating sprites, detecting collisions, drawing game elements, and cleaning up expired effects. It updates all sprite groups, manages missile guidance, applies physics (gravity, impacts), checks for off-screen bullets, renders visual ...
def logic(self, screen): """ Logic method that runs all the engines methods needed for each frame. login(Screen) -> none """ self.eventhandler() #Handle game events self.missile_guidance() #Give missiles coordinates of target ship #Update all spritegroups self.bg.update() self.hud.update() se...
def set_kubernetes_attributes(self, source=None,task_outputs=None): attributes = source.node_template.attributes if 'tokens' not in attributes: tokens = [] attributes['tokens'] = tokens else: tokens = attributes['tokens'] if 'dashboard_url' not in sou...
The function `set_attributes` determines the type of the `source` node and applies specific attribute-setting logic using methods like `set_kubernetes_attributes`, `set_docker_attributes`, or `set_tic_attributes` based on the node's template type. It then returns the modified `source` object with updated attributes.
def set_attributes(self, task_outputs,source): # target = nodes_pair[0] # source = nodes_pair[1] if source.node_template.type == 'tosca.nodes.QC.docker.Orchestrator.Kubernetes': source = self.set_kubernetes_attributes(source=source,task_outputs=task_outputs) if source.node_te...
def _create_multi_dict(self) -> None: """Check if path is directory of configuration files""" for file in os.listdir(self._multiDirectory): for fileType in Multiple.configFileTypes: if fileType in file.split(".")[1]: self._numConfigs += 1 ...
The main task of the code is to load multiple configuration files from a specified directory. It initializes the directory path, creates a dictionary structure for the files, iterates through each configuration file in the directory, loads their content into the object, and clears any cached data afterward.
def load_multi(self, path) -> None: """Load directory of config files""" self._multiDirectory = path self._create_multi_dict() for configFile in self._dirList: self._fileObject = configFile self._multi_load_content() self.clear_multi_cache()
def echo(msg, pre=""): prefix = Style.DIM + Fore.WHITE + '({}) '.format(pre.capitalize()) + Fore.RESET + Style.RESET_ALL if pre else '' print("| " + Back.BLACK + "{pf}{msg}".format(pf=prefix, msg=msg) + Back.RESET + Fore.RESET + Style.RESET_ALL) def get_input(question='', prompt='> '): if question: ...
This function presents a numbered list of choices to the user, allowing selection via index or direct input. If exitable is True, it adds an exit option (either "exit" or "0"). It validates input, returning the selected choice, the corresponding list item, or None for exit. Invalid inputs trigger an error and re-prompt...
def get_choice(choices, exitable: bool = False): """Get user choice from a given list Args: choices: list. The list that user can choose from. exitable: bool. Does `exit` is an option for user to select. """ EXIT_WORD = "exit" if "0" in choices else "0" for index, item in enumerate(...
def state_to_features(self, game_state: dict) -> tuple: """ Converts the game state to the input of your model, i.e. a feature vector. :param game_state: A dictionary describing the current game board. :return: a tuple (feature, allowed actions) where feature = (vicinity_type,(neighbours),(b_indicator)), a...
The code implements a Q-learning agent that decides actions in a game by balancing exploration and exploitation. It tracks the agent's state, avoids loops by detecting repeated positions, and selects actions based on Q-values. The agent updates records, checks allowed actions, and uses epsilon-greedy strategies for exp...
def act(self, game_state: dict) -> str: """ Your agent should parse the input, think, and take a decision. When not in training mode, the maximum execution time for this method is 0.5s. :param self: The same object that is passed to all of your callbacks. :param game_state: The dictionary that describes eve...
def findPossibleCharsInPlate(img_grayscale, img_thresh): list_of_possible_chars = [] # this will be the return value contours = [] img_thresh_copy = img_thresh.copy() # find all contours in plate contours, npa_hierarchy = cv2.findContours(img_thresh_copy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) ...
This function processes each detected license plate by preprocessing images, identifying character contours, grouping matching characters, removing overlaps, and recognizing characters to extract plate text, returning updated plates with detected characters.
def detect_chars_in_plates(list_of_possible_plates): int_plate_counter = 0 img_contours = None contours = [] if len(list_of_possible_plates) == 0: # if list of possible plates is empty return list_of_possible_plates # return # at this point we can be sure the list of possible plates has ...
def reset_board(): board = np.zeros((8, 8), dtype=np.int8) board[[3, 4], [4, 3]] = 1 board[[4, 3], [4, 3]] = -1 board = board.tolist() return board def find_possible_moves(self, board, player): moves = set() for xb in self.x_board: for yb in self.y_boa...
This code simulates a game between a random player (player 1) and an AI (player -1) in Othello. It alternates turns, with player 1 choosing random moves and player -1 using either a simple or model-based strategy depending on move count. The loop continues until both players have no valid moves, then returns the final ...
def test_vs_random_bot(self, _): board = self.reset_board() player = 1 move_count = 0 no_possible_moves = [False, False] while True: moves = self.find_possible_moves(board, player) if len(moves) == 0: # if no possible moves: for both player end the iothel...