dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def __is_account_already_exists(self, account: Account) -> bool: accounts = self.get_all_accounts() res = [True if equal_accounts(account, acc) else False for acc in accounts] return any(res) def get_all_accounts(self) -> List[Account]: with open('{}.csv'.format(self.__filename), 'r') as...
The code updates an existing account by replacing the old account with a new one in a CSV file. It checks if the old account exists, retrieves all accounts, finds the index of the old account, replaces it with the new one, and writes the updated list back to the CSV file.
def update_account(self, old_account: Account, new_account: Account): if self.__is_account_already_exists(old_account) is True: accounts = self.get_all_accounts() index = find_account_index(accounts, old_account) accounts[index] = new_account self.__write_accounts...
def process_input(source, args): row = int(args.get("row")) column = int(args.get("column")) path = args.get("path") basedir = args.get("basedir") language = args.get("language") dirs = args.get("dirs") catalogs = args.get("catalogs").split(",") if args.get("catalogs") else [] env =...
The code processes input based on a specified mode (completions, definitions, calltips, catalogs) by analyzing the source code, scanning the workspace, and returning relevant data as JSON. It uses helper functions to retrieve completion suggestions, definitions, call tips, or catalogs, depending on the mode, and format...
def process(source, args): mode = args["mode"] buffer, line, offset = process_input(source, args) scan_workspace(buffer) if mode == "completions": return json.dumps(get_completions(buffer, line, offset)) if mode == "definitions": return json.dumps(get_definitions(buffer, line, o...
def dilation(self, grayScaleImage, kernelSize, kernel_structure): # get kernel we need kernel = self.create_kernel_structure(kernelSize, kernel_structure) # add padding to the image padding_pixels = kernelSize // 2 image_padded = np.pad(grayScaleImage, ((padding_pixels, padding_...
This function performs morphological operations (dilation, erosion, opening, closing) on an image. If the image is in color, it processes each color channel (BGR) separately and merges them. For grayscale images, it directly applies the operation. The kernel size and structure determine the morphology's effect, returni...
def perform_morphology(self, mode, color, kernelSize, kernel_Structure): if color is True: b, g, r = cv2.split(self.originalImage) if mode.lower() == "dilation": dilated_b = self.dilation(b, kernelSize, kernel_Structure) dilated_g = self.dilation(g, kernel...
def distances(points): result = {} for i in range(len(points)): p1 = points[i] for j in range(i+1, len(points)): p2 = points[j] d = distance(p1, p2) assert d not in result result[d] = (p1, p2) return result def one(it): values = list(it) ...
The main task of the code is to compute the 3D positions and orientations of multiple scanners relative to a reference scanner by matching overlapping beacon points. It iterates through scanner pairs, identifies shared beacons, calculates coordinate transformations, and resolves consistent orientations to determine eac...
def find_positions(): while len(positions) < len(scanners) - 1: for sf, scanner_from in enumerate(scanners): if sf != 0 and sf not in positions: continue d1 = distances(scanner_from) for st, scanner_to in enumerate(scanners): if st == 0 or...
def parse_header(self): _ = self.read(3, "version") return self.read(3, "type_id") def parse_literal(self): start = self.i ret = "" while True: part = bits[self.i:self.i+5] ret += part[1:] self.i += 5 if part[0] == "0": ...
This function parses a packet by determining its type, handling literal values or sub-packets based on a length type identifier, recursively processing nested packets, and applying an operator to the collected values to return an integer result.
def parse_packet(self): type_id = self.parse_header() if type_id == 4: return self.parse_literal() length_type_id = self.read(1, "length_type_id") if length_type_id == 0: length = self.read(15, "length") stop = self.i + length values = [] ...
def extract_root_domain(url): tsd, td, tsu = extract(url) if tsd == "": top = td + '.' + tsu else: #Include subdomain if it exists top = tsd + '.' + td + '.' + tsu return top def check_dir(root_domain): i = 0 new_dir = root_domain #Check if directory exists, if yes r...
The function automates web scraping by navigating to a URL, checking its status code against a specified value, handling alerts, taking screenshots, attempting a dummy login, and collecting HTTP resources. It returns True on successful execution or False if errors occur, such as invalid status codes, driver issues, or ...
def grim(url, filetype, useragent, headless_mode, logs, all_resource, alert, wait_time, txt, statuscode, proxy, proxycred, login, href): try: root_domain = extract_root_domain(url) url_root_domain = root_domain urls = [] urls_filetype = {} responses = 0 #This will be ...
def check_args(): parser = argparse.ArgumentParser() parser.add_argument('--url', required=True, help="Specify the URL") parser.add_argument('--filetype', required=False, help="Specify the resource filetype to save") parser.add_argument('--useragent', required=False, help="Specify the user agent. Defaul...
The main task of the code is to scrape URLs (either from a text file or a single URL) using configurable parameters like user agent, proxy, and headless mode. It processes each URL with the `grim()` function, outputs success/failure status, and handles errors. The script reads input arguments, executes scraping tasks, ...
def main(): try: url, filetype, useragent, headless_mode, logs, all_resource, alert, wait_time, txt, statuscode, proxy, proxycred, login, href = check_args() if txt: url_txt = [] url_txt = read_txt(url) #If reading URLs from a file, perform the scraping for each ...
def discharge_mask(charge_schedule, working_charge_schedule, discharge_time, battery_mode): # Mask system used as .loc difficult to use in this application: ideally would put working_charge_schedule in place of discharge_time_mask discharge_time_mask = charge_schedule.index.to_series().isin(working_charge_sched...
The function optimizes a charge schedule by iteratively selecting profitable intervals for charging and discharging a battery, based on price or carbon reduction motives. It identifies the highest-price interval for discharging, calculates virtual net profit for charging, and adds charge/discharge pairs if profitable. ...
def v2(charge_schedule, battery_mode, motivation): """Populates charge schedule with charge and discharge commands, at intervals which result in a net profit. Works by selecting the maximum price interval for discharging, calculating the virtual net profit for charging (to enable discharging) in all other i...
def journey_origin(inputs): """Defines the journey origin- read from Inputs Schedule. This value should always be set to the Home Address""" journey_start = inputs['Origin'] # This should be read from the input file return journey_start def journey_destination(inputs, reserve_journey): """Defines the j...
The main task of the code is to retrieve and print journey details from Excel input data, including origin, destination, optimistic travel time, actual time, traffic-affected time, and distance. It processes the input data through multiple functions to generate and display these parameters for a specified journey.
def main(): inputs = pd.read_excel('../Inputs/Yaz_Journey_API_inputs_data.xlsx').iloc[0, :] # response = initialise_api_data(inputs, reserve_journey) # print(response.text) journey_start = journey_origin(inputs) journey_end = journey_destination(inputs, False) time_optimistic = journey_time_opti...
def clear(): """ Function to define a way to clear the screen in a way that is cross-platform. """ if os.name == "nt": _ = os.system("cls") else: _ = os.system("clear") def preflightChecks(droneManufacturer): """ This function just grabs preflight checks from .txt files in the "checklists/preflig...
This function displays a flight-stage menu (Preflight, Takeoff, Flight, Landing, Non-normal Checklist, Exit) and loops until the user selects "6" (Exit). It validates input, executes corresponding checklists for options 1-5, and shows warnings for non-normal checklists. Invalid inputs trigger error messages and reloopi...
def displayMenu(droneManufacturer): """ This function displays a menu that the user can pick options from. An invalid option is caught, we tell the user that they've picked an option that doesn't quite work and then loop back to the menu """ userInput = "" clear() while userInput != "6": print("Please C...
def h(p1, p2): x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2) def go_though_path(came_from,current,draw): if came_from: #stay in place if an enemy is in front temp=came_from[current] if not temp.is_enemy(): current.reset() temp.make_enemy() ...
The code implements the A* pathfinding algorithm to find a path from a start node to an end node on a grid. It uses a priority queue to explore nodes, calculating `g` (cost from start) and `f` (estimated total cost) scores. When the end node is reached, it returns `True` or constructs the path if `makepath` is enabled....
def algorithm(draw, grid, start, end,makepath): #count is used to break ties if two tiles have the same score count = 0 # all the tiles we are considering open_set = PriorityQueue() # 0 is f score, count - break ties if two values had the same score, just pick the first one, start is the node ...
def make_grid(rows, width): grid = [] # gap - gap between each rows gap = width // rows for i in range(rows): # makes a 2d list grid.append([]) for j in range(rows): spot = Spot(i, j, gap, rows) grid[i].append(spot) return grid def algorithm(draw, g...
This code initializes a grid-based game with obstacles, objectives, portals, and enemies. It ensures all objectives are reachable, places the player and enemies with valid paths, and implements movement mechanics. The game loop handles player input, enemy AI using pathfinding, and checks for win/loss conditions based o...
def startgame(win, width): # number of rows in a grid ROWS = 30 grid = make_grid(ROWS, width) #places 250 walls randomly for x in range(0,250): temp=False while(not temp): number=random.randint(0, 29) number2 = random.randint(0, 29) if(grid[num...
def overwrite_highscore(game_stats): file_content = '' with open ("./data.json", "r") as file_r: file_content = json.load(file_r) if file_content["high_score"] < game_stats.high_score: file_content["high_score"] = game_stats.high_score with open ("./data.json", "w") as file_...
The function handles user input events in a game, processing keyboard and mouse actions. It exits on quit, resets the game on Enter key during game over, and manages play button interactions (hover effects, state transitions) based on the current game state (menu or play). It updates the screen and triggers game restar...
def check_event(ship, game_setting, screen, bullets, btn_play, game_stats, aliens, game_settings, score, sound, menu): for event in pygame.event.get(): if event.type == pygame.QUIT: overwrite_highscore(game_stats) sys.exit() if event.typ...
def check_collision(game_settings, aliens): for each_alien in aliens.sprites(): if each_alien.check_collision(): change_fleet_direction(game_settings, aliens) break def reset_game(game_settings, screen, game_stats, ship, aliens, bullets, score, sound): if game_stats.ship_live...
The function `update_fleet` manages alien movement and collision checks in a game. It updates alien positions, detects collisions between the player's ship and aliens, and triggers a game reset if a collision occurs. It also checks if aliens reach the screen bottom, likely triggering game-over logic. The function integ...
def update_fleet(game_settings, aliens, ship, screen, game_stats, bullets, score, sound): check_collision(game_settings, aliens,) aliens.update() if pygame.sprite.spritecollideany(ship, aliens): reset_game(game_settings, screen, game_stats, ship, aliens, bullets, score, sound) aliens_hit_bottom...
def calculate_h(node, end): a=getVertexCoords(node,4) b=getVertexCoords(end,4) x1=a[0] y1=a[1] x2=b[0] y2=b[1] h = 0 h=math.sqrt(2)*min(abs(x2-x1),abs(y2-y1))+max(abs(x2-x1),abs(y2-y1))-min(abs(x2-x1),abs(y2-y1)) return h def getPath(node): path =[node] current = node whi...
The code implements a pathfinding algorithm (A*) to find a route from a start node to an end node. It uses a priority queue (fringeList) to explore nodes, calculating heuristic (h_value) and cost (g_value) values. Nodes are expanded by checking successors, updating their costs, and avoiding revisiting closed nodes. The...
def Solve(start, end): start.g_value = 0 start.parent = start fringeList=[] heapq.heapify(fringeList) start.h_value = calculate_h(start, end) heapq.heappush(fringeList, (start, -1 * start.g_value + start.h_value)) closedList=[] heapq.heapify(closedList) while len(fringeList) != 0: ...
def getDist(s,s2): a=getVertexCoords(s.name - 1,matrix_m) b=getVertexCoords(s2.name - 1,matrix_m) x1=a[0] y1=a[1] x2=b[0] y2=b[1] xVal=x2-x1 yVal=y2-y1 if(xVal == 0 or yVal == 0): print('1 Cost to go From: {} To: {}'.format(s.name - 1, s2.name - 1)) return 1 else:...
This function updates the path cost and priority of a node (s2) in a priority queue (fringeList) when a cheaper path via another node (s) is found. It recalculates s2's g-value, h-value, and f-value, removes s2 from the queue if present, and reinserts it with the updated priority to reflect the improved path.
def UpdateVertex(s,s2, fringeList, start, end): if s.g_value + getDist(s,s2) < s2.g_value: print('Found better path to s`, setting s` parent to s...') s2.parent = s if s2 in fringeList: print('s` found in fringe list.\nRemoving from list and reheapifying...') fringeLi...
def calculate_h(node, end): a=getVertexCoords(node.name - 1,matrix_m) b=getVertexCoords(end.name - 1,matrix_m) x1=a[0] y1=a[1] x2=b[0] y2=b[1] h = 0 h=math.sqrt(2)*(min(abs(x2-x1),abs(y2-y1))) + max(abs(x2-x1),abs(y2-y1)) - min(abs(x2-x1),abs(y2-y1)) return h def getPath(node): p...
This function implements a pathfinding algorithm using a priority queue (fringe) and closed list to explore routes from 'start' to 'end' in a matrix. It calculates heuristic (h_value) and cost (g_value) for nodes, updates successor nodes via UpdateVertex, and returns a path if the goal is reached, otherwise returns fai...
def Solve(start, end, matrix): start.g_value = 0 start.parent = start fringeList=[] heapq.heapify(fringeList) start.h_value = calculate_h(start, end) start.updateFValue() # Not sure if this works heapq.heappush(fringeList, (start.g_value + start.h_value, start)) closedList=[] heapq.h...
def update_guide_instruction(self) : #print("num3 = ", self.num3) self.guide_list[self.num3] = self.get_guide_exit_num() self.num3 += 1 if self.num3 == self.iters : self.num3 = 0 self.level = list(Counter(self.guide_list).keys())[0] if self.level == 4 : Recognizer.SHOW_INST = False Recognizer.S...
The code updates different UI components based on Recognizer flags: guide/instruction, menu, or game. It checks if SHOW_GUIDE/SHOW_INST is active to update guides, SHOW_MENU to update the menu, or defaults to updating the game itself. The delta parameter likely controls the update timing or state transitions.
def update(self, delta) : if Recognizer.SHOW_GUIDE or Recognizer.SHOW_INST : self.update_guide_instruction() elif Recognizer.SHOW_MENU : self.update_menu() else : self.update_game()
def event(self, event): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == pygame.BUTTON_LEFT: if not self.start_line_pos: self.start_line_pos = event.pos self.obstacles.append(Line(self.start_line_pos, event.pos)) e...
This code runs a game loop using Pygame, handling events (like quitting), updating game state with delta time and mouse position, and rendering frames at 100 FPS until the user exits.
def loop(self): running = True while running: dt = self.clock.tick(100) / 1000 * 60 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False else: self.event(event) mouse...
def intersections_without_word(words: list, without_word: str)->set: """ The function returns the intersection of the locations of the words without one word """ locations = [WORD_TRIE.get(word) for word in words if word != without_word] if None in locations or not locations: return set() ...
The function manages user input for text searches by processing input to generate autocomplete suggestions. It extracts words, checks for valid input, and uses helper functions to find intersections and generate candidates. It displays top results or prompts for more input if no matches are found, looping until a valid...
def user_query(): """ The function manages the communication with the client """ sentence = input("Hello, enter the text that you to find:\n") while True: if sentence.endswith('#'): sentence = input("Hello, enter the text that you to find:\n") words = re.findall(r'\w+', ...
def _assertSpecified(self, items, check_in): for x in items: if check_in[x] is None: raise ValueError(check_in[x] + ' must be specified.') def _assertList(self, items, check_in): for x in items: if not isinstance(check_in[x], list): raise ValueError(x + ' must be a list.') def _logit...
The function `regularized_loss` computes the total loss by combining an unregularized loss with L1 and L2 regularization terms. It validates input examples, computes logits, and returns the sum of regularization losses (`_l1_loss`, `_l2_loss`) and the unregularized loss from examples. This integrates regularization int...
def regularized_loss(self, examples): """Add operations to compute the loss with regularization loss included. Args: examples: Examples to compute loss on. Returns: An Operation that computes mean (regularized) loss for given set of examples. Raises: ...
def sparse_graph_from_neighborlist(displacement_fn: Callable, positions: jnp.ndarray, neighbor: partition.NeighborList, r_cutoff: jnp.array, species: jnp.array = None, ...
Your return The function converts particle positions, boxes, and species data into sparse graph representations for molecular datasets. It handles variable numbers of particles and boxes across snapshots, generating edges and triplets based on a radial cutoff. With padding, it returns a unified `SparseDirectionalGrap...
def convert_dataset_to_graphs(r_cutoff, position_data, box, species, padding=True): """Converts input consisting of particle poistions and boxes to a dataset of sparse graph representations. Due to the high memory cost of saving padded graphs, this preprocessing step is on...
def getOptions(): parser = OptionParser() parser.add_option('-f', '--ftp', help="Required: Location of the FTP genomes directory", metavar="DIR", default='', dest="ftpDir") parser.add_option('-g', '--gid', help="Optional: File containing genome ID list to filter off of", metavar='FILE', default='', dest='gidFNm') ...
The code processes genomic data by parsing command-line options, extracting gene identifiers (GIDs), analyzing FTP data to compute statistics, identifying high-quality genomes, generating output files (FASTA, tables), and printing top results. It focuses on data analysis, filtering, and structured output for genomic re...
def main(): options, parser = getOptions() gids = getGIDLst(options.gidFNm) plfHsh,figPLFHsh,plfLenHsh,gidFigHsh, figLenHsh = parseFTP(options, gids) plfStaHsh = getPLFStaHsh(plfHsh) printStats(options, plfStaHsh) gGenFighsh, topPLFs = getGoodGenomes(options, plfStaHsh, gidFigHsh, figPLFHsh, figLenHsh, plfLenH...
def send_message_to_player(self, player, message): message_with_hp = "[{} - HP: {}] {}".format(player.name, player.hp, message) player.conn.send(message_with_hp.encode()) def handle_challenge(self, challenger, data): with self.challenge_lock: if not challenger.challenged: ...
This code handles a player's interactions in a game, sending initial instructions, processing commands like 'challenge', 'choice', 'chat', or 'quit', and managing the player's HP. It keeps the player active in the game loop as long as their HP is positive, calling appropriate methods for each command and removing the p...
def handle_player(self, player): self.send_message_to_player(player, "Game started! You have {} HP.\n You can challenge other players by sending 'challenge <player_name> <choice>.\n Choices: R (Rock), P (Paper), S (Scissors)\n Example: challenge player2 R\n use 'choice <choice>' to respond to a challenge. Examp...
def send_message_to_player(self, player, message): message_with_hp = "[{} - HP: {}] {}".format(player.name, player.hp, message) player.conn.send(message_with_hp.encode()) def remove_player(self, player): self.players.remove(player) player.conn.close() # Remove player from any act...
This code processes a challenge between two players in a game, determining outcomes based on their choices (rock-paper-scissors logic). It updates HP for winners/losers, sends result messages, checks for elimination if HP reaches zero, and declares a winner when only one player remains.
def handle_challenge_response(self, challenger, opponent): if challenger.choice == opponent.choice: self.send_message_to_player(challenger, "It's a draw with {}.".format(opponent.name)) self.send_message_to_player(opponent, "It's a draw with {}.".format(challenger.name)) else: ...
def tournament_teams(data): """ Removes teams from the data set that do not have a seed in the tournament """ # removes field names data = np.delete(data, 0, 0) for team in reversed(range(NUM_TEAMS)): if data[team][3] == "": data = np.delete(data, team, 0) return d...
The main task of the code is to load tournament data from a CSV file, filter out non-tournament teams, and compute/print three metrics for the first round: highest likelihood, highest-ranked teams, and random likelihood outcomes. It uses functions to process data and generate results for analysis.
def main(): data = np.loadtxt("data.csv", delimiter=",", dtype=str) # removes non-tournament teams data = tournament_teams(data) print(highest_likelihood(first_round, data)) print(highest_ranked(first_round, data)) print(random_likelihood(first_round, data))
def match_hoi(pred_det, gt_dets): is_match = False remaining_gt_dets = [gt_det for gt_det in gt_dets] for i, gt_det in enumerate(gt_dets): human_iou = compute_iou(pred_det['human_box'], gt_det['human_box']) if human_iou > 0.5: object_iou = compute_iou(pred_det['object_box'], gt_d...
The function `eval_hoi` evaluates the performance of predicted Human-Object Interaction (HOI) detections against ground truth annotations. It processes each HOI class (`hoi_id`), matches predicted detections (`pred_anno`) to ground truth (`gt_dets`), and computes the Average Precision (AP) metric. Detections are sorted...
def eval_hoi(self, hoi_id, global_ids, gt_dets, pred_anno, mode='default', obj_cate=None): # print(f'Evaluating hoi_id: {hoi_id} ...') y_true = [] y_score = [] det_id = [] npos = 0 for global_id in global_ids: if hoi_id in gt_dets[global_id]: ...
def deal(self): for player in self.__players: player.draw(self.deck) def __limit__(self, playerPointer): biggestBet = max(self.__playersCurrentBets) return not (self.__playersCurrentBets[playerPointer] == biggestBet) def processPlayerAction(self, action, playerIndex): playerM...
This code manages a game round by iterating through players to take actions, processing bets, and dealing communal cards when all players have acted. It checks for a single-player scenario to declare a winner, resets pointers, and transitions to the next phase when betting is complete.
def play(self): self.deal() playerPointer = 0 while self.__status == e.ROUNDSTATUS.IN_ROUND: action = self.__players[playerPointer].action(self, self.__limit__(playerPointer)) self.processPlayerAction(action, playerPointer) playerPointer += 1 if s...
def _init_params(self, init_flag, hidden_units): """ Initialize parameters according to the init_flag: 1 for random initializations (a uniform distribution from -0.1 to 0.1) and 2 for zero initializations. Bias term will always be initialized to zero. hidden_units: number of hid...
The main task of the code is to train a neural network using Stochastic Gradient Descent (SGD) over a specified number of epochs. It initializes model parameters, performs forward and backward passes for each training example, updates parameters using gradients, and records cross-entropy loss on both training and valid...
def train(self, t_labels, t_data, v_labels, v_data, num_epoch, hidden_units, init_flag, learning_rate, metrics_f): """ Train the neural net using Stochastic Gradient Descent (SGD). """ # initialize parameters alpha, beta = self._init_params(init_flag, hidden_units) ...
def load(self, input_file): """ Load data into memory. Returns: labels list, data table """ raw_data = np.genfromtxt(input_file, delimiter=',', dtype=np.int, autostrip=True) # in numpy, arrays slices are just views on the original array ...
The main task of the code is to initialize a model, train it using provided training and validation data, and evaluate its performance by calculating and saving training/validation errors to a metrics file. It loads input data, sets up model parameters, trains the model (via self.train()), and writes error metrics usin...
def __init__(self, train_input, validation_input, train_out, validation_out, metrics_out, num_epoch, hidden_units, init_flag, learning_rate): t_labels, t_data = self.load(train_input) v_labels, v_data = self.load(validation_input) # number of inputs values exclu...
def gcost(mat, targetmat): count = 0 for i in range(len(mat)): for j in range(len(mat[0])): if (mat[i][j] != targetmat[i][j]) : count += 1 return count def sumkurang(mat): sum = 0 ckr = 0 for i in range(len(mat)): for j in range(len(mat[0])): ...
This code solves a sliding puzzle (like the 8-puzzle) using A* algorithm with a priority queue. It checks if the puzzle is solvable by verifying the parity of "sumkurang" and explores possible moves by generating new states from the empty tile's position. It tracks execution time and the number of generated nodes, outp...
def solve(mat,target): start = timeit.default_timer() pq = priorityQueue() gc = gcost(mat,target) root = node(None,mat,0,gc) pq.push(root) jumlahsimpul = 1 if (sumkurang(mat) %2 != 0) : print("Tidak ada solusi") end = timeit.default_timer() else : row = [-1,0,1,0...
def gcost(mat, targetmat): count = 0 for i in range(len(mat)): for j in range(len(mat[0])): if (mat[i][j] != targetmat[i][j]) : count += 1 return count def sumkurang(mat): sum = 0 ckr = 0 for i in range(len(mat)): for j in range(len(mat[0])): ...
This code solves a puzzle (e.g., 8-puzzle) using A* search with a priority queue. It checks if the initial state is solvable via sumkurang parity, generates valid moves, and tracks nodes. If a solution is found, it prints the path; otherwise, it reports failure. Time and node count are also measured.
def solve(mat,target): start = timeit.default_timer() pq = priorityQueue() gc = gcost(mat,target) found = False root = node(None,mat,0,gc,-1) pq.push(root) jumlahsimpul = 1 if (sumkurang(mat) %2 != 0) : print("SOLUSI TIDAK DITEMUKAN") else : row = [-1,0,1,0] ...
def init (self): N = 256 self.i = 0 self.j = 0 self.k = 0 self.z = 0 self.a = 0 self.w = 1 self.s = [i for i in range(N)] def absorb_bytes (self, bytes): for byte in bytes: self.absorb(byte) def absorb_stop (self): if self.a == N // 2: self.shuffle() self.a = (sel...
This function performs authenticated encryption using AEAD (Authenticated Encryption with Associated Data). It absorbs the key, nonce, and header, then encrypts plaintext in blocks using a sponge-based algorithm. The output is a ciphertext and a MAC (message authentication code) of specified length, ensuring both confi...
def aead_encrypt (self, nonce, key, header, plaintext, mac_len): self.init() self.absorb_bytes(key) self.absorb_stop() self.absorb_bytes(nonce) self.absorb_stop() self.absorb_bytes(header) self.absorb_stop() data_size = len(plaintext) block_size = N // 4 block_count = data_si...
def init (self): N = 256 self.i = 0 self.j = 0 self.k = 0 self.z = 0 self.a = 0 self.w = 1 self.s = [i for i in range(N)] def absorb_bytes (self, bytes): for byte in bytes: self.absorb(byte) def absorb_stop (self): if self.a == N // 2: self.shuffle() self.a = (sel...
This function decrypts data using an AEAD (Authenticated Encryption with Associated Data) scheme. It initializes the cryptographic context, absorbs the key, nonce, and header, then processes the plaintext in blocks using XOR and squeezing operations. It constructs the decrypted ciphertext and generates a MAC (message a...
def aead_decrypt (self, nonce, key, header, plaintext, mac_len): self.init() self.absorb_bytes(key) self.absorb_stop() self.absorb_bytes(nonce) self.absorb_stop() self.absorb_bytes(header) self.absorb_stop() data_size = len(plaintext) block_size = N // 4 block_count = data_si...
def tuneMCMmultker(xTrain, yTrain, kerTypeMCM , cParams , gamma , alpha ): n,d = xTrain.shape xTrain1,xValid,yTrain1,yValid = train_test_split(xTrain, yTrain, test_size = 0.2, random_state = 42) bestAcc = 0 Cbest = 0 tempalpha = alpha for i in range(len(cParams)): Ctest = cParams[i] ...
The code performs cross-validation on a dataset using a multi-kernel machine learning model. It loads data, splits it into training/test sets, normalizes features, tunes hyperparameters (C, alpha, gamma) via iterative optimization, and evaluates model performance (accuracy, support vectors) across 5 folds. Results are ...
def main(): for dataset in [30]: print(dataset) data = pd.read_csv('data_folds/'+str(dataset)+'.csv') data = np.array(data) folds = pd.read_csv('data_folds/'+str(dataset)+'fold.csv') folds = np.array(folds).ravel() y = data[:,-1] x = data[:,:-1] n...
def margin_kernel(self, X1, kernel_type = 'linear', gamma =1.0): """ X1: n_samples1 X M X: n_samples1 X n_samples1 : if kernel_type is non primal """ if(kernel_type == 'linear'): X = linear_kernel(X1,X1) elif(kernel_type == 'rbf'): X = rbf...
This function performs optimization for machine learning models using kernel methods or primal solvers. It trains models with specified algorithms (MCM/LSMCM), handles Mercer/non-Mercer kernels, iterates for convergence, and returns optimized weights, objective values, iterations, and function evaluations. It adapts to...
def inner_opt(self, X, Y, data1, level): gamma = self.gamma kernel_type = self.kernel_type iterMax2 = self.iterMax2 iterMax1 = self.iterMax1 tol = self.tol algo_type = self.algo_type #if data1 = None implies there is no kernel computation, i.e., there is only prim...
def subset_selection(self,X,Y): n_components = self.n_components PV_scheme = self.PV_scheme problem_type = self.problem_type N = X.shape[0] # M = X.shape[1] numClasses = np.unique(Y).size use_global_sig = False use_global_sig1 = False if(us...
This code trains an ensemble of models using random feature and sample subsampling, kernel transformations, and combines their outputs. It handles both classification and regression tasks, with separate logic for each. For regression, it creates robust predictions by adding/subtracting epsilon, while classification use...
def fit(self,xTrain,yTrain): #xTrain: samples Xfeatures #yTrain: samples #for classification: entries of yTrain should be between {0 to numClasses-1} #for regresison : entries of yTrain should be real values N = xTrain.shape[0] M = xTrain.shape[1] if(self.problem...
def extract_features(self, face_landmarks): return { "forehead": self.average_landmark([ face_landmarks.landmark[67], face_landmarks.landmark[69], face_landmarks.landmark[66], face_landmarks.landmark[109], face_landmark...
The code processes facial landmarks by extracting features, determining orientation, converting orientation to Euler angles for rotation, and returning these three components as results.
def process_face(self, face_landmarks): face_features = self.extract_features(face_landmarks) orientation = self.extract_orientation(face_features) rotation = self.euler_angles_from_orientation(orientation) return face_features, orientation, rotation
def exercise_a_calculations(): xls = pd.read_excel('./Tables/Table 1.xlsx') a = np.array d_i = 0.0089 L = 0.66*a([4, 3, 2, 1]) A_i = d_i*np.pi*L T_h = 273.15 + 47.5 T_c = 273.15 + 12.7 c_p_c = 4182 c_p_h = 4180 rho_h = 1/(1.0114*10**-3) rho_c = 1/(1.0008*10**-3) m_dot_h =...
The main task of the code is to sequentially execute four calculation functions (A-D), clear accumulated results after each, and generate a plot. It processes distinct exercises, isolates their outputs by resetting shared data storage (`VALUES`), and finally visualizes results from the last exercise via `figure_1_plot(...
def calculations(): exercise_a_calculations() VALUES.clear() exercise_b_calculations() VALUES.clear() exercise_c_calculations() VALUES.clear() exercise_d_calculations() figure_1_plot() return
def exercise_a_calculations(): xls = pd.read_excel('./Data/Table 1, 2.xlsx') t1_columns = ['d [mm]', 'Q [m^3/s]', 'T [C]', 'h1 [m]', 'h2 [m]', 'V_avg [m/s]', 'v [m^2/s]', 'Re_D', 'f_e', 'f_c', 'h_e [m]', 'h_c [m]'] for column_name in t1_columns: get_average_sa...
The main task of the code is to execute a series of calculations and generate visualizations. It runs functions for Exercise A, B, and D calculations, followed by plotting three figures (Figure 1, 2, 3), likely for data analysis or reporting. The code sequentially processes mathematical computations and their correspon...
def calculations(): exercise_a_calculations() figure_1_plot() figure_2_plot() figure_3_plot() exercise_b_calculations() exercise_d_calculations()
def name(self): """ name is folder name """ return os.path.basename(os.getcwd()) def description(self): """ first line of readme """ try: readme = [ f for f in os.listdir(os.getcwd()) if f.lower().startswith("readme") ][0] with open(rea...
This method generates default parameters for a package setup by returning a dictionary containing keys like name, description, version, and others, each populated by calling corresponding instance methods. It is typically used in Python package configuration to standardize setup configurations, ensuring consistent meta...
def setup_defaults(self): """ default params for setup """ return dict( name=self.name(), description=self.description(), version=self.version(), url=self.url(), install_requires=self.install_requires(), packages=self.packages(), ...
def make_produce_array(element_producer): n = random.randint(2, 5) def produce(): return '[' + ','.join([element_producer() for i in range(n)]) + ']' return produce def make_produce_class(value_producers): keys = make_keys(len(value_producers)) def produce(): return '{' + ','.join(...
This script generates large JSON documents with customizable structures, supporting arrays, objects, nested elements, and combinations. It uses command-line arguments to define size, type (int/array/object), nesting depth, and includes options for string lists, class generation, and complex nested object creation. The ...
def main(): parser = argparse.ArgumentParser( description="Generate a large JSON document.") parser.add_argument('--array-size', nargs=1, type=int, default=[100000]) parser.add_argument( '--array-type', choices=['int', 'array', 'object'], default='object') parser.add_argument('--array-el...
def get_dependencies( *, requirements: str | pathlib.Path = None, dev_requirements: str | pathlib.Path = None ) -> tuple[Dependencies, Dependencies]: if requirements is not None and os.path.exists(requirements): dependencies = parse_requirements(source=requirements) if dev_...
The main task of this code is to configure and set up a Python package by collecting files, dependencies, and metadata. It processes parameters like `package`, `readme`, `requirements`, and `include` to generate package data, resolve dependencies, and prepare setup arguments. The function constructs package names, hand...
def setup( package: str | pathlib.Path, *, readme: str | bool | pathlib.Path = None, exclude: Iterable[str | pathlib.Path] = None, include: Iterable[str | pathlib.Path] = None, requirements: str | pathlib.Path = None, dev_requirements: str | pathlib.Path = None, p...
def _get_path_to_output_file(path_to_input_file, path_to_output_dir): if not path_to_output_dir: return None input_filename = util_file.get_last_part_of_path(path_to_input_file) output_filename = util_file.change_extension( input_filename, ".yaml.txt" ) # adding .txt so can preview in W...
This function processes input files, directories, or URLs by summarizing their content into specified output files. It ensures the output directory exists, skips existing output files, processes each input file, tracks processing statistics (files processed, skipped, time, cost), and prints a summary of results.
def summarize_file_or_dir_or_url( path_to_input_file_or_dir_or_url, path_to_output_dir, target_language ): if path_to_output_dir: util_dir.ensure_dir_exists(path_to_output_dir) input_filepaths = extractor.collect_input_filepaths( path_to_input_file_or_dir_or_url ) files_processed =...
def side_string(self, side): if side not in self.sides: side = self.sides[side] return side def can_move(self, side, pos): side = self.side_string(side) return self.cube[side][pos] == '-' def move_piece(self, player, side, pos): self.cube[side][pos] = player def check_side_win(se...
The function `make_move` executes a player's turn in a game by validating the move, updating the game state (recording moves, removing open positions), performing the move, checking for side-specific wins/ties, edge interactions, and overall win conditions, then returning `True` if valid; otherwise, `False` if invalid ...
def make_move(self, player, side, pos): side = self.side_string(side) if not self.can_move(side,pos): #or self.is_game_over: return False # Invalid move / Game ended if player == "X": self.x_moves.append((side,pos)) if player == "O": self.o_moves.a...
def get_batch(self, split: str) -> tuple[torch.Tensor, torch.Tensor]: # data = self.config.train_data if split == 'train' # else self.config.val_data data = self.config.data.data.get(split, None) assert data is not None ix = torch.randint( len(data) - self.config.mode...
The code trains a model by iterating over batches, performing forward/backward passes via `train_step`, logging metrics (loss, speed, MFU), evaluating periodically with `evaluate`, and saving checkpoints based on validation loss. It tracks timing, updates training history, and syncs metrics to W&B for monitoring.
def train( self, train_iters: Optional[int] = None, ): x, y = self.get_batch('train') t0 = time.perf_counter() running_mfu = -1.0 output = {'x': x, 'y': y} t0 = time.perf_counter() losses = {} train_iters = ( self.config.tra...
def left_click(self, mouse_pos): clicked_cell = self.get_clicked_cell(mouse_pos) if clicked_cell: row, col = clicked_cell if self.flags[row][col]: return self.board[row][col].hidden = False #print(f"Left-clicked cell: row={row}, col={col}") if ...
This code manages a game loop using Pygame, handling user input for menu navigation and game interactions. It displays a menu, processes selections to start a new game or quit, and transitions to game states. It checks win/game-over conditions, renders the board, and displays appropriate messages, resetting the menu af...
def run(self): running = True menu = True while running: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONUP: if even...
def mass_to_dict(mass): ''' mass is in the form of [ mass, [[y_min],[y_max coords],[x_min coords],[x_max coords]], mass_ID] converts a masses values to dictionary returns dictionary of coordinates params: refined_arr - array of image closed in around the specified mass mass is in ...
This function merges adjacent masses in the y-direction if they are spatially close (within a specified skip range), combining their coordinates and IDs. It iterates backward through the mass list, merges overlapping or nearby masses, updates the mass structure, and returns the modified masses along with unique IDs of ...
def bridge_masses_by_y(masses_by_y, skip = 2):#incomplete ''' combines masses that are within prosthesis, or same body and cut off masses_by_y [combined_mass, [[h_min, w_h_min], [h_max, w_h_max], [h_w_min, w_min], [h_w_max, w_max]], mass_ID] y groupings in form of [[h,[w_start, w_end, mass_ID],[w_start,...
def primer(img_arr, rearrange): ''' runs preliminary look at image to get needed data ''' #img_arr = convert_to_grey_scale(img_arr) #brightest_fraction = .35 #get_brightest_fraction(img_arr) #outdated program, couldn't find in initial files t_img_arr = np.rot90(img_arr, 1) #compact_img_...
The main task of the code is to analyze X-ray images of prostheses by isolating the brightest regions (assumed to be the prosthesis), determining its orientation and bounds, reframing the image to focus on the prosthesis, and excluding non-essential features like the head and shell. It uses intensity thresholds, mass g...
def main_exec(logger): ''' Program takes an image array and isolates the brightest, or highest values, or intensities It creates spans along a single axis where are the adjacent pixels are above the intensity It creates masses from the adjoining spans (adjoining up and down and side to side) it ass...
def read_state(relay_dir, thermostat_dir): global gas_heating_switch, electrical_heating_switch, desired_temperature, current_temperature, electrical_heating_on, gas_heating_on, only_on_cheap_electricty with open(os.path.join(thermostat_dir, 'gas-heating-switch'), 'r') as content_file: gas_heating_switc...
The main task of the code is to monitor and control heating systems (electrical and gas) based on temperature thresholds from thermostat data. It reads input arguments for PID, relay, and thermostat directories, validates their existence, and runs a loop that adjusts heating states (on/off) by comparing current tempera...
def main(): if len(sys.argv) != 4: sys.stderr.write( "heating.py expects three arguments pointing to the PID file, to the relay dir, and to the folder with " "thermostat data.\n") sys.exit(1) global pid_file, relay_dir pid_file = sys.argv[1] relay_dir = sys.argv[...
def precision_at_k(y_true, y_scores, k): ''' Calculates precision for a model at a given k threshold. Code adapted from Rayid Ghani with permission. Inputs: y_true: array of actual scores y_scores: array of predicted scores k (float): a threshold Returns: precision ...
The main task of the code is to evaluate multiple classifiers with varying parameters and thresholds across different data splits, calculating performance metrics like AUC-ROC, precision, recall, and F1 score for each combination. It iterates through training/test splits, classifiers, parameter grids, and thresholds, s...
def classify(data_splits, classifiers, features, target, parameters, models_to_run, thresholds): ''' Iterates through a sequence of models, prediction windows, and parameters in order to build a dataframe of evaluation metrics Inputs: dataframe validation_dates (list of prediction window...
def create_ax(self): """ ###Description: Creates and returns the figure and the plot object 'ax' which will be used to plot all the coordinates ###Returns: The plot object 'ax' """ fig = plt.figure(figsize=(15, 15)) ax = fig.add_subplot(111, projection="ai...
The function `accept_choice` prompts the user to choose between creating a new plot with initialized colors or loading an existing plot from a pickle file. If option 1 is selected, it generates a new figure and axis, initializes colors, and plots. If option 2 is chosen, it loads a pre-saved plot object and continues pl...
def accept_choice(self): """accepts the user's choice and depending on it, either calls the function to create new figure and plot object 'ax' and initialises the colors or use the pickeled object and existing colors.""" ch = input( "1.Plot with all the option\n2.Plot on the existing...
def user_login(self, username, password): self.driver.delete_all_cookies() # log out first if the previous session was not logged out try: self.driver.get('https://www.youtube.com/') WebDriverWait(self.driver, 60).until( EC.element_to_be_clickable((By.XPA...
The main task of the code is to automate video-watching processes across multiple user accounts. It iterates through a list of usernames, logs each in with their password, watches videos based on specified categories and time intervals, interacts with the sidebar, and logs out. The function orchestrates these steps seq...
def run(self, usernames, password, categoryList, length_interval): ''' Main function that orchestrate the whole process of traversing through videos. Iterate through the list of usernames in order and make each one of the accounts to watch videos according to the speficiations. '...
def read_pos_curr(groupBulkRead,packetHandler,id,poscurr): poscurr.id = id bulkRead(groupBulkRead, packetHandler) poscurr.position = extractData(groupBulkRead, id, ADDR_PRESENT_POS, LEN_PRESENT_POS) poscurr.current = extractData(groupBulkRead, id, ADDR_PRESENT_CURRENT, LEN_PRESENT_CURRENT) try: ...
This function reads motor position and current data via ROS, controls motor position with velocity profiles, and publishes real-time sensor data. It maintains a 10Hz loop, adjusts motor position based on thresholds, calculates velocity profiles, and resets to a home position when limits are exceeded.
def pub_posCurr(portHandler, packetHandler, groupBulkRead, groupBulkWrite, id, poscurr): pub = rospy.Publisher('position_current', posCurr, queue_size=10) rospy.init_node('read_posCurr', anonymous=True) #set frequency of 10 Hz ros_freq = 10 rate = rospy.Rate(ros_freq) position = 0 pos_inc = ...
def get_target_commands(my_host): my_host_tags = hosts[my_host] my_target_commands = {} for group_command in sorted(general_commands.keys()): for my_host_tag in my_host_tags.strip().split(): for command_tag in general_commands[group_command]["tags"].split(): if re.search(...
The main task of the code is to collect performance data from network devices, primarily Junos-based systems, by establishing connections, executing predefined commands, parsing XML outputs, and aggregating metrics into data points for storage. It handles connection retries, error logging, device metadata extraction (e...
def collector(**kwargs): for host in kwargs["host_list"]: kpi_tags={} # Check host tag to identify what kind of connections will be used (ej junos / others / etc) if "non_junos_devices" in hosts[host].split(): pass # Reserved for future purposes else: # By de...
def SeqGen(group_id=0, pig_count=50, sample_rate=1.0, series_length=35, data_cache=None, fold_set=None): if data_cache == None: with open("data/data_dump.dat", "rb") as fh: data_cache = pickle.load(fh)["pig_series"] group_mat = GroupSampling(data_cache, group_id=group_id, pig_cou...
The code processes sequence clustering using a distance estimator, with options to generate data, compute distances, perform hierarchical clustering, and visualize results. It supports benchmarking, saving/loading data, and various modes like plotting raw sequences, clustering, or evaluating performance. The core task ...
def Main(): parser = argparse.ArgumentParser(description="PIDENT Clustering") parser.add_argument("-c", default=10, dest="pig_count", type=int, help="Number of clusters (pigs) (integer)") parser.add_argument("-m", default="cluster", dest="mode", choices=["cluster","plot","recalc","benchmark_s","benchmark_f"...
def GetAvgGrowth(pig_data, fold_sets): avg_growth = list() for fold_n in range(len(fold_sets)): fold_coefs = list() train_set = list() for i in range(len(fold_sets)): if i != fold_n: train_set += fold_sets[i] for animal_id in train_set: pig...
The code generates a structured dataset for time series forecasting by processing pig growth data, applying transformations, and organizing data into folds/groups. It loads precomputed indices, samples trajectories, matches raw data, and formats outputs based on parameters like format_mode, sample_rate, and series_leng...
def GenerateDataset(format_mode, tj_model, series_count=100, pig_count=10, sample_rate=1.0, series_length=35, fold_count=3, min_pigs=0.5, ff_step_size=1.0, ff_frag_size=7, ff_horizon=14): with open("data/data_dump.dat", "rb") as fh: pig_data = pickle.load(fh)["pig_s...
def initialize_plot(formatting): """ Create Bokeh figure to which glyphs/elements can be added. :param (dict) formatting: see DEFAULTFORMAT from params.py :return: Bokeh figure object """ bkplot = plotting.figure(title=formatting['title'], background_fill_color=formatting[...
The function generates a choropleth map using geographic data (county/state) by merging input data (DataFrame or CSV) with shapefiles, handling missing values, and applying specified color schemes. It returns a Bokeh plot object or saves it as HTML, with customizable formatting and output options.
def plot(file_or_df, geoid_var, geoid_type, y_var, y_type, geolvl='county', geolabel='name', formatting=None, output=False, dropna=True): """Short summary. :param (str/pd.DataFrame) file_or_df: csv filepath or pandas/geopandas DataFrame with geoid_var :param (str) geoid_var: name of column contain...
def _bucket_from_argument( bucket: Optional[BucketLikeType] ) -> Bucket: if bucket is None: return _default_bucket() if isinstance(bucket, str): return _s3().Bucket(bucket) else: # Assume it's a bucket object already. return bucket def _s3() -> S3ServiceResource: s3 = boto3....
This function writes a string or bytes to an S3 object with the specified key. It encodes strings to bytes if needed, retrieves the target bucket from configuration, and uploads the content using AWS S3's put_object method.
def write_string_to_object( object_name: str, text: Union[str, bytes], bucket: Optional[BucketLikeType] = None ) -> None: ''' Write a string into an object in S3. ''' bucket = _bucket_from_argument(bucket) if isinstance(text, str): text = text.encode() bucket = _s3().Bucket(c...
def calculate_segmentation_metrics(target_mask_modality, complete_predicted_masks, complete_test_directory, directory_of_complete_targets): print("Calculate segmentation metrics ...\n\n") list_of_ious = [] list_of_precisions = [] list_of_recalls = [] list_of_f1_sco...
The code evaluates segmentation metrics (IoU, Hausdorff Distance) and front delineation errors for predicted masks (zones/fronts) against ground truth data. It performs post-processing on zone masks, generates evaluation results in JSON, and creates visualizations comparing predictions with SAR images and bounding boxe...
def main(complete_test_directory, directory_of_complete_targets_zones, directory_of_complete_targets_fronts, directory_of_sar_images): # ############################################################################################### # CALCULATE SEGMENTATION METRICS (IoU & Hausdorff Distance) # ####...
def replaceIff(cnf_curr) : try: if isinstance(cnf_curr, list) : sym = cnf_curr[0].lower() if sym == "not" : child = replaceImplies(cnf_curr[1]) cnf_next = ["not", child] else : lhs = replaceImplies(cnf_curr[1]) ...
The code processes logical expressions from an input file, applying transformation steps (replacing iff/imply, moving negations, De Morgan's laws, and removing duplicates) to convert them into a standardized form. It writes the resulting expressions to "sentences_CNF.txt", handling potential errors gracefully.
def main(): try: file = open(sys.argv[2]) outputFile = open("sentences_CNF.txt", "w+") num = int(file.readline()) + 1 for i in range (1, num): inp = eval(file.readline()) step1 = replaceIff(inp) step2 = replaceImplies(step1) step3 = m...
def create_dir_if_not_exists(directory): if not os.path.exists(directory): os.makedirs(directory) def execute_in_simulo(experiment, experiment_name, base_directory, experiment_base_directory, default_socket_creation_time...
The code launches and manages simulation experiments using a configuration JSON file. It reads parameters, sets up directories, executes each experiment, generates Gantt charts if specified, compares results to OAR, tests noise impact, and aggregates outputs if configured. It tracks success/failure status and provides ...
def launch_experiment(config_json_filename): json_file = open(config_json_filename, 'r') json_data = json.load(json_file, object_pairs_hook=OrderedDict) output_directory = str(json_data['output_directory']) create_dir_if_not_exists(output_directory) default_timeout = None if 'default_timeout' ...
def Set_Value(self,value): self.value = value def Get_Name(self): return self.name def Allow_Presynaptic_Neuron_To_Influence_Me(self, syn_weight: float, pre_syn_value: float): transform = pre_syn_value * syn_weight self.Add_To_Value(transform) def Threshold(self): self.value =...
This function updates a neuron's value by aggregating weighted inputs from presynaptic neurons, then applies a thresholding operation to constrain the value within the range [-1, 1]. It initializes the neuron to 0.0, iterates over synapses targeting this neuron, retrieves synaptic weights and presynaptic values, and ac...
def Update_Hidden_Or_Motor_Neuron(self, neurons: dict, synapses: dict): # apparently we need to initialize this self.Set_Value(0.0) for syn in synapses.keys(): if syn[1] == self.Get_Name(): # this synapse goes to this neuron. Get synapse weight and the value of the pr...
def sendCommand(com): writeLine(com) readAll() def waitForIdle(): while True: time.sleep(0.050) if getState()[1:5] == "Idle": return def probe(): sendCommand("G38.2 F20 Z-30") waitForIdle() def getPosition(): # MPos:5.000,0.000,0.000 return getState().split("|")[1...
The code scans a grid area by moving a probe over a specified region, collecting position data at each point. It calculates coordinates based on input parameters, sends G-code commands to position the probe, waits for idle status, probes the surface, records the position, and repeats across a grid defined by num_x and ...
def scanRoutine(x, w, y, h, num_x = 15, num_y = 10): sendCommand("G0 Z1") sendCommand("G90") for x_i in range(0, num_x): print('[') for y_i in range(0, num_y): cur_x = x + w / (num_x - 1) * x_i cur_y = y + h / (num_y - 1) * y_i sendCommand(f'X{cur_x:.3f} Y...
def load_xml(): data_f = 'multilingual-all-words.en.xml' key_f = 'wordnet.en.key' dev_instances, test_instances = ld.load_instances(data_f) dev_key, test_key = ld.load_key(key_f) dev_instances = {k:v for (k,v) in dev_instances.items() if k in dev_key} test_instances = {k:v for (k,v) in test...
The main task of the code is to load development and test datasets from XML, then evaluate them using two methods: `run_first_common_sense` and `run_lesk`, applying both to the development and test sets with their respective keys for comparative analysis or model evaluation.
def main(): dev_instances, dev_key, test_instances, test_key = load_xml() run_first_common_sense(dev_instances, dev_key) run_first_common_sense(test_instances, test_key) run_lesk(dev_instances, dev_key) run_lesk(test_instances, test_key)
def get_start_date(): # Create a DynamoDB client dynamodb = boto3.client('dynamodb') # Retrieve the item from table try: response = dynamodb.get_item( TableName='PROJECT_NAME-lambda-date', Key={ 'env': {'S': 'prod'} } ) except botocore....
The code's main task is to check if the current date is later than a start date, and if so, update compacted logs with data between those dates. If not, it raises an error. It then updates the last processed date and returns None. This is likely part of a data synchronization or log management workflow.
def lambda_handler(event, context): end_date = date.today() if (get_start_date() < end_date): update_compacted_logs(get_start_date(), end_date) else: raise ValueError("Data is already updated") update_date(str(end_date)) return None
def parse_date(isodate): 'Returns the y-axis coordinate for an isodate (YYYY-MM-DD).' parsed_date = dateutil.parser.parse(isodate) days_alive = (top_date - bottom_date).days # Total days alive day_count = (top_date - parsed_date).days # Number of days into life at which event occurred scale = (opti...
The function draws a vertical rectangle on a timeline to represent the duration of a residence stay, using start and end dates to determine height. It applies CSS styling, adds a label if provided, and validates date order. Optional parameters allow customization.
def residence(css_color, label, start_isodate, end_isodate, **kwargs): '''Draws a box of y-axis length = duration of stay at a residence. **kwargs: optional css styling.''' end_isodate = end_isodate or top_isodate # Input Quality assert start_isodate < end_isodate, (start_isodate, end_isodate) ...
def parse_date(isodate): 'Returns the y-axis coordinate for an isodate (YYYY-MM-DD).' parsed_date = dateutil.parser.parse(isodate) days_alive = (top_date - bottom_date).days # Total days alive day_count = (top_date - parsed_date).days # Number of days into life at which event occurred scale = (opti...
This function draws a weekday event as a styled rectangle on a timeline, using start/end dates/hours to define coordinates. It applies CSS styling, validates input, and adds a centered label inside the rectangle, handling date parsing and coordinate conversion for accurate visualization.
def weekday(css_color, label, start_isodate, end_isodate, start_hour, end_hour, **kwargs): '''Draws a weekday event from (start_hour, start_isodate (YYYY-MM-DD)) to (end_hour, end_isodate (YYYY-MM-DD)). **kwargs: optional css styling.''' end_isodate = end_isodate or top_isodate # Input Quality ass...
def width_from_hours(num_days, num_hours): 'Given total num_hours spent over num_days, returns the width in pixels' # Input Quality assert num_hours <= (num_days*16) options.weekday_hour_width = weekday_hour(10) - weekday_hour(9) return (num_hours/260) * options.weekday_hour_width / (num_days/365...
This function generates a visual representation of a roommate's sleeping period between two dates, drawing a styled rectangle with a label in a specified slot (0-3). It calculates coordinates based on dates, applies CSS styling, and renders the pillow-cuddle friend's timeline segment.
def sleepmate(css_color, label, start_isodate, end_isodate, slot=0, **kwargs): '''Draws pillow cuddle-friends you had from start_isodate (YYYY-MM-DD) to end_isodate (YYYY-MM-DD). There are four available slots for 4 home-mates. You can indicate which one you want occupied by setting slot to 0-3. **kwargs: o...
def parse_date(isodate): 'Returns the y-axis coordinate for an isodate (YYYY-MM-DD).' parsed_date = dateutil.parser.parse(isodate) days_alive = (top_date - bottom_date).days # Total days alive day_count = (top_date - parsed_date).days # Number of days into life at which event occurred scale = (opti...
This function draws a weekend event visual element (rectangle with label) between specified start and end dates. The width is proportional to hours_per_week invested, with slot determining horizontal positioning. It validates input dates, calculates coordinates using parsed dates and hour-to-width conversion, applies C...
def weekend(css_color, label, start_isodate, end_isodate, hours_per_week, slot=0, **kwargs): '''Draws a weekend event from start_isodate (YYYY-MM-DD) to end_isodate (YYYY-MM-DD). Width of the drawing is proportional to the hours_per_week invested. **kwargs: optional css styling.''' end_isodate = end_is...
def residence(css_color, label, start_isodate, end_isodate, **kwargs): '''Draws a box of y-axis length = duration of stay at a residence. **kwargs: optional css styling.''' end_isodate = end_isodate or top_isodate # Input Quality assert start_isodate < end_isodate, (start_isodate, end_isodate) ...
This function processes memory data by assigning colors based on type and label, then routes it to specific drawer functions (e.g., residence, occurrence, sleepmate) for visualization. It stores memory details in a list and applies conditional logic to determine the appropriate rendering method, handling different memo...
def generic(type, intensity, label, start_isodate, end_isodate=None, weekday_start_hour=None, weekday_end_hour=None, hours=None, **kwargs): 'Processes all of the memories and sends them to the appropriate drawer' href = kwargs['href'] if 'href' in kwargs else '' title = kwargs['title'] if 'title' in kwarg...
def generic(type, intensity, label, start_isodate, end_isodate=None, weekday_start_hour=None, weekday_end_hour=None, hours=None, **kwargs): 'Processes all of the memories and sends them to the appropriate drawer' href = kwargs['href'] if 'href' in kwargs else '' title = kwargs['title'] if 'title' in kwarg...
The main task of the code is to generate a histomap (timeline visualization) from a specified start date to an end date, configuring an SVG grid with axes, date markers, time segments (weekdays/weekends), age intervals, event lines, and optional legends. It calculates grid dimensions, sets viewport bounds, and draws la...
def timespan(start_isodate, end_isodate, **kwargs): 'Draws the histomap grid from start_isodate (YYYY-MM-DD) to end_isodate (YYYY-MM-DD).' # Set options timeline_options.update(**kwargs) for k, v in kwargs.items(): generic('option', 0, k, v) generic('timespan', 0, '', start_isodate, end_is...
def playing_round_setup(self): self.is_player_turn = True self.is_second_hand_turn = True self.dealer.dealer_hand_value = 0 self.split_selection = 0 self.player_bust = False self.first_selection = True def init_card_deal(self): for card in range(2): ...
This code manages a single round of a Blackjack game, handling card dealing, player wagering, player and dealer actions, split decisions, and hand comparisons. It ensures the round progresses through setup, player turn, dealer turn, and result evaluation, terminating the round once all actions are resolved.
def playing_round(self): self.is_playing_round = True while self.is_playing_round: self.playing_round_setup() print(f"Welcome, {self.player.name}, to round {self.round_num} of Blackjack.") self.player.place_wager() print("\nNow that all wagers have been ...
def classifier_config(classifier): if classifier == 'Random Forest Model': ml_flow = RandomForestClassifier(bootstrap=True, min_samples_leaf=2, n_estimators=200, max_features='sqrt', min_samples_split=10, max_depth=50) elif classifier == 'SVM': ml_flow = SVC(kernel='linear', C=0.001, ga...
The code processes network flow data for machine learning tasks by cleaning and aggregating flow statistics, then performs classification, feature selection, hyperparameter tuning, or testing based on user-specified functionality. It reads input data, converts features to numeric values, and applies chosen ML functions...
def main(): os.chdir(os.getcwd() + '/App/') classifier = sys.argv[1] functionality = sys.argv[2] with open('Neptune/stats_training/FlowStats_target_cleaned.txt', 'w') as flow_target_cleaned: flow_target_cleaned.write("target\n") ml_flow = classifier_config(classifier) # Clean training...
def load_context(): '''loads the context file into a dict''' try: context_file = '_context.json' with open(context_file, 'r') as fin: context = json.load(fin) return context except: raise Exception('unable to parse _context.json from work directory') def get_aoi(a...
The main task of the code is to process precision orbits (poeorbs) intersecting a specified Area of Interest (AOI), either for all tracks or specific input tracks. It retrieves configuration parameters, checks for available tracks, and submits jobs to query orbit data using a defined queue and version. The process appl...
def main(): ctx = load_context() queue = ctx.get('enumerator_queue', 'standard_product-s1gunw-acq_enumerator') enumeration_job_version = ctx.get('enumeration_job_version', 'master') aoi = get_aoi(ctx.get('aoi_name')) tracks = parse_tracks(ctx, aoi) #parse the tracks from context. If none are input, ...
def _make_bam(self, strand): """ Extract sequences from fast5 files and map them to the reference sequence Args: strand: either template or complement Returns: AlignmentFile object of the generated bam-Alignment """ # with NamedTemporaryFile() a...
The code constructs a statistical model for a given DNA strand (template or complement) by processing aligned reads, identifying correct kmers, and serializing the model as a pickle file named with the strand identifier.
def make_model(self, strand): """ Runner function: make the model for either template or complement strand. Pickles the model to {basename}.strand.pickle. Args: strand: Returns: """ self.logger.info("Making model for {0}-strand".format(strand)) ...
def painter_set_basic_painter(self): self.game_painter.setPen(qt.QPen(qt.QColor(0, 0, 0), 1, qtcore.Qt.SolidLine)) # self.game_painter.setBrush(qtcore.Qt.NoBrush) self.game_painter.setBrush(qt.QBrush(qt.QColor(254, 254, 254), qtcore.Qt.Dense4Pattern)) pass def draw_food(self): se...
This code handles the painting of a game's visual elements during the paint event. It initializes a painter, draws the game boundary, renders food and special food items, checks if the snake has eaten food, draws the snake, and verifies if the snake has died. The primary task is to visually represent the game state, in...
def paintEvent(self, event): self.game_painter.begin(self) self.painter_set_basic_painter() self.game_painter.drawRect(0, 0, self.window_min_width - 1, self.window_min_height - 1) self.draw_food() self.draw_special_food() # -- Check if snake ate the food here self...
def regionAndTourn(soup): ##region and tournament regionAndTournament = soup.find('div', class_ = 'col-12 col-sm-7').text.split(' ') region,tournament = tourmAndregion(regionAndTournament) if('(WR)' in tournament): tournament = tournament.replace('(WR)','') tournament = tournament[:-1] ...
The function scrapes match and game data from web links, processes HTML content to extract match details, generates SQL queries to insert data into a database, and appends game data to a DataFrame. It skips duplicates, handles different page types (with/without summaries), and iterates through game links to scrape indi...
def scrapMatchs(links, num_in_tourn, df,tournID): num_of_match_in_tournament = 1; number_of_matches_added = 0; #for each link in the list, scrape the page building a match for link in links: if('page-preview' in link): continue URL = "https://gol.gg"+link; source = re...
def extract_frames(args): dirs = get_immediate_subdirectories(args.out_dir) for d in dirs: # video path is created in download.py root_path = os.path.join(args.out_dir, d) video_path = os.path.join(root_path, 'video.mp4') # frame rate same as video cmds = ['ffmpe...
The code's main task is to extract multimodal features from audio-visual data. It processes video frames, audio waveforms, and spectrograms, aligns audio with text via forced alignment, and uses OpenFace for facial feature extraction, preparing data for tasks like speech recognition, emotion analysis, or multimodal mod...
def extract_features(args): extract_frames(args) extract_waveforms(args) extract_spectrograms(args) force_align(args) run_openface(args)
def read_notebook_files(nb: Path) -> dict[NotebookLanguage, Path]: files: dict[NotebookLanguage, Path] = {} for lang, file_name in NB_FILE_NAMES.items(): path = nb / file_name if path.exists(): files[lang] = path return files def read_notebook_sources( files: dict[NotebookLa...
The function reads a notebook's metadata and files, parses its JSON specification, processes source files, and constructs a structured `Notebook` object containing block sources, blocks, properties, tags, and other attributes derived from the input path and metadata.
def read_notebook(wf: Path, notebook_meta: dict) -> Notebook: path = wf / notebook_meta["name"] notebook_spec: dict = json.loads((path / "Notebook.json").read_text()) files = read_notebook_files(path) sources = read_notebook_sources(files) block_sources = read_block_sources_per_id(sources) retur...
def read_notebooks(wf: Path, notebooks_meta: list[dict]) -> list[Notebook]: return [read_notebook(wf, nb_meta) for nb_meta in notebooks_meta] def read_resource_properties(resource_spec: dict) -> dict: custom_props: list[dict] = resource_spec.get("locals", []) return {prop["id"]: prop["code"] for prop in cus...
The function reads a workfolder's metadata and structure from a JSON file, constructs a Workfolder object with attributes like ID, name, description, notebooks, and properties. It filters notebook pages from the JSON spec, loads notebook details, and extracts resource properties/tags, returning a structured Workfolder ...
def read_workfolder(wb: Path, workfolder_meta: dict) -> Workfolder: path = wb / workfolder_meta["name"] workfolder_spec: dict = json.loads((path / "Workfolder.json").read_text()) notebooks_meta = [p for p in workfolder_spec.get("pages", []) if p.get("type") == "notebook"] return Workfolder( id=w...
def find_accid(): """ Finds the ID of an account for the Salt, Donations, and VoteDonate tables """ accid = 0 # Prepare SELECT statement prep_select = "SELECT accId FROM accounts WHERE uname = %s" # A tuple should always be used for binding placeholders (%s) cursor.execute( pre...
(The main task of the code is to securely store donation data in the "Donations" table by encrypting credit card or Bitcoin information using a salt, then inserting the encrypted data into the table based on the payment method (credit card or Bitcoin). It also calls the `insert_votedonate()` function to record the dona...
def insert_donation(): """ Stores the donation that was placed in the Donations table and uses a function to store donations in the VoteDonate table """ global errctr accid = find_accid() # gets an ID try: # Converts the string value that is returned in find_salt() back to bytes ...
def actions_to_areas(self, full_state): full_areas = [[(None, None) for t in range(self.HOR)]for s in range(self.num_of_swarms)] latest = [(0, 0) for s in range(self.num_of_swarms)] for swarm in range(self.num_of_swarms): for time in range(self.HOR): full_areas[swarm]...
The code generates probability matrices for each swarm, tracking the likelihood of having a certain number of drones and rewards over time. It initializes matrices with zeros, sets initial states, and updates them based on actions and unvisited areas, stopping when no further actions are possible or when revisiting are...
def get_matrices(self, full_state): """ We create an empty (all zeros) matrix of probabilities. Each number in it represents the probability of the swarm having x drones while gaining y rewards. For our every action we update the matrix unless there are no more actions in which case we stop or i...
def generateArrivalTime(self): return self.clock + (-np.log(1-(np.random.uniform(low=0.0,high=1.0))) * 3) def addCustomer(self): self.clock = self.idleCustomer.getArrivalTime() self.idleCustomer.setInQueueArrive(self.customerQueue.getSize()) i...
This code advances simulation time by managing customer arrival and teller availability. It checks if an idle customer exists, generates arrival times if needed, and compares the customer's arrival time with tellers' departure times. If the customer arrives before both tellers finish, they are added to service. Otherwi...
def advanceTime(self): if self.idleCustomer == None: arrivalTime = self.generateArrivalTime() self.idleCustomer = Customer(arrivalTime) if self.idleCustomer.getArrivalTime() < self.teller1.getDepartureTime() and self.idleCustomer.getArrivalTime() < self.teller2.getDepartureTime...
def parseArgs(argv): """ Function that parses the arguments sent from the command line and returns the behavioral variables to the caller. Parameters ---------- - argv : str Arguments sent through the command line Returns ------- - waitTime : int ...
The code initializes a bulk downloader for the SureDone API, parsing command-line arguments (wait time, config path, delimiter, output settings). It validates Python version ≥3.5, loads API credentials from a config file, and invokes a GET request to export data. If successful, it downloads the exported file to the spe...
def main(argv): localFrame = inspect.currentframe() # Parse arguments # When verbose argument is added, change the verbose of the logger based on the argument as well waitTime, configPath, delimiter, outputFilePath, preserveOldFiles, verbose, dataFields, \ outputFileExtension = parseArgs(argv) ...
def try_parse_int(value): try: return int(value), True except ValueError: return value, False def auto_create_graph(self, width, height) -> EnvironmentGraph: elevations = [] for i in range(width): row = [] for j in range(height): row.append...
The main task of the code is to provide a menu-driven interface for creating/managing environments and running pathfinding algorithms. It allows users to create/import/export environments, select algorithms, input start/end coordinates, execute path calculations, and visualize results with metrics like distance, energy...
def run_tool(self): supported_alg_names = self.supported_algorithms.keys() menu = NavMenu(supported_alg_names) choice = "" while choice.lower() != "exit": menu.reset_menu() choice = input("Please choose a menu option by typing in its label: ") ...
def display(board): """ Display current board in debug purposes """ print("-----") for row in board: for cell in row: print(cell, "\t", end="") print() print("-----") def player(board): """ Returns player who has the next turn on a board. """ x_nu...
The main task of the code is to test a Tic-Tac-Toe minimax algorithm on a predefined board state. It initializes a 3x3 game board, displays it, identifies the current player, and executes the minimax function to determine the optimal move. The result of the algorithm's calculation is then printed, demonstrating its dec...
def main(): # A simple test case board = [[X, EMPTY, EMPTY], [EMPTY, O, EMPTY], [X, EMPTY, EMPTY]] print("initial") display(board) print("Current move: ", player(board)) result = minimax(board) print("result of calculation") print(result)
def _matrix_abscisse_to_observation_abscisse(self, matrix_abscisse): """ Convert a matrix abscisse to an observation abscisse """ return matrix_abscisse/self.length*10. def _matrix_ordonnee_to_observation_ordonnee(self, matrix_ordonnee): """ Convert a matrix ordonnee to an observation ordonnee "...
This code initializes a reinforcement learning environment with customizable length, width, goal, and initial states. It sets up observation/action spaces for 3D navigation, calculates initial reward based on distance to the goal, and tracks environment state, reward history, and step limits. The agent's position, goal...
def __init__(self, length, width, goal=[None, None, None], initial=[None, None, None], max_steps=100): self.length = length self.width = width self.counter = 0 self.info = {} if goal[0] is None: self.goal = { "abscisse": self._matrix_abscisse_to_observ...
def print_mr_home(): home = os.getenv("VMR_HOME", DEFAULT_VMR_HOME) arr = os.listdir(f"{home}") logger.info(arr) def prepare_vmr_home(): home = os.getenv("VMR_HOME", DEFAULT_VMR_HOME) os.makedirs(home, exist_ok=True) def exists_cluster(): _, peers = get_info() return peers is not None def ch...
This script manages the metadata repository (VMR) process, ensuring it runs in either standalone or cluster mode. It checks for existing clusters, handles Raft peer additions/removals, restarts the VMR if it fails, and logs status. The loop continuously monitors the VMR's liveness, gracefully restarting it with configu...
def main(): logger.info("start") print_mr_home() limits.set_limits() prepare_vmr_home() standalone = False if not exists_cluster(): if check_standalone(): standalone = True logger.info("it starts standalone") elif exists_wal(get_raft_dir()): ...
def num_cols(self): #return the number of columns in the Wave #hint: return the len() of the first list return len(self.Wave[0]) def num_rows(self): #return the number of rows in the Wave #return the len() of the Wave return len(self.Wave) def draw_cell(self, image, pos)...
The main task of the code is to draw all cells of a grid onto a given image. It iterates through each cell using nested loops over columns (x) and rows (y), then calls the `draw_cell` method to render each cell at position (x, y) onto the image. This systematically populates the entire grid structure onto the provided ...
def draw(self, image): # draw the entire Grid onto the given image # make a double nested loop then # use draw_cell to draw a single cel for x in range(self.num_cols()): for y in range(self.num_rows()): self.draw_cell(image,(x,y))
def _parse_trackid(response): regex = r'a=control:(.*)/(?P<trackid>\w+=\d+)' match = re.search(regex, response.body, re.S) return match.group('trackid') def describe(self): response = self._request( method='describe', url=self.safe_url) if response.statu...
The main task of the code is to initialize an RTSP stream setup by parsing a track ID, sending a SETUP request with RTP/UDP transport parameters, and validating the server's response. It configures unicast RTP streaming using the provided `rtp_port`, raises an error if the request fails, and returns the response otherw...
def setup(self, rtp_port): trackid = self._parse_trackid(self.describe()) response = self._request( method='setup', url=f'{self.url}/{trackid}', headers={ 'Transport': f'RTP/AVP/UDP;unicast;client_port={rtp_port}-{rtp_port}' }) if...
def read_load_profiles(path_to_raw_load, entsoe_priority): """Reads national load data and handles outliers.""" data = pd.read_csv(path_to_raw_load, parse_dates=["utc_timestamp"]) data = data[(data["variable"] == "load")] data = select_statistics_by_source_priority(data, entsoe_priority) return data...
The function processes national electricity load data for a specified year by reading raw data, filtering by country, selecting the target year and filling gaps, handling outliers, and saving the processed time series to a CSV file. Input parameters include data paths, country list, year, gap tolerance, and outlier thr...
def national_load( path_to_raw_load, entsoe_priority, year, acceptable_gap_hours, outlier_thresholds, path_to_output, countries ): """Extracts national load time series for all countries in a specified year.""" load = read_load_profiles(path_to_raw_load, entsoe_priority) load = filter_national(load,...
def clear_screen(self): for widget in self.root.winfo_children(): widget.destroy() def get_db_connection(): return s.connect(host="localhost", user='root', passwd="VSE@2022", database=database_name) def cat_display(self, category): self.current_category = category self.current_qu...
The code initializes a quiz interface by fetching non-score tables from a database, displaying each as a selectable button. It clears the screen, connects to the database, retrieves table names excluding those ending with '_scores', creates buttons for each table, positions them vertically, and closes the connection. E...
def start_quiz(self): self.clear_screen() conn = get_db_connection() cursor = conn.cursor() cursor.execute("SHOW TABLES WHERE `Tables_in_quiz` NOT LIKE '%_scores'") tables = cursor.fetchall() a = 0 for table in tables: table_name = table[0] ...
def get(square): piece = board[SQUARES[square]] return {'type': piece['type'], 'color': piece['color']} if (piece != None) else None def update_setup(fen): global history if len(history) > 0: return if fen != DEFAULT_POSITION: header['SetUp'] = '1' header['FEN'] = fen el...
This function removes a chess piece from the board at the specified square, updates the game state by clearing the piece's position, and handles special logic for kings (marking their status as empty if removed). It then refreshes the game setup using a FEN string and returns the removed piece.
def remove(square): global board global kings piece = get(square) board[SQUARES[square]] = None if (piece!= None and piece['type'] == KING): kings[piece['color']] = EMPTY update_setup(generate_fen()) return piece
def put(piece, square): global board if (not('type' in piece and 'color' in piece)): return False if (SYMBOLS.find(str(piece['type']).lower()) == -1): return False if (not(square in SQUARES)): return False sq = SQUARES[square] if (piece['type'] == KING and not( king...
This code parses a FEN string to initialize a chess game state, including board setup, turn, castling rights, en passant square, and move counters. It processes each token from the FEN, maps pieces to their positions, updates global variables for game metadata, and triggers a setup update.
def load(fen_param): global turn tokens = fen_param.split(" ") square = 0 for i, s in enumerate(tokens): for j in range(len(s)): piece = s[j] if(piece == '/'): square += 8 elif piece.isdigit(): square+= int(piece) ...
def pickSeeds(self, n): maxArea = -1 * sys.float_info.max s = None t = None for e1 in n.entries: for e2 in n.entries: if e1 != e2: r = MBR(e1, e2) a = self.getArea(r) - self.getArea(e1) - self.getArea(e2) ...
The code splits a node into two child nodes by selecting seeds, creating new nodes, redistributing entries, updating the parent node, and tightening the structure to maintain tree consistency.
def split(self, n): s1, s2 = self.pickSeeds(n) n1 = Node(s1.x, s1.y, s1.xx, s1.yy, self.nNodes + 1, s1.feat, s1.name) n2 = Node(s2.x, s2.y, s2.xx, s2.yy, self.nNodes + 2, s2.feat, s2.name) self.nNodes += 2 n1.addEntry(s1) n2.addEntry(s2) n.entries.remove(s1) ...
def tighten(self, n): x = sys.float_info.max y = sys.float_info.max xx = sys.float_info.min yy = sys.float_info.min n.sig = 0 for e in n.entries: if e.x < x: x = e.x if e.xx > xx: xx = e.xx if e.y < y: y = e....
The main task of the code is to adjust a tree structure by recursively splitting nodes when their entry count exceeds a maximum threshold (self.mMax) and propagating adjustments upward to maintain tree balance. It first tightens the node, splits it if necessary, and recursively adjusts the parent node to ensure structu...
def adjustTree(self, n): self.tighten(n) if len(n.entries) > self.mMax: np = self.split(n) self.adjustTree(np) elif n.parent is not None: self.adjustTree(n.parent)
def chooseLeaf(self, n, e): if n.isLeaf: return n mininc = sys.float_info.max nnext = None for c in n.entries: inc = self.getRequiredExpansion(c, e) if inc < mininc: mininc = inc nnext = c return self.chooseLeaf(nnext, e) ...
This code inserts an element into a tree structure, creating a new node if the tree is empty. It selects a leaf node, adds the element, splits the node if it exceeds capacity, and adjusts the tree structure to maintain balance and integrity.
def insert(self, e): if self.root is None: #n = Node(p.x, p.y, p.x, p.y, self.nNodes + 1) n = Node(e.x, e.y, e.xx, e.yy, self.nNodes + 1, e.feat, e.name) self.root = n self.nNodes += 1 else: n = self.root #e = Entry(p.x, p.y, self.nPoi...
def init_population(max_len: int, pop_size: int) -> list: pop: set = set() while len(pop) < pop_size: prog = rand_prog(max_len) pop.add(prog) return list(pop) def fill_selector(pop: list, fe: FitnessEvaluator) -> list: selector: list = [] pop_score = indv_score = 0 #find the o...
The code implements an evolutionary algorithm to generate a program string (up to max_len) that, when interpreted, exactly matches a target array. It iteratively evolves a population of candidate programs using selection, crossover, and fitness evaluation via fe.evaluate(), terminating when a program achieves a fitness...
def create_program(fe: FitnessEvaluator, max_len: int) -> str: """ Return a program string no longer than max_len that, when interpreted, populates a memory array that exactly matches a target array. Use fe.evaluate(program) to get a program's fitness score (zero is best). """ selector: list = ...
def domain(idx: int, board: list, nrows: int, ncols: int) -> list: all_adj: set = adjacent_spots(idx, board, nrows, ncols) rel_unexplored: set = set() dx: list = [] discovered_bombs: int = 0 for spot in all_adj: if board[spot] == -2: rel_unexplored.add(spot) if board[spo...
The function `sweep_mines` solves a minefield by iteratively exploring safe indices using a `BoardManager`, deducing bomb locations through logical inference, and updating the board until all safe cells are revealed. It avoids unsafe moves by propagating clues, identifying guaranteed safe moves, and marking bombs. The ...
def sweep_mines(bm: BoardManager) -> List[List[int]]: """ Given a BoardManager (bm) instance, return a solved board (represented as a 2D list) by repeatedly calling bm.move(index) until all safe indices have been explored. If at any time a move is attempted on a non-safe index, the BoardManager will...