dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def check_crash(): if pyautogui.locateOnScreen('crash.png', confidence=0.8, region=(0,0,700,1100)): x,y = pyautogui.locateCenterOnScreen('crash.png', confidence=0.8, region=(0,0,700,1100)) pyautogui.click(x,y) time.sleep(15) log_out_if_logged_in() def log_out_if_logged_in(): chec...
The code performs a series of actions: checks for crashes, logs out if logged in, retrieves historical data, and simulates a mouse drag from (300,600) to (300,800) over 0.6 seconds to mimic scrolling up. Its main task is to manage system state, ensure user logout, fetch historical information, and execute a controlled ...
def scroll_up(): check_crash() log_out_if_logged_in() historical() mouse.drag(300, 600, 300, 800, absolute=True, duration=0.6)
def check_for_pop_ups(): for y in range (2): check_crash() check_restartGame() check_browser() check_for_csBACK() check_for_Discord() check_googleStore() check_for_zvz() check_for_daily() check_for_rift() checkLogIn() check_for...
The function checks if the game is on the map by searching for 'Base.png' within a specific screen region using pyautogui. If the image isn't detected (with 90% confidence), it triggers a message, simulates a click to switch contexts, logs a status, and pauses for 4 seconds to allow the switch.
def check_if_on_map(): check_for_pop_ups() if pyautogui.locateOnScreen('Base.png', confidence=0.9, region=(0,0,700,1100)) == None: cs_message() click(81,969) print("not on map, switching...") time.sleep(4)
def check_for_pop_ups(): for y in range (2): check_crash() check_restartGame() check_browser() check_for_csBACK() check_for_Discord() check_googleStore() check_for_zvz() check_for_daily() check_for_rift() checkLogIn() check_for...
The code's main task is to check for pop-ups, locate a specific image ('Base.png') on the screen, and if detected, trigger a message, click a coordinate, and pause to switch contexts, likely automating navigation in a game or application.
def bring_on_base_screen(): check_for_pop_ups() if pyautogui.locateOnScreen('Base.png', confidence=0.9, region=(0,0,700,1100)) != None: cs_message() click(81,969) print("on map, switching...") time.sleep(4)
def cs_message(): if pyautogui.locateOnScreen('cs_message.png', confidence=0.8, region=(0,0,700,1100)) != None: x, y = pyautogui.locateCenterOnScreen('cs_message.png', confidence=0.7, region=(0,0,700,1100)) time.sleep(1) pyautogui.click(x,y) def historical(): if pyautogui.locateOnScreen(...
The main task of the code is to automate logging into a specific farm account by locating a screen image ('FarmX/name.png') using image recognition, waiting for it to appear, clicking it to log in, and performing additional actions like scrolling, checking pop-ups, and waiting for confirmation. The loop ensures the acc...
def log_into_account(farm_number): cs_message() historical() cs_message() logged_in = False timera = 0 while logged_in == False: while pyautogui.locateOnScreen('Farm' + farm_number + '/name.png', confidence=0.7, region=(0,0,700,1100)) == None: if timera < 14: ...
def search_zip_contents(filepath, queries): # opening the zip may fail, or accessing a file in the zip may fail try: # open zip file with zipfile.ZipFile(filepath) as archive: # enumerate contents for name in archive.namelist(): # only consider .txt files if not name.lower().endswith('.txt'): c...
This function recursively searches for text files (.txt, .htm, etc.) and ZIP archives in a given directory, checking each ZIP file's contents and directly searching text files for specified queries.
def search_all_zips(dirpath, queries): # get a filenames in a dir filelist = [name for name in os.listdir(dirpath)] # sort for readability filelist.sort() # enumerate all files in a directory for filename in filelist: # construct the path filepath = os.path.join(dirpath, filename) # check for directory if...
def bsp_list(dirpath): bsplist = list() # process all files in the directory for filename in os.listdir(dirpath): # skip files with the wrong extension if not filename.endswith('.bsp'): continue filepath = os.path.join(dirpath, filename) # open bsp file and load e...
This function gathers BSP file details from a mod directory and pak files, removes duplicates, filters maps, sorts by name, and prints them with optional author information, using a specified separator.
def print_bsp_list(mod_path, sep='\t', report_author=True): bsplist = list() # load bsp files from maps/ directory mapspath = os.path.join(mod_path, 'maps/') if os.path.exists(mapspath): # get the list of bsp details bsplist += bsp_list(mapspath) # load bsp details from pak files ...
def deal(): players = {} players["dealer"] = draw_cards(2) players["player"] = draw_cards(2) return players def display_cards(players, reveal): dealer_displays = " Dealer has :" player_displays = " Player has :" if (reveal): for card in players["dealer"]: dealer_displays ...
The code simulates a Blackjack game where a player and dealer take turns drawing cards. The player chooses to 'Hit' or 'Stand', with automated checks for busting and adjusting aces (11→1). The dealer follows rules to draw cards until busting or standing. The game concludes by evaluating if the player wins based on deal...
def main(): players = deal() display_cards(players, False) player_choice = "" while True: while player_choice.lower() != ('h') and player_choice.lower() != ('s'): player_choice = input("Options are to (H)it or (S)tand :") if player_choice == 'h': print('Hit!') ...
def checkWinner(self, brd: board.Board): if not self.checkAvailablesFor(brd, "x") and not self.checkAvailablesFor(brd, "o"): return 1 if len(brd.blue) > len(brd.red) else -1 if len(brd.red) > len(brd.blue) else 0 return False def checkAvailablesFor(self, brd: board.Board, objetives: str) -> ...
This function implements the minimax algorithm with alpha-beta pruning to determine the optimal move in a board game. It evaluates possible moves recursively, maximizing/minimizing scores based on the player's turn, and applies pruning to improve efficiency. The function checks for game-ending conditions, updates score...
def minimax(self, brd: board.Board, depth: int, isMaximizing: bool, alphaBeta: "tuple[int, int]") -> int: result = self.checkWinner(brd) if result != False or depth == (3 if self.difficulty else 0): brd.updateScore() return len(brd.red) if isMaximizing: self.c...
def train_set(values,numbers): trainset = [] for i in numbers: x= values[i] trainset.append(x) trainset= np.transpose(trainset) # transform n x 23 to 23 x n return trainset def decision_tree(trainset,tree=None): #Get attribute with maximum information gain parent_guess = most_...
The function calculates the success rate of a decision tree model as the training set size increases incrementally. It iterates through specified training set sizes (increment_id), constructs a decision tree for each, predicts labels on a test set, compares predictions to actual outputs, computes accuracy, and collects...
def success_rate(testset_dict,test_id,sampling_id,increment_id): accuracy_collection = [] numbers = 0 # get dataset with increment and build the tree for i in increment_id: print('Running with {} examples in training set'.format(i)) numbers = sampling_id[:i] trainset= train_set(...
def train_set(values,numbers): trainset = [] for i in numbers: x= values[i] trainset.append(x) trainset= np.transpose(trainset) # transform n x 23 to 23 x n return trainset def decision_tree(trainset,tree=None): parent_guess = most_important(trainset) values = np.unique(train...
This function calculates the success rate of a decision tree model as the training set size increases incrementally. It iterates over specified training set sizes (increment_id), constructs a decision tree for each, predicts test samples, compares predictions against actual labels, and records accuracy. The output is a...
def success_rate(testset_dict,test_id,sampling_id,increment_id): accuracy_collection = [] numbers = 0 # get dataset with increment and build the tree for i in increment_id: print('Running with {} examples in training set'.format(i)) numbers = sampling_id[:i] trainset= train_set(...
def print_curl(g): for group in g: print("curl -H 'user-key: 401df87a02a8f4c13842a135bad415a4' -d 'fields name, rating, genres, involved_companies, url, summary; limit 50; where id = ", tuple(group), ";' 'https://api-v3.igdb.com/games/' >> newgames.json", sep="") def split_list(l): idx = 0 groups = [] while...
The main task of the code is to process and display information about companies by splitting missing companies into groups, printing existing and missing companies, formatting the groups, and showing all companies along with their count. The final line also processes missing games using a curl print, though this may be...
def main(): """ grouped_cos = split_list(find_missing_companies()) print("EXISTING:", find_existing_companies()) print("MISSING:", grouped_cos) format_groups(grouped_cos) print("ALL") print(find_all_companies()) print(len(find_all_companies())) print("-----") """ print_curl(split_list(find_missi...
def load_content_image(): img = tf.io.decode_image( tf.io.read_file("temp.jpg"), channels=3, dtype=tf.float32)[tf.newaxis, ...] img = crop_center(img) img = tf.image.resize(img, (256, 256), preserve_aspect_ratio=True) return img def load_style_image(style_image_url): style_image = load_image(sty...
This code generates a stylized image by applying the artistic style of a given style_image to a content image using a pre-trained neural network model (hub_module). It loads the content and style images as TensorFlow constants, processes them through the model, extracts the stylized output, and displays the result.
def generate_image(hub_module, style_image): engine.get_cur_image() content_img = tf.constant(load_content_image()) style_img = tf.constant(load_style_image(style_image)) outputs = hub_module(content_img, style_img) stylized_image = outputs[0] show_n([stylized_image], titles=['Stylized image'])
def _satisfy_var(self, point, func): assert tuple(point) in self.sim_data var = np.var(self.sim_data[tuple(point)]['res'], ddof=1) num_eval = self.sim_data[tuple(point)]['res'].size # calculate the probability of variance being smaller than the variance threshold using the posterior inve...
The function `_satisfy_mu` evaluates two decision points by comparing their mean objective values and variances from simulation data. It calculates the probability that one point's mean is not significantly worse than the other using a normal distribution. If the probability falls within a significance threshold, it ad...
def _satisfy_mu(self, point_1, point_2, func): assert tuple(point_1) in self.sim_data assert tuple(point_2) in self.sim_data # check if robust optimization is needed if self.robust_obj: self._satisfy_var(point_1, func) self._satisfy_var(point_2, func) # ca...
def _func_eval(self, point, num_eval, func): res = [] point = point if isinstance(point, np.ndarray) else np.asarray(point) # make decision vectors a tuple for use in the dictionary true_point = self._back_transform(point) for _ in range(num_eval): res.append(func(true_point)...
This function generates neighboring centers along dimensions with maximum side length by evaluating points in ±delta directions, stores their results, checks significance if noisy_direct is enabled, and determines min/max neighbors based on objective evaluations, returning a dictionary of sorted neighbors for each dime...
def _sort_c_neighbors(self, c, func): max_side_len = np.max(self.sim_data[tuple(c)]['side_len']) # find the maximum side length delta = 1 / 3 * max_side_len # distance to the new neighboring centers dims = np.where(self.sim_data[tuple(c)]['side_len'] == max_side_len)[0] # find the dimensions wit...
def _check_bounds(self, lower_bounds, upper_bounds): # make lower bounds numpy array if isinstance(lower_bounds, list): lower_bounds = np.asarray(lower_bounds, dtype=np.float64) elif isinstance(lower_bounds, np.ndarray): lower_bounds.astype(np.float64) assert ...
The code implements a minimization algorithm that iteratively divides hyperrectangles to find optimal solutions within given bounds. It checks input bounds, identifies potentially optimal regions, splits them based on sorted dimensions, and tracks evaluation metrics. The loop continues until maximum iterations, functio...
def minimize(self, func, lower_bounds, upper_bounds): self._check_bounds(lower_bounds, upper_bounds) # check input bounds # main loop with three termination criteria while (self.iter_ < self.max_iter) and (self.total_func_eval < self.max_total_func_eval) and (self.total_point_eval < self.max_tot...
def start_screen(self): self.reset() pygame.display.set_caption("GENIUS") messages = ['WELCOME TO GENIUS', 'press SPACE to START', 'press ESC to LEAVE', 'use your keyboard to play:'] colors = [[BLACK, BRIGHT_YELLO...
This code implements a finite state machine (FSM) to manage game state transitions. It continuously checks the current state (e.g., initial screen, level selection, gameplay, game over, winner) and invokes corresponding methods to handle each state's logic, creating a loop that drives game flow and screen updates based...
def fsm(self): while True: if self.state == INITIAL_SCREEN: self.start_screen() elif self.state == CHOOSE_LEVEL: self.choose_level() elif self.state == GAME_ON: self.game_on() elif self.state == GAME_OVER: ...
def check_win(player): """ Check rows, columns and diagonals for a win :param player: The player to check for a win :return: True if the player has won, False otherwise """ # Check rows for row in range(3): if board[row][0] == board[row][1] == board[row][2] == player: ret...
This code implements a game loop for a two-player (human vs AI) game using Pygame. It handles user input for placing human moves, checks for wins/draws, switches turns to the AI, updates the game state, and renders the board. The loop continues until the game ends, then waits for user input to exit.
def main_loop(): global game_over, current_player, winner while not game_over: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN and current_player == HUMAN: mouse_x ...
def check_win(player): """ Check rows, columns and diagonals for a win :param player: The player to check for a win :return: True if the player has won, False otherwise """ # Check rows for row in range(3): if board[row][0] == board[row][1] == board[row][2] == player: ret...
The main task of the code is to run a game loop for a turn-based game (likely Tic-Tac-Toe), handling player input, AI moves, win/draw checks, and screen updates. It processes mouse clicks for the human player, validates moves, switches to AI turn, checks for victories or draws, and updates the display with appropriate ...
def main_loop(): global game_over, current_player, winner while not game_over: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN and current_player == HUMAN: mouse_x ...
def heuristic(p1, p2): """ Calculates the Manhattan distance between two points - heuristic for A*. :param p1: The first point. :param p2: The second point. :return: The Manhattan distance between the two points. """ x1, y1 = p1 x2, y2 = p2 return abs(x1 - x2) + abs(y1 - y2) def reco...
This function implements A* or Dijkstra's algorithm to find the shortest path between start and end nodes on a grid. It uses a priority queue to explore nodes, updating g-scores (actual cost) and f-scores (heuristic-informed estimate). For A*, f-score includes a heuristic; for Dijkstra, it uses only g-score. When the e...
def algorithm(start: Node, end: Node, algorithm_type=A_STAR): """ Implements the A* or Dijkstra's algorithm to find the shortest path between the start and end nodes. :param start: The start node. :param end: The end node. :param algorithm_type: The type of algorithm to use (A* or Dijkstra). """...
def make_grid(): """ Creates the grid of nodes. """ global GRID, START, END GRID = [] gap = WIDTH // ROWS # Divide the total width by the number of rows to get the width of each cell for i in range(ROWS): GRID.append([]) for j in range(ROWS): node = Node(i, j, ga...
This code creates a grid-based pathfinding visualizer using Pygame. It allows users to place barriers, set start/end points, and select algorithms (A* or Dijkstra's) to visualize pathfinding. The main loop handles user input for grid manipulation, algorithm selection, and executes the chosen algorithm on the grid, upda...
def main(): make_grid() running = True algorithm_type = A_STAR while running: draw() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Left or right mouse button if pygame.mouse.get_pressed()[0] or pyga...
def DrawAxis(win): for i in range(window_h): pt = Point(window_w/2,i) pt.draw(win) for i in range(window_w): pt = Point(i,window_h/2) pt.draw(win) def BresenhamLine(x1,y1,x2,y2,win): x, y = x1, y1 dx = abs(x2 - x1) dy = abs(y2 - y1) if x1==x2 and y1==y2 ...
The code initializes a grid, takes user input for a polygon's vertices, draws the polygon using Bresenham's line algorithm, and applies the flood fill algorithm to fill the polygon. It creates a graphics window, sets the background, draws axes, and performs the fill before closing the window.
def FloodFillInit(): for i in range(window_w): points.append([]) for j in range(window_h): points[i].append("blue") print("Enter no. of sides in polygon:") s=int(input("Enter sides:")) print("Enter the points:") po=[] for i in range(s): print("enter...
def drawAxis(win): for i in range(window_h): pt = Point(window_w/2,i) pt.draw(win) for i in range(window_w): pt = Point(i,window_h/2) pt.draw(win) def PutPixle(win, x, y): """ Plot A Pixle In The Windows At Point (x, y) """ newx, newy = convertPixel(x,y) prin...
The code implements Bresenham's circle algorithm to draw a circle on a graphics window by calculating pixels using a decision parameter and eight-way symmetry. It initializes variables, plots the circle's octant points, and uses conditional updates to determine pixel positions, ultimately rendering the full circle via ...
def bressenhamCircle(xc,yc,r): x = 0 y=r d = 3-(2*r) win = GraphWin('Midpoint Circle drawing Algorithm', window_w, window_h) drawAxis(win) PutPixle(win,xc,yc) eightWaySymmetricPlot(xc,yc,x,y,win) while x<=y: if d<0: d = d+(4*x)+6 else: d = d+(4*x)-...
def drawAxis(win): for i in range(window_h): pt = Point(window_w/2,i) pt.draw(win) for i in range(window_w): pt = Point(i,window_h/2) pt.draw(win) def PutPixle(win, x, y): """ Plot A Pixle In The Windows At Point (x, y) """ newx, newy = convertPixel(x,y) prin...
This code implements the midpoint circle drawing algorithm to plot a circle with 8-way symmetry. It initializes variables, calculates decision parameters, and iteratively updates pixel positions to draw the circle in all octants using symmetry, then displays the result in a graphical window.
def midPointCircle(xc,yc,r): x = 0 y=r d = 5/float(4)-r win = GraphWin('Midpoint Circle drawing Algorithm', window_w, window_h) drawAxis(win) PutPixle(win,xc,yc) eightWaySymmetricPlot(xc,yc,x,y,win) while x<=y: if d<0: d =d+2*x+1 else: d = d+2*(x...
def BresenhamLine(x1,y1,x2,y2,win,color=None): x, y = x1, y1 dx = abs(x2 - x1) dy = abs(y2 - y1) if x1==x2 and y1==y2 : PutPixle(win,x,y,color=color) elif y1==y2: if x1<x2: while x != x2 : PutPixle(win,x,y,color=color) x+=1 els...
The code defines a function `move_object` that continuously listens for arrow key inputs to move a graphical object (likely a line or rectangle) on a window. It adjusts the object's coordinates, redraws lines using Bresenham's algorithm, and applies flood fill to update the display, ensuring the object moves within the...
def move_object(ll,lr,ul,ur,window): while True: key = window.getKey() absolute_half_width = window_w/2 absolute_half_height = window_h/2 if key=='Right': step = 20 if abs(lr[0])+step>absolute_ha...
def BressenhamLine(x1,y1,x2,y2,win): x, y = x1, y1 DrawAxis(win) dx = abs(x2 - x1) dy = abs(y2 - y1) if x1==x2 and y1==y2 : PutPixle(win,x1,y1) elif y1==y2: if x1<x2: while x != x2 : PutPixle(win,x,y) x+=1 else: ...
The code implements a scanline polygon filling algorithm. It takes user input for polygon vertices, constructs edge tables, and applies either the Edgelist with Active Edgelist or standard Edgelist ScanLine algorithm to render filled polygons, using graphical input/output for visualization.
def main(): global st_y global en_y option = int(input("Enter 1 for Edgelist and Active Edgelist ScanLine and \nEnter 2 for Edgelist ScanLine Algorithm \n")) print("Enter no. of sides in polygon:") s = int(input("Enter sides:")) print("Enter the points:") points = [] for i in range(s): ...
def BresenhamLine(x1,y1,x2,y2,win,color=None): x, y = x1, y1 dx = abs(x2 - x1) dy = abs(y2 - y1) if x1==x2 and y1==y2 : PutPixle(win,x,y,color=color) elif y1==y2: if x1<x2: while x != x2 : PutPixle(win,x,y,color=color) x+=1 els...
The main task of the code is to create an interactive graphical application where a user clicks inside a square to trigger a flood fill (coloring the square blue) and then animates the square passing through two yellow lines. The program uses Bresenham's algorithm to draw shapes, validates user input, and demonstrates ...
def square_pass(): for i in range(window_w): points.append([]) for j in range(window_h): points[i].append("blue") ll = [-250,-250] lr = [-150,-250] ur = [-150,-150] ul = [-250,-150] po=[ll,lr,ur,ul] s = 4 straightline1 = [[0,5],[40...
def _check_instrument(self, update): """Check that update's instrument is correct. Args: update (dict): Data from IG Streaming service. Returns bool: True if correct. """ instrument = update['name'].split(':')[1] if instrument == self.instrument:...
The function processes streaming candlestick data by continuously retrieving updates every second. It checks if the instrument matches, extracts timestamp, bid, and ask prices from the update, and saves the consolidated candle data to disk while appending it to a dataset if valid.
def callback_tick(self, update): """Retrieve stream of candle stick type data. Data is retrieved continuously (streaming), about every 1 seconds. If the candle has finished (consolidated), the candle is saved. Args: update (dict): Data from IG Streaming service. """...
def seg2d_vol_to_iou2d(seg_vol, th_iou=0): get_seg = lambda z: seg_vol[z] index = range(seg_vol.shape[0]) return segs_to_iou(get_seg, index, th_iou) def iou_list_to_global_id(iou_list): get_iou = lambda z: ( read_vol(iou_list[z]) if isinstance(iou_list[z], str) else iou_list[z] ) index =...
The main task of the code is to track and remap 2D segmentation labels across a 3D volume by calculating IOU between consecutive slices, generating global ID mappings, and applying these mappings to remap labels in each slice. It also filters out small objects if specified, enabling parallel processing for large volume...
def track_seg2d_vol( seg2d_vol, mapping=None, matches=None, global_id=None, iou=None, th_iou=0.1, th_sz=-1, ): # parallel version: demo/track_seg2d_list.py # assume can't load all seg2d into a volume if global_id is None: if iou is None: iou = seg2d_vol_to_iou...
def getmetrics(type, target, base_sample_root, ranks, ckpt, n_samples, config, sample_root, eval_json, numgen, base_ckpt="sd-v1-4.ckpt"): # load data meta_data = json.load(open(eval_json, 'r'))[type][target] target_prompts = retrieve_target_prompts(type, target, eval_json) numgens = 2 * [...
This code evaluates machine learning models by processing checkpoints and computing metrics. It handles two stages: if `eval_stage` is False, it iterates over checkpoints, prints them, and runs `getmetrics` for evaluation; if True, it retrieves target prompts and executes `calmetrics` to calculate metrics. The script m...
def main(args): sample_root = safe_dir(Path(args.root) / args.eval_path) os.makedirs(args.base_outpath, exist_ok=True) ranks = [int(i) for i in args.gpus.split(',') if i != ""] if not args.eval_stage: for ckpt in (Path(args.root) / 'checkpoints').glob(args.filter): print(ckpt) ...
def register_halo(app): with app.app_context(): from halo_app.apis import load_api_config if 'SSM_TYPE' in app.config and app.config['SSM_TYPE'] != 'NONE': load_api_config(app.config['ENV_TYPE'], app.config['SSM_TYPE'], app.config['FUNC_NAME'], app.config['API...
This function creates a Flask application using an app factory pattern, initializes Swagger API documentation, loads configuration settings, and registers extensions, blueprints, error handlers, and other components. It returns the configured Flask app instance with integrated API specs and monitoring.
def create_app(config_object='webfront_service.settings.__init__'): """An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ app = Flask(__name__.split('.')[0]) app.config.from_object(config_object) ...
def get_len_t(D, T): len_t = D[T[0]][T[-1]] for i in range(len(T) - 1): len_t += D[T[i]][T[i + 1]] return len_t def get_routes(m, n, tau, eta, alpha, beta): routes = [[] for _ in range(m)] for k in range(m): allow_list = [i for i in range(n)] tabu_list = [] routes[k] ...
The code implements an Ant Colony Optimization (ACO) algorithm to solve the Traveling Salesman Problem (TSP). It iteratively generates ant routes using pheromone (tau) and heuristic (eta) matrices, updates the best route (T_) based on path lengths (L_), and adjusts pheromone levels (tau) after each iteration. The goal ...
def antTSP(tmax, D, alpha, beta, Q, tau0, q): n = len(D) m = n eta = [[0] * len(D[i]) for i in range(n)] tau = [[0] * len(D[i]) for i in range(n)] for i in range(n): for j in range(n): if i != j: eta[i][j] = round(1 / D[i][j], 3) tau[i][j] = tau0...
def get_len_t(D, T): len_t = 0 for l_i in range(len(T) - 1): len_t += D[T[l_i]][T[l_i + 1]] return len_t def get_routes(l_start, l_end, m, n, tau, eta, alpha, beta): routes = [[] for _ in range(m)] for k in range(m): allow_list = [l_i for l_i in range(n)] tabu_list = [] ...
The code implements an ant colony optimization algorithm to find the shortest path between a start and end node in a graph. It initializes pheromone (tau) and heuristic (eta) matrices, iteratively generates routes using pheromone and heuristic values, updates the best route (T_) if a shorter path is found, and returns ...
def antPath(tmax, start, end, D, alpha, beta, Q, tau0, q): n = len(D) m = n eta = [[0] * len(D[i]) for i in range(n)] tau = [[0] * len(D[i]) for i in range(n)] for i in range(n): for j in range(n): if i != j: eta[i][j] = round(1 / D[i][j], 3) tau[...
def get_player_position(self, player_id, board=None): """ :param player_id: 0/1/-1 board: the current state board :return: """ pos = [] size = np.array(board).size if size == 24: for i in range(24): if board[i] == player_id + 1:...
This function evaluates all possible soldier moves on a board game, using a search algorithm to determine the optimal move by maximizing a value. It iterates through each soldier's potential directions, simulates moves, and selects the highest-value move within a time constraint. It also checks if a "mill" (three-in-a-...
def _stage_2_move(self, turn_time) -> tuple:## posiblite direction change start_time = time.time() cell, soldier_that_moved = -1, -1 soldiers_on_board = self.get_player_position(0) time_divisor = len(soldiers_on_board) minmax_turn_time = turn_time/time_divisor max_val = A...
def goal(self, state): if state.current_turn > 17: player_count = np.count_nonzero(state.playerPositions == -2) rival_count = np.count_nonzero(state.rivalPositions == -2) num_move_1 = self.player_cant_move(1, state) num_move_2 = self.player_cant_move(2, state) ...
The code calculates a utility value for a game state by combining three heuristics: mill count difference, incomplete mill count, and remaining soldiers. It prioritizes remaining soldiers (weight 4), mill advantage (weight 3), and potential mills (weight 2) to evaluate state favorability for the maximizing player. If t...
def utility(self, state, maximizing_player): if self.goal(state): return 1000 h1 = self.diff_mill_count(state.board, maximizing_player) h2 = self.incomplate_mill_count(state.board) h3 = self.remaining_soldier_count(state) return 3*h1 + 2*h2 + 4*h3
def get_data(file_path): with open(file_path, "rb") as f: data = pickle.load(f) return data def train(train_data, evaluate_fips, train_fips, epoch, iter_count=0, mode="init", exp_postfix="", best_train_r2=float("-inf")): lossfn = nn.MSELoss(reduction='mean') compute_r2 = R2Loss() h...
The main task of the code is to train and evaluate a model with adaptive task splitting. It initializes experiment directories, saves configurations, loads data, and iteratively trains on dynamically split "easy" and "hard" task subsets during epochs. The training adjusts task partitions based on performance metrics (R...
def main(): if not os.path.exists(args.exp_dir): os.makedirs(args.exp_dir) with open(os.path.join(args.exp_dir, 'configs.json'), 'w') as f: json.dump(vars(args), f, indent=2) if args.test_only != 1: if os.path.exists(os.path.join(args.exp_dir, "tasks_easy.txt")): os.remo...
def get_data(file_path): with open(file_path, "rb") as f: data = pickle.load(f) return data def get_cluster_model(data): input_list = [] fips_list = [] for iter, batch in enumerate(data.items()): batch = batch[1] support_x, support_y, support_fips, support_dp, support_year, q...
The code performs clustering on training and test data using KMeans, then trains a model iteratively on each cluster. It saves configurations, manages experiment directories, and optionally tests only. The main task involves clustering data, training per-cluster models, and evaluating them across epochs.
def main(): if not os.path.exists(args.exp_dir): os.makedirs(args.exp_dir) with open(os.path.join(args.exp_dir, 'configs.json'), 'w') as f: json.dump(vars(args), f, indent=2) if args.test_only != 1: if os.path.exists(os.path.join(args.exp_dir, "train_clusters.json")): os...
def get_SF_galaxies(snap, simulation_run='RefL0100N1504', m_star_min=8.0, m_star_max=10.5, m_gas_min=8.5, verbose=False): # Create Query of EAGLE database myQuery = '''SELECT \ SF_Metallicity as Zgas,\ Stars_Metallicity as Zstar,\ StarFormationRate as SFR,\ Ma...
(The function saves star-forming galaxy data from a simulation snapshot by filtering galaxies via mass thresholds, storing group catalog info in `.npy` files, and optionally processing individual galaxies to extract and save detailed data using the EAGLE simulation. It organizes outputs by snapshot, handles file lookup...
def save_data(snap, EAGLE, sim_name, file_ext='z000p000', m_star_min = 9.0, m_star_max=11.0, m_gas_min=9.0, where_to_save=None): # Note that I am only interested in central galaxies here... can be modified to include satellite save_dir = '%s_SF_galaxies/' %sim_name + 'snap_%s' %str(snap).zfil...
def generate_dots(self): for dot in range(self.dot_num): new_dot = self.generate_dot(self.dots) print("generate dot:", dot, ": ", new_dot) self.dots.insert(dot, new_dot) def get_start_dot(self): self.start_dot_key = random.randint(0, self.dot_num) - 1 start_...
The code processes a route by generating points, selecting a starting dot, identifying nearby points, inserting the start dot into the route, and converting the route into a visual chart for representation.
def processing(self): print("generate dots") self.generate_dots() print("picking starting dot") start_dot = self.get_start_dot() print("get near dot") self.near_dots(start_dot) print("====================") self.route.insert(0, self.start_dot) prin...
def get_key(self): var = self.get_varint() field_number = var >> 3 # proto define field number wire_type = var & (0x1 | 0x1<<1 | 0x1<<2) return field_number,wire_type def get_varint(self): int_bts = [] bt = self.eat_bytes(1) int_bts.append(bt) while self.n...
The code parses a binary buffer into a dictionary (`msg`) by iterating through fields, decoding values based on wire types (varint, length-delimited, etc.), and handling repeated fields by appending values to lists. It constructs keys using field numbers and wire types, ensuring repeated entries are stored as lists. Th...
def parse(self): # msg should always be dict, key-value pair msg = {} while self.buffer: field_number,wire_type = self.get_key() if wire_type == self.TYPE_VARINT: var = self.get_varint() elif wire_type == self.TYPE_LENGTH_DELIMITED: ...
def aggregate_sso_data(output_filename=None): """ Aggregate all SSO data in Fink Data is read from HDFS on VirtualData Parameters ---------- output_filename: str, optional If given, save data on HDFS. Cannot overwrite. Default is None. Returns ---------- df_grouped: Spark Data...
The function `build_the_ssoft` generates a pandas DataFrame containing SSO (Small Solar System Objects) data by processing aggregated or downloaded Fink data. It filters objects by minimum measurements, samples data if specified, computes orbital parameters using a chosen model (default: SHG1G2), and adds derived featu...
def build_the_ssoft(aggregated_filename=None, bft_filename=None, nproc=80, nmin=50, frac=None, model='SHG1G2', version=None) -> pd.DataFrame: """ Build the Fink Flat Table from scratch Parameters ---------- aggregated_filename: str, optional If given, read aggregated data on HDFS. Default is No...
def check_exists(path): """ Check if a file or directory exists at the given path. Parameters: path (str): The path to check for existence. Returns: bool: True if a file or directory exists at the given path, False otherwise. """ import os if os.path.exists(path): ret...
The code's main task is to predict corrected hour angle (HA) and declination (Dec) values using a trained neural network model. It processes input parameters (HA, Dec, temperature, latitude, and previous values) by calculating trigonometric features, scaling them, feeding them into the model, and applying inverse scali...
def make_predict(ha=None, dec=None, temp=None, latitude=None, prev_ha=None, prev_dec=None): """ Make predictions using a trained model. Args: ha (float): Target's hour angle. dec (float): Target's declination. temp (float): Temperature in degrees Celsius. ...
def isComplete(self, assignment: Dict[Variable, Value]) -> bool: """ Return whether the assignment covers all variables. :param assignment: dict (Variable -> value) """ # TODO: Implement CSP::isComplete (problem 1) return len(self.remainingVariables(assignment))==0 def select...
This code implements a backtracking algorithm to solve a Constraint Satisfaction Problem (CSP) via brute force. It recursively assigns values to variables, checks validity, and returns a complete valid assignment if found. The method uses helper functions to select variables, order domains, and validate assignments, ba...
def _solveBruteForce(self, assignment: Dict[Variable, Value], domains: Dict[Variable, Set[Value]]) -> Optional[Dict[Variable, Value]]: """ Implement the actual backtracking algorithm to brute force this CSP. Use `CSP::isComplete`, `CSP::isValid`, `CSP::selectVariable` and `CSP::orderDomain`. ...
def isComplete(self, assignment: Dict[Variable, Value]) -> bool: """ Return whether the assignment covers all variables. :param assignment: dict (Variable -> value) """ # TODO: Implement CSP::isComplete (problem 1) return len(self.remainingVariables(assignment))==0 def select...
The main task of the code is to implement a backtracking algorithm with forward checking for solving Constraint Satisfaction Problems (CSPs). It recursively assigns values to variables, prunes domains via forward checking, and returns a complete valid assignment if possible. If no solution exists, it returns False. The...
def _solveForwardChecking(self, assignment: Dict[Variable, Value], domains: Dict[Variable, Set[Value]]) -> Optional[Dict[Variable, Value]]: """ Implement the actual backtracking algorithm with forward checking. Use `CSP::forwardChecking` and you should no longer need to check if an assignment is val...
def isComplete(self, assignment: Dict[Variable, Value]) -> bool: """ Return whether the assignment covers all variables. :param assignment: dict (Variable -> value) """ # TODO: Implement CSP::isComplete (problem 1) return len(self.remainingVariables(assignment))==0 def select...
The main task of the code is to implement a backtracking algorithm with AC3 constraint propagation for solving Constraint Satisfaction Problems (CSPs). It recursively selects variables, reduces domains using AC3, checks validity, and backtracks if no solution is found. The function returns a complete valid assignment i...
def _solveAC3(self, assignment: Dict[Variable, Value], domains: Dict[Variable, Set[Value]]) -> Optional[Dict[Variable, Value]]: """ Implement the actual backtracking algorithm with AC3. Use `CSP::ac3`. :return: a complete and valid assignment if one exists, None otherwise. ...
def domainsFromAssignment(assignment: Dict[Variable, Value], variables: Set[Variable]) -> Dict[Variable, Set[Value]]: """ Fills in the initial domains for each variable. Already assigned variables only contain the given value in their domain. """ domains = {v: v.startDomain for v in variables} f...
The main task of the code is to solve a Constraint Satisfaction Problem (CSP) using forward checking. It initializes domains from the initial assignment, applies forward checking to prune inconsistent domains, and then invokes the core solving method `_solveForwardChecking` with the updated domains and initial assignme...
def solveForwardChecking(self, initialAssignment: Dict[Variable, Value] = dict()) -> Optional[Dict[Variable, Value]]: """ Called to solve this CSP with forward checking. Initializes the domains and calls `CSP::_solveForwardChecking`. """ domains = domainsFromAssignment(initialAssignment, sel...
def domainsFromAssignment(assignment: Dict[Variable, Value], variables: Set[Variable]) -> Dict[Variable, Set[Value]]: """ Fills in the initial domains for each variable. Already assigned variables only contain the given value in their domain. """ domains = {v: v.startDomain for v in variables} f...
This method solves a Constraint Satisfaction Problem (CSP) using the AC3 algorithm. It initializes variable domains from the input assignment, applies AC3 to enforce arc consistency by reducing domains, then calls `_solveAC3` to find a valid solution with the updated domains.
def solveAC3(self, initialAssignment: Dict[Variable, Value] = dict()) -> Optional[Dict[Variable, Value]]: """ Called to solve this CSP with AC3. Initializes domains and calls `CSP::_solveAC3`. """ domains = domainsFromAssignment(initialAssignment, self.variables) domains = self.ac3(i...
def parse_j1939_id(can_id): sa = SA_MASK & can_id pf = (PF_MASK & can_id) >> 16 da = (DA_MASK & can_id) >> 8 if pf >= 240: # PDU2 format pgn = pf * 256 + da da = 0xFF else: pgn = pf * 256 #special cases: # if(can_id == 0x1dff7a00): # return return p...
The code parses JSON data to extract CAN bus messages, filtering by date if specified. It converts CAN IDs to integers, parses J1939 IDs (PGN, DA, SA), processes CAN data, and compiles relevant message data into a list for output.
def parse_data_from_messages(sort_by_date): data = json.load(file_json_file) list_to_send = [] for json_element in data: if(sort_by_date != ""): msg_date = (json_element["dateHourSecondsTimeReceived"].strip()) if(not sort_by_date in msg_date): continue ...
def MakingRequest(url: str) -> str: URL = 'https://www.x-rates.com/table/?from=USD&amount=1' r = requests.get(URL) if r.status_code == 200: soup = BeautifulSoup(r.text, 'html.parser') print("\033[92m Request was successfully done. The status code: {}".format(r.status_code)) USDollarE...
The code retrieves USD exchange rates from a specified URL, processes the data into a dictionary and DataFrame, and saves the results as JSON and CSV files for further use or analysis.
def finalExecutionOfExchangeRate(): URL = 'https://www.x-rates.com/table/?from=USD&amount=1' MakingRequest(URL) ConvertingListComprehensionToDicionary() DictionaryDataCurrencyValues = DictionaryOfExchangeRate() SaveToJSONfile(DictionaryDataCurrencyValues) dfUSDollarExchangeRates = DataFrameOfExc...
def numOfLines(file): with open(file) as f: count = sum(1 for _ in f) return count def initial(): # To calculate the extreme points to make the initial simplex x_min_temp = 10**9 x_max_temp = -10**9 y_min_temp = 10**9 y_max_temp = -10**9 z_min_temp = 10**9 z_max_temp = -10**9 for i in range(num): if po...
The code computes the convex hull of a 3D point set from an input file. It reads points, constructs initial planes, iteratively builds the hull by identifying external points and updating planes, and removes internal structures. Finally, it outputs the number of vertices, volume, and surface area of the convex hull to ...
def make_hull(fdata): global points global num global list_of_planes points = [] # List to store the points # if len(sys.argv) < 2: # print "Few arguments. See README for help" # sys.exit() try: # Open the input and store it in points list data = open(fdata, "r") num = numOfLines(fdata) for line in da...
def handle_client_message(self, msg): logger.info(f"role: {self.role}, leader_id: {self.leader_id}") # Drop all messages where there is no leader_id or it is None. if self.role == 'candidate': return elif self.role == 'follower': if self.leader_id is not None: ...
This method processes incoming messages in a distributed consensus system, handling client messages, Raft AppendEntries/RequestVote requests, and their replies. It updates the node's term and role (to follower) when receiving higher-term messages, ensuring consistency. Different message types trigger specific handlers ...
def handle_msg(self, msg: Message): logger.info(f"Message {msg.action} from {msg.sender} received by {msg.receiver}") if not hasattr(msg.action, 'term'): self.handle_client_message(msg) return if self.current_term < msg.action.term: self.current_term = msg.ac...
def translate_question_to_sql(self, question: str): database_ddl = self.enrich_ddl_with_comments(self.db_connector.get_all_schemas_ddl()) database_type = self.db_connector.db_type system_prompt="You are a helpful SQL develper.\n-Reply with SQL code snippet example : ```sql select * from table```...
The code translates a user's question into an SQL query, executes it against a database, handles errors by correcting the query, and generates a natural language response using an LLM. It also translates the question and response between languages if needed, ensuring the final answer matches the original language of th...
def answer(self, question: str, verbose=False) -> str: # Translate the question to English if necessary original_language = self.language if original_language != 'English': question = self.language_translator.translate_to_english(question, original_language) # Translate the ...
def get_time_from_file(self, fp): try: with open(fp) as f: start_time_raw = f.readline() return start_time_raw except Exception: self.reset_timer() def extract_time(self, the_time): h, m, s, ms = [int(i) for i in the_time.split(':')] re...
The code sets a file path, extracts and validates a start time from the file, converts it to an integer, and updates the timer time if valid. If extraction fails, it prints the error and resets the timer.
def set_file(self, file): self.file_path = file start_time_raw = self.get_time_from_file(self.file_path) if start_time_raw is not None and start_time_raw is not '' and start_time_raw is not 0: try: start_time = int(self.extract_time(start_time_raw)) se...
def system(sys): systems = [sys[np.random.randint(0, len(sys))] for _ in range(200)] return systems def DE(system, i=0,e=0,f=0, color_code=random, width = 1, alpha = 1, delta = 1, dt = 0.5, randomise=0, minimize=0, r=0): a = system[0] b = system[1] c = system[2] d = system[3] sol_ = list() ...
The main task of the code is to generate a series of visualizations by repeatedly applying the DE function with randomized parameters to plot dynamic trajectories, overlaying text annotations, and saving each iteration as an image. It creates an interactive matplotlib plot, iterates 'reps' times, and exports frames sho...
def repeat(reps): plt.ion() figure,ax = plt.subplots() k = 100 plt.xlim([-k,k]) plt.ylim([-k,k]) random_number_1 = np.random.randint(0, len(sink)) random_number_2 = np.random.randint(0, len(sink)) random_number_3 = np.random.randint(0, len(sink)) systems = system(spiral_source) f...
def enlarge_bounding_box(bbox: torch.Tensor) -> torch.Tensor: """Enlarge the bounding box to the smallest square that contains it without changing its center. @param bbox: A tensor of shape (4) containing the bounding box in the format [x, y, w, h]. @return: A tensor of shape (4) containing the enlarged bo...
The main task of the code is to process a batch of images and their associated annotations by cropping and resizing images based on bounding boxes, extracting and processing keypoints, and generating keypoint heatmaps. It returns a list containing the cropped image and the processed keypoint images for further analysis...
def process_batch( image: torch.Tensor, bbox: torch.Tensor, keypoints: torch.Tensor, label_mask: torch.Tensor, image_size: int, scale_factor: int, ) -> List[torch.Tensor]: """Process a batch of data. @param image: A tensor of shape (batchsize, channels, height, width) containing the ima...
def disable_nus(show_message=True): # Check if NUS is already enabled. zgoptns, vclist = GETPAR("ZGOPTNS"), GETPAR("VCLIST") if not ("-DNUS" in zgoptns and "noah" in vclist): if show_message: info_message(NUS_ALREADY_OFF.format(this_script_name())) return # To undo NUS is ea...
The main task of the code is to enable Non-Uniform Sampling (NUS) in a spectroscopy setup by validating system parameters, calculating adjusted sampling values, generating a NUS schedule via an external tool, and updating configuration parameters. It checks if NUS is already enabled, verifies pulse program compatibilit...
def enable_nus(show_message=True): # Check if NUS is already enabled. If so, disable it. zgoptns, vclist = GETPAR("ZGOPTNS"), GETPAR("VCLIST") if "-DNUS" in zgoptns and "noah" in vclist: disable_nus(show_message=False) # Check if the pulse programme supports -DNUS flag pulprog = GETPAR("PUL...
def check_userdata(ctx, user): global global_args if 'board' not in ctx.user_data: # no board... this means that this # is the first time we see this user logging.info(f'initializing new user - switch turn mode = {global_args}') init_learner_data_for_user(ctx, user) creat...
The function `set_ai_to_minimax` configures a Minimax AI for a user in a game context. It checks the user's data, creates a Minimax AI instance for them, and initiates a new game. This likely supports a bot or game system where users can select AI strategies, with Minimax being a decision-making algorithm for competiti...
def set_ai_to_minimax(update, context): check_userdata(context, update.message.from_user) create_ai_for_user(context, 'minimax', update.message.from_user) newgame(update, context)
def check_userdata(ctx, user): global global_args if 'board' not in ctx.user_data: # no board... this means that this # is the first time we see this user logging.info(f'initializing new user - switch turn mode = {global_args}') init_learner_data_for_user(ctx, user) creat...
The function `set_ai_to_learner` initializes a learner-specific AI model for a user by checking their data, creating an AI instance, and starting a new game. It ensures user data is validated, provisions the AI for learning tasks, and triggers gameplay or interaction setup.
def set_ai_to_learner(update, context): check_userdata(context, update.message.from_user) create_ai_for_user(context, 'learner', update.message.from_user) newgame(update, context)
def check_end_of_game(res, brd): if res != 0 or brd.is_full(): return True return False def do_ai_move(ctx, c_id, ai_piece): _x, _y = ctx.user_data['ai'].move(ctx.user_data['board']) _, _res = ctx.user_data['board'].place_pawn(_x, _y, ai_piece) ctx.bot.send_message(c_id, ctx.user_data['lang'...
The function processes a user's move in a game, updates the board with the human player's piece, checks for game termination, triggers an AI move if the game continues, and manages game state transitions, including logging, result display, and initiating new games when necessary.
def parse_move_message(update, context): user_id = update.message.from_user['id'] c_id = update.message.chat_id logging.info(f'parse_move_message() called. chat_id {c_id}') context.bot.send_message(c_id, context.user_data['lang'].gettext("Your move: ") + update.message.text.upper(), ...
def check_userdata(ctx, user): global global_args if 'board' not in ctx.user_data: # no board... this means that this # is the first time we see this user logging.info(f'initializing new user - switch turn mode = {global_args}') init_learner_data_for_user(ctx, user) creat...
This function processes user messages in a game context by validating moves and handling them accordingly. It checks if a move is valid using the board's validation method, then processes the move with `parse_move_message` if valid, or handles invalid moves with `parse_nomove_message`, ensuring proper user interaction ...
def parse_message(update, context): check_userdata(context, update.message.from_user) if context.user_data['board'].is_valid_move(update.message.text): parse_move_message(update, context) else: parse_nomove_message(update, context)
def updateClosestPlayer(app): if(not app.showChat): minUid=None minValue=None players=list(app.players.keys())+[app.villain.uid] for uid in players: player=None if(uid not in app.players): player=app.villain else: player=app.players[uid] ...
The code handles game state updates, including protagonist movement based on mouse input, room transitions, player movement logic, gravity-based navigation, message switching, smiling mechanics, and time-based events like killing. It updates positions, checks interactions, manages game timers, and triggers actions like...
def timerFired(app): if(not app.paused and app.pressed and not app.showChat): #move protag based on mouse movements difference=abs(app.mouseX-app.protag.position) if(app.mouseY>=app.border+100): if(app.mouseX>app.protag.position and not app.protag.position>=app.w...
def __parse_name(self) -> None: logging.debug(" __parse_name") while (self.__next_line() is not None): line = self.line_str Environment.NAME = line def __parse_game_slots(self) -> None: logging.debug(" __parse_game_slots") while (self.__next_line() is not None):...
The main task of the code is to parse a file's contents by reading its lines, initializing counters, and delegating parsing tasks to helper methods. It reads the file, stores its lines, sets line and heading indices, then calls functions to extract structured data like names, game/practice slots, games, practices, comp...
def __parse_file(self) -> None: logging.debug("__parse_file") with open(self.filename, "r") as fh: self.file_contents = fh.readlines() self.num_lines = len(self.file_contents) self.current_line = 0 self.current_heading_index = 0 self.line_str =...
def resize_image(image, width = None, height = None, inter = cv2.INTER_AREA): """Resizes the input without distortion # Function source: https://stackoverflow.com/questions/44650888/resize-an-image-without-distortion-opencv """ # initialize the dimensions of the image to be resized and # grab the i...
The function detects numbers in images or video frames by processing inputs through resizing, face cropping (if applicable), blob detection, and number recognition. It handles multiple number detection or single-number extraction, with error handling and debugging options.
def detectNum(input_path, detect_multiple=False, debug = False, video_input=False): """Detects number from raw image by applying processing pipeline functions""" if video_input: img = input_path.copy() if detect_multiple: img = resize_image(img,500) else: ...
def search_all_ip_address(self): def map_ip_file(ipls, filels): ipls.sort() map_list = list() for sip in ipls: # Combine all same ip key map_list.append({sip: list(set([item[sip] for item in filels if sip in item.keys()]))}) return ...
The main task of the code is to process a list of keywords by searching through files. It handles three cases: exact matches, wildcard searches (with "*"), and a special "all ip" query. Results are stored in a dictionary, with each keyword as a key and corresponding search results as values.
def walk_keyword(self, keys): logger.info("Walking keyword: %s in total file: %s" % (keys, len(self.file_list))) for key in keys: if key.lower() == "all ip": self.result[key] = self.search_all_ip_address() elif "*" in key: self.result[key] = self.b...
def build_description(self): logger.info("Generating description info...") self.result["description"] = dict() self.result["description"]["keyword"] = self.keyword self.result["description"]["path"] = self.path ret = subprocess.check_output(r"cd {} && git branch | grep \*".format...
The main task of the code is to initialize the object's state by building a description, processing a file list from a specified path, and handling keywords. The method executes `build_description()` to set up the object's description, `walk_file_list(self.path)` to process files in the given path, and `walk_keyword(se...
def __enter__(self): """ Enter function will implement after __init__ :return: self, type: object """ self.build_description() self.walk_file_list(self.path) self.walk_keyword(self.keyword) return self
def UI_changes(self): self.system_service.setCurrentIndex(7) self.system_service.tabBar().setVisible(False) self.enable_disableupdate_employee() self.get_category() self.get_branch() self.get_location() BOOK_STATUS = ('New', 'Used', 'Old') self.book_status...
This code initializes a main window for a GUI application, setting up the user interface, connecting UI elements to handlers for login functionality, system buttons, and tab-specific operations (today, books, clients, history, settings). It prepares the window's structure, initializes components, and links interactions...
def __init__(self, parent=None) -> None: super(Main, self).__init__(parent) QMainWindow.__init__(self) self.emp = None self.setupUi(self) self.UI_changes() self.handle_login() self.handle_main_system_buttons() self.Handle_today_tab() self.Handle_bo...
def getInputData(window):#Gets data from input boxes and then passes it to the maya parts of the script print("Getting data from input boxes") mayaBinDir=window.lineEdit_binPath.text() pluginDir=window.lineEdit_pluginPath.text() scenePath=window.lineEdit_scenePath.text() print("Maya Bin Dir:",mayaB...
The code initializes a UI by loading a `.ui` file, sets plugin paths and window icons, connects buttons to functions for importing data, canceling, and opening file dialogs, restores previous settings, and displays the window with a Qt application.
def initUI():#Launches the UI loader = QUiLoader() if not QApplication.instance():#If an instance does not exist app = QApplication(sys.argv)#Launch a new Qapplication else:#If an instance does exist app = QApplication.instance()#Launch a new instance uiPath=pluginDir+"\MMU_UE_UI.ui" ...
def _(msg): return msg def newnames(varnames, suffixes, nameset, overwrite): """Return list of modified varnames with extension varnames is a list of variable names to modify. suffix is a list of suffixes to be appended to each name. if the suffix is not blank, it is preceded by "_"...
This function generates and submits SPSS commands to perform a text analysis search using specified words, language, and parameters. It validates inputs, constructs output variables, applies search criteria, and displays synonyms in a pivot table if enabled. The core task involves creating a text analysis workflow with...
def searching(searchwords, smode, nameset, swsuffix, varnames, overwrite, searchstem, posp, displaysyn, searchlang): global haswordslistparams if searchwords is None: raise ValueError(_("A word search was specified, but no word list was given")) searchlang = searchlang.lower() if not searchlang ...
def checkdep(package): """Check whether package is installed and fail if not package is the extension command name, e.g., STATS_TEXTANALYSIS""" from importlib import util spec = util.find_spec(package) # if there is a directory matching package but no .py file, # spec will not be ...
This function performs text processing tasks such as spell checking, frequency analysis, sentiment scoring, search operations, and lexicon creation on specified variables. It handles input validation, language settings, and executes designated operations based on flags like dospelling, dofreq, dosent, etc., generating ...
def dotext(varnames=None, overwrite=False, stopwordslang="english", stemmerlang="english", dospelling=False, ignorenames=True, extradict=None, spsuffix="cor", language="english", dofreq=False, stem=False, freqcount=10, doscores=False, scoresfile=None, dosent=False, stypes=None, ssuffixe...
def load_model(self): statefile = "./state" qvfile = "./qv" self.state_list = self.file2data(statefile) self.qv_list = self.file2data(qvfile) def insert_qv_at_index(self, index, qv_l, qv): if(len(qv_l) > index): qv_l[index] = qv else: diff = (index...
This code applies a negative reward to update Q-values in a reinforcement learning model. It loads the model, adjusts the Q-value of the last action using a learning rate and discount factor, inserts the updated Q-values into a list, and saves the model with updated states and Q-values.
def apply_negative_reward(self): self.load_model() self.last_qvalues[self.last_a] += self.learning_rate * (-1 + self.discount_factor * np.max(self.last_next_qvalues) - self.last_qvalues[self.last_a]) self.insert_qv_at_index(self.last_index, self.qv_list, self.last_qvalues) self.save_mode...
def load_model(self): statefile = "./state" qvfile = "./qv" self.state_list = self.file2data(statefile) self.qv_list = self.file2data(qvfile) def board2state(self, b, p): st = np.zeros([9]) for j in range(3): for i in range(3): if(b[j][i] == p)...
The main task of this code is to implement a Q-learning algorithm for a game-playing agent. It updates Q-values based on the current state, selected action, reward, and next state. The agent checks if the current state exists in its database, selects an action (randomly or via max Q-value), computes the reward, updates...
def learn(self): #print("LEARN >> player:{}".format(self.whoami)) self.load_model() state = self.board2state(self.game.get_board(), self.whoami) index = 0 a = 0 q_values = np.zeros([9]) if(self.state_in_data(state, self.state_list)): index = self.get_...
def load_model(self): statefile = "./state" qvfile = "./qv" self.state_list = self.file2data(statefile) self.qv_list = self.file2data(qvfile) def board2state(self, b, p): st = np.zeros([9]) for j in range(3): for i in range(3): if(b[j][i] == p)...
The code implements a reinforcement learning agent that selects actions based on pre-trained Q-values or random exploration, then updates the game state and processes rewards. It checks if the current game state exists in a stored list; if so, it uses corresponding Q-values to choose an action, prioritizing max Q-value...
def run(self): print("RUN >> player:{}".format(self.whoami)) self.load_model() state = self.board2state(self.game.get_board(), self.whoami) index = 0 a = 0 q_values = np.zeros([9]) if(self.state_in_data(state, self.state_list)): index = self.get_index...
def _is_valid_index(self, index: int) -> bool: return 0 <= index and index < len(self._input_cpp_content) def _get_receiver(cls, line: str) -> str: assert SelectParser.has_channel_mark(line) components: typing.List[str] = line.split(cls._CHANNEL_MARK)[0].split() return components[0] if c...
The code processes input C++ content to generate output code by filtering and modifying specific lines. It skips non-#include lines, writes a header, handles channel-based message operations (write/read), and processes "select" blocks by inserting defines. It iterates through input lines, conditionally writing transfor...
def generate(self) -> None: with open(self._output_cpp_file_name, "w") as output: index: int = 0 index_select: int = 0 while True: if not self._is_valid_index(index): break line: str = self._input_cpp_content[index] ...
def loadData(): train = np.loadtxt("train_cancer.csv", delimiter=",") test = np.loadtxt("test_cancer_pub.csv", delimiter=",") X_train = train[:, 0:-1] y_train = train[:, -1] X_test = test return X_train, y_train[:, np.newaxis], X_test def dummyAugment(X): aug_X = np.insert(X, 0, 1, axis=1) # print...
The code trains logistic regression models with and without a bias term, compares their performance via training loss curves, performs k-fold cross-validation to select the optimal learning rate, and generates test predictions using the best model parameters, saving results to a CSV file.
def main(): # Load the training data logging.info("Loading data") X_train, y_train, X_test = loadData() X_train_bias = dummyAugment(X_train) logging.info("\n---------------------------------------------------------------------------\n") # Fit a logistic regression model on train and plot its losses log...
def getNodeIndex(x, y): return x * height + y def findSet(parent, index): if index != parent[index]: return findSet(parent, parent[index]) return parent[index] def unionSet(parent, index1, index2, weightlist): root1 = findSet(parent, index1) root2 = findSet(parent, index2) if root1 == root2: return ...
This function checks adjacent grid cells to determine if they belong to different connected components using Union-Find. If so, it randomly selects a direction, removes the corresponding wall by updating the map, merges the components, and returns True. If no valid directions exist, it returns False. The process ensure...
def checkAdjacentPos(map, x, y, width, height, parentlist, weightlist): directions = [] node1 = getNodeIndex(x,y) root1 = findSet(parentlist, node1) if x > 0: root2 = findSet(parentlist, getNodeIndex(x-1, y)) if root1 != root2: directions.append(WALL_DIRECTION.WALL_LEFT) if y > 0: root2 ...
def set_coding_mat(self): ''' This method initializes the coding matrix, self.C ''' pass def update_irf(self, h_irf=None): # If nothing is given set to gaussian if(h_irf is None): print("hirf is NONE") self.h_irf = np.zeros((self.n_maxres,)) self.h_irf[0] = 1. else: self.h_irf = h_irf.squeeze() ...
This code initializes an object by setting up a coding matrix (C), configuring impulse response functions (IRF) for system band-limit and reconstruction, enabling/disabling IRF-based shift estimation via the `account_irf` flag, updating parameters derived from C, and retrieving available reconstruction/decoding algorit...
def __init__(self, h_irf=None, account_irf=False): # Set the coding matrix C if it has not been set yet if(self.C is None): self.set_coding_mat() # (self.n_maxres, self.n_codes) = (self.C.shape[-2], self.C.shape[-1]) # Set the impulse response function (used for accounting for system band-limit and match fil...
def simulatedAnnealingAlgo(graph, same_first_sol, graphShow): times = [] start = time.time() temperature = TEMPERATURE_INITIAL listCurrentScore = [] listBestScore = [] temperatureList = [] citiesArr = list(graph.nodes.values()) currentSolution, scoreCurrent = generate_first_solution(grap...
The code compares Simulated Annealing and Tabu Search algorithms on a graph. It reads input parameters, runs both algorithms, tracks their best solutions and costs, and visualizes results if enabled. The main task is evaluating and contrasting the two optimization techniques' performance on a graph problem, including i...
def main(): global tabu_list_max_size graph_path = sys.argv[1] tabu_list_max_size = int(sys.argv[2]) graph = Graph(graph_path) graph.nb_nodes = int(sys.argv[3]) numberOfEpochs = int(sys.argv[4]) same_first_sol = False graphShow = False a = len(sys.argv) if a > 5: if int(...
def no_weights(): """ The function displays an error message, because there aren't saved weights. """ pop = Tk() pop.wm_withdraw() messagebox.showerror("Error", "No weights to load the model with") pop.destroy() def check_acc(model, path, size, classes): """ Parameters ----------...
The function tests a Keras model on a dataset by checking accuracy if weights exist, then creates a GUI window for uploading images to classify traffic signs using the trained model, displaying results in a labeled interface.
def test(model, path, size, classes): """ Parameters ---------- model : A keras model. path : A string which is the path to the organized dataset. size : An integer which is the edge size of the input images. classes : A list that contains the names of the different classes. The functio...
def read_input_file(fileName): tempBuildingWeights = [] intData = [] with open(fileName, 'r') as inFile: data = inFile.readlines() for row in data: if ',' in row: # If we are reading a list of number tempBuildingWeights.append([int(num) for num...
The code reads input data about building simulations and floor structures, processes them through simulation runs and vertical merges, calculates the remaining floors after processing, and prints the heights of these remaining floors across multiple buildings.
def main(): filePath = 'input.txt' # sys.argv[1] simulations, verticalMerges, numberOfFloors, floors = read_input_file(filePath) numberOfBuildings = len(floors[0]) floors = run_simulations(simulations, verticalMerges, floors, numberOfBuildings) remainingFloors = count_remaining_floors(floors, numb...
def initialize_population(size): return [ChessNN() for _ in range(size)] def evaluate_fitness(model, number_of_games): total_score = 0 wins = 0 losses = 0 for _ in range(number_of_games): winner, white_score, black_score = play_random_game(model) #score_difference = white_score - bl...
The code evolves a population of models over multiple generations using a genetic algorithm approach. It evaluates each model's fitness and win rate, selects top-performing models, and repopulates the next generation. The global best model is tracked and saved periodically. Statistics like standard deviation, average f...
def evolve_models(generations, number_of_games): global global_best_model, global_best_fitness population_size = 50 top_n = 25 population = initialize_population(population_size) for gen in range(generations): fitness_scores = [] win_fractions = [] for model in population: ...
def is_finished(self) -> bool: return all([x.is_satisfied() for x in self.problem.constraints]) and len( self.problem.get_unassigned_variables()) == 0 def select_unassigned_variable(self) -> Optional[Variable]: if self.use_mrv: return self.mrv() unassigned_variables = sel...
This code implements a backtracking algorithm for solving constraint satisfaction problems. It recursively assigns values to unselected variables, checks consistency, applies forward checking if enabled, and backtracks when assignments lead to conflicts. The goal is to find a valid solution by exploring possible value ...
def backtracking(self): if self.is_finished(): return True var = self.select_unassigned_variable() for value in self.order_domain_values(var): var.value = value if self.is_consistent(var): if self.use_forward_check: self.f...
def print_colour_warning(message=None): print("+----------------------------------------------------------------+") if message is not None: lenzero = 63 - len(message) print('| {0}{1: <{2}}|'.format(message, ' ', lenzero)) print("| Please supply EITHER: ...
This code processes FITS files to create a merged catalog, validating metadata consistency (e.g., filter types, exposure dates) and ensuring correct combinations of observational data. It checks for mixed filter types, duplicate exposures, and required filter pairings (e.g., Hα with r-band). If valid, it processes indi...
def runmerge(filelist, radius, aperture, xmx, keep, nomerge, clobber): if len(filelist) > 8: print_colour_warning() sys.exit(0) # Create empty table which will store key FITS header information dtype = [('Filename', '|S256'), ('FieldID', '|S10'), ('obsdate', '|S8'), ('Filter', '|S6'), ('Exp...
def playerSnake(): while alive: playerGetDirection() moveSnake() gameUpdate() checkGameOver() def fastSnake(): while alive: fastSnakeGetDirection() moveSnake() gameUpdate() checkGameOver() def aStarSnake(): while alive: aSta...
The code presents a menu for selecting different snake simulation types (e.g., Human Snake, fast Snake, A* Snake, etc.) and directs the user's choice to corresponding functions. It loops until a valid input is received, then executes the selected simulation function, with placeholder 'pass' statements for unimplemented...
def chooseSnake(): snake = 0 while snake == 0: print("What Snake simulation would you like to play?") print(" 1. Human Snake") print(" 2. fast Snake") print(" 3. A* Snake") print(" 4. Hamaltonian Snake") print(" 5. Hamaltonian skip Snake") print(" 6. Ham...
def aStarFailTest(loop): failedSeeds = [] for i in range(loop): print(i) worldData = randomWorldGen() seed = worldData[5] Start = Tile(worldData[1],"self") End = Tile(worldData[2],"self") walls = [] for wall in worldData[3]: walls.append(T...
This code tests failed seeds using the A* algorithm by initializing game worlds for each failed seed, rendering the game window, and handling delays. It checks up to 5 batches of seeds, processes world data, and prints results, with a focus on debugging or validating game pathfinding mechanics.
def test1(): loop = 5 failedSeeds = aStarFailTest(loop) if failedSeeds: #load seed #initialie vars for seed in failedSeeds: worldData = loadSeed(seed) Start = Tile(worldData[1],"self") End = Tile(worldData[2],"self") walls ...
def get_intent(self, user_input): self.erase() while not self.intent: try: self.get_intent_(user_input) # user_input except Exception: user_input = query_user("I haven't recognized your intent. Please try again: ") def is_query_intent(self): ...
The main task of the code is to process user input by determining its intent and routing it to the appropriate handler: querying if it's a query intent, or handling non-query tasks otherwise, after displaying a welcome message.
def handle_intent_(self, welcome_message="Welcome to the CDL-Assistant. How can I help you?"): user_input = query_user(welcome_message) self.get_intent(user_input) if self.is_query_intent(): return self.handle_query_intent() else: return self.handle_non_query_inte...
def create_primes_sheet(wb, nlist): primes_ws = wb.add_sheet("Prime Factorizations") for num in range(1, len(nlist)): primes_ws.write(num, 0, num) for index, factor in enumerate(nlist[str(num)]["factors"]): primes_ws.write(num, index + 1, factor) def create_twin_primes_sheet(wb, nlis...
The main task of the code is to generate an Excel workbook containing three sheets: primes, twin primes, and their factorizations, using input data from `nlist`, and save it with a filename incorporating an environment variable for versioning.
def create_workbook(nlist): wb = xlwt.Workbook() create_primes_sheet(wb, nlist) create_twin_primes_sheet(wb, nlist) create_twin_primes_factorizations_sheet(wb, nlist) worksheet_version = os.getenv("WORKSHEET_VERSION") wb.save(f"primes-{worksheet_version}.xls")
def angle (a, b, c): return math.degrees(math.acos((c**2 - b**2 - a**2)/(-2.0 * a * b))) def getSimilarityValues(self, faceList, ratioMinMatrix, ratioMaxMatrix, myAngles, otherAngles, comparedZAngles): """ THESHOLD COMPARISONS """ # These are basically arbitrary and can be fine-tuned to acc...
The code compares two 3D meshes by calculating distance ratios, normalized min/max differences, and angular discrepancies between corresponding vertices and faces. It generates similarity metrics for the original mesh and expanded shapes (via neighbor iterations), returning a list of comparison results for each expansi...
def compare(self, otherMesh, timesToGetNeighbors = 1): # This is going to be the workhorse of the program. # Logic can be added here for any comparison, but it will all have to be done in ratios # We can divide each distance by the other mesh's at the same [i][j] position to get the ratios ...
def broadcast_error( message ): #print( message ) express_publish( { "channel": "errors" , "message": message } ) def express_publish( options ): options[ 'list_key_prefix' ] = "sleep.raspi.python." + options[ 'channel' ] try: print( options[ 'message' ] ) response = requests.post( 'http://localhost:80/python-s...
The code performs real-time motion detection using background subtraction, tracking motion events via frame differencing and contour analysis. It logs motion thresholds, manages event pools for timing validation, and triggers alerts (via publish commands) based on configurable thresholds. Additional checks ensure alert...
def motionTracking( self ): avg = None firstFrame = None min_area = 500 delta_thresh = 5 motionCounter = 0 #self.simulate_motion() while( self.w_Capture.isOpened() ): ( grabbed , frame ) = self.w_Capture.read() if not grabbed: broadcast_error( "Can't Connect to PI Camera" ) sleep( 1 )...
def broadcast_log( message ): #print( message ) express_publish( { "channel": "events" , "message": message } ) def update_loaded_config( config ): if 'EMAIL_COOLOFF' in config: LOADED_CONFIG[ 'EMAIL_COOLOFF' ] = config[ 'EMAIL_COOLOFF' ] if 'MIN_MOTION_SECONDS' in config: LOADED_CONFIG[ 'MIN_MOTION_SECONDS' ] ...
The code's __init__ method initializes a motion tracking system by setting up variables for event tracking, configuring parameters from a config file, starting video capture from a webcam, and initiating motion detection. It logs status, manages motion event thresholds, and prepares for motion analysis and alert handli...
def __init__( self ): broadcast_log( "python --> motion_simple_rewrite_fixed.py --> init()" ) self.write_thread = None self.EVENT_TOTAL = -1 self.EVENT_POOL = [] self.ExtraAlertPool = [ datetime.now( eastern_tz ) - timedelta( minutes=59 ) ] * 8 self.total_motion = 0 self.video_index = 0 self.last_em...
def broadcast_error( message ): send_web_socket_message( "python-new-error" , message ) def broadcast_event( message ): send_web_socket_message( "python-new-event" , message ) def send_web_socket_message( type , message ): try: json_string = json.dumps( { "type": type , "message": message } ) print ( json_string...
The code performs real-time motion detection using background subtraction. It tracks motion over time, triggers alerts when motion exceeds thresholds, and manages event pooling with cooldowns. It processes camera frames, detects movement via contour analysis, and sends alerts via WebSocket/Twilio based on time interval...
def motionTracking( self ): avg = None firstFrame = None min_area = 500 delta_thresh = 5 motionCounter = 0 while( self.w_Capture.isOpened() ): ( grabbed , frame ) = self.w_Capture.read() if not grabbed: broadcast_error( "Can't Connect to PI Camera" ) sleep( 1 ) break frame = imut...
def broadcast_error( wMsgString ): send_web_socket_message( "python-new-error" , wMsgString ) def broadcast_event( wMsgString ): send_web_socket_message( "python-new-event" , wMsgString ) def send_web_socket_message( wType , wMsgString ): xJString = json.dumps( { "type": wType , "message": wMsgString } ) ...
The code performs real-time motion detection using background subtraction. It captures video frames, applies grayscale conversion and Gaussian blur, calculates frame differences, thresholds changes, and identifies contours. If motion exceeds a threshold, it logs events, checks time intervals between motions, and trigge...
def motionTracking( self ): avg = None firstFrame = None min_area = 500 delta_thresh = 5 motionCounter = 0 while( self.w_Capture.isOpened() ): ( grabbed , frame ) = self.w_Capture.read() if not grabbed: broadcast_error( "Can't...
def broadcast_event( wMsgString ): send_web_socket_message( "python-new-event" , wMsgString ) def make_folder( path ): try: print( "Trying to Make Folder Path --> " ) print( path ) os.makedirs( path ) except OSError as exception: pass def motionTracking( self ): avg ...
The code initializes a motion detection system by setting parameters for motion thresholds, managing event tracking, creating video recording directories, and starting camera capture. It configures motion event limits, recording durations, and cooldowns for alerts, while preparing file structures to store motion-trigge...
def __init__( self ): broadcast_event( "python --> motionSave.py --> init()" ) self.write_thread = None self.EVENT_TOTAL = -1 self.EVENT_POOL = [] self.ExtraAlertPool = [ datetime.now( eastern_tz ) - timedelta(minutes=59) ] * 8 self.total_motion = 0 self.video...
def build_static_network(city): """Construct the atops & connection network of the transport system from all the routes""" # Get the list of routes and stops for this city routes_list = get_routes_list(city) print("Found " + str(len(routes_list)) + " routes") # Hold all the stops and their connections stops_lis...
The main task of the code is to execute network-building operations based on command-line arguments. It processes inputs like "static," "distances," "times," "clean," or "all" to build networks, calculate distances, times, or clean data for a specified city. The script uses sys.argv to handle arguments, with "help" dis...
def main(): """Execute the main actions of the network builder program Args: static - build the static network of stops and connections between them distances - calculate the straight-line and road distances between stops city - the city for which we want to get results """ # With the "static" argument,...
def calculate_trip_uniform(G, routes_list, stops_list, connections_list, radius, sample_size, repetitions): cutoff_high_deg = 0.0072 # 800m cutoff_low_deg = 0.0036 # 400m # Adjust the result by 30% due to greedy path bias adjustment_weight = 0.7 lat_list = [float(stop['lat']) for stop in stops_list] lon_list ...
The code calculates comprehensive metrics for a city's transportation network, including route/stops/connections counts, average travel speeds, wait times, trip times (uniform/population-based), normalized distances, coverage analysis, and connectivity measures, using input data and graph structures to evaluate urban m...
def calculate_city_metrics(G, routes_list, stops_list, connections_list, city, sample_size, repetitions): sectors_list = read_demographics_file(cities[city]['tag']) # Area and earth radius presets radius = cities[city]['radius'] area = cities[city]['area'] metrics = {} # ----------- General Statistics ------...
def draw_static_network(G,stops_list): nx.draw_networkx( G, node_size=0.1, with_labels=False ,edge_color="#AAAAAA" ,node_color="black" ,arrows=False ,pos=convert_stops_to_positions(stops_list)) # plt.show() # print("Bridges:") bridges, G2 = get_graph_bridges(G) # # print(bridges) nx.draw_network...
The code's main task is to execute network visualization tasks based on command-line arguments. It handles four modes: (1) drawing static networks, (2) calculating Points of Interest (POI) statistics for specified cities, (3) computing network metrics (e.g., connectivity, coverage) for multiple cities and saving result...
def main(): """Execute the main actions of the network visualizer program Arguments: static - draw the static network city - """ # With the "draw" argument, draw the network if len(sys.argv) > 2 and (sys.argv[1] == "draw" or sys.argv[1] == "-d" ): draw_static_network(G,stops_list) # With the "poi" a...
def terminal_test(board): return all(all(cell != EMPTY for cell in row) for row in board) def heuristic_look_for_corners_and_center(board, player): value = 0 for i in range(8): for j in range(8): if board[i][j] == player: if (i == 0 and j == 0) or (i == 7 and j == 7) or \...
This function implements the Minimax algorithm with Alpha-Beta pruning and a heuristic to evaluate board states. It recursively explores valid moves, prioritizing corner and center positions via a heuristic. For maximizing players, it selects the move with the highest evaluation, updating alpha; for minimizing players,...
def Min_Max_Alpha_Beta_Heuristic_Pruning_heuristic_1(board, depth, player, alpha, beta, maximizing_player): if depth == 0 or terminal_test(board): return heuristic_look_for_corners_and_center(board, player), 0 valid_moves = get_valid_moves(board, player) if maximizing_player: max_val = ...
def terminal_test(board): return all(all(cell != EMPTY for cell in row) for row in board) def heuristic_look_for_corners_and_borders(board, turn): value = 0 for i in range(8): for j in range(8): if board[i][j] == turn: if (i == 0 and j == 0) or (i == 7 and j == 7) or \ ...
This function implements the Minimax algorithm with alpha-beta pruning and a heuristic evaluation. It evaluates board states using a heuristic focused on corners and borders, recursively exploring valid moves to determine the optimal strategy for the current player while pruning suboptimal branches to enhance efficienc...
def Min_Max_Alpha_Beta_Heuristic_Pruning_heuristic_2(board, depth, player, alpha, beta, maximizing_player): if depth == 0 or terminal_test(board): return heuristic_look_for_corners_and_borders(board, player), 0 valid_moves = get_valid_moves(board, player) if maximizing_player: max_val =...
def initialize_board(): board = [[EMPTY] * N for _ in range(N)] board[3][3] = BLACK board[3][4] = WHITE board[4][3] = WHITE board[4][4] = BLACK return board def print_board(board): print(" A B C D E F G H") print(" 0 1 2 3 4 5 6 7") for i in range(N): row = str(i) + " " ...
This function implements a turn-based Othello game where two players take turns inputting moves. It validates moves against available positions, alternates players after each valid move, and declares a winner or tie when the board is full. The game displays the board, tracks scores, and enforces rules like passing turn...
def play_othello_vs_player(): board = initialize_board() current_player = BLACK while True: print_board(board) print("Actual player:", "X" if current_player == BLACK else "O") if current_player == BLACK: while True: try: row = ...
def terminal_test(board): return all(all(cell != EMPTY for cell in row) for row in board) def get_score(board): black_score = sum(row.count(BLACK) for row in board) white_score = sum(row.count(WHITE) for row in board) return black_score, white_score def get_valid_moves(board, player): valid_moves = ...
This function implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for a player in a game. It recursively evaluates all valid moves, alternating between maximizing and minimizing players, while pruning branches that cannot influence the final decision. The function returns the best eva...
def Min_Max_Alpha_Beta(board, player, alpha, beta, maximizing_player): global COUNTER COUNTER += 1 if terminal_test(board): return get_score(board)[1], 0 valid_moves = get_valid_moves(board, player) if maximizing_player: max_val = float('-inf') best_move = None f...
def initialize_board(): board = [[EMPTY] * N for _ in range(N)] board[3][3] = BLACK board[3][4] = WHITE board[4][3] = WHITE board[4][4] = BLACK return board def print_board(board): print(" A B C D E F G H") print(" 0 1 2 3 4 5 6 7") for i in range(N): row = str(i) + " " ...
This function implements a game of Othello where a human player (BLACK) competes against an AI (WHITE) using the minimax algorithm. It alternates turns, validates moves, handles user input, and determines the winner based on tile counts when the board is full.
def play_othello_vs_AI(): board = initialize_board() current_player = BLACK while True: print_board(board) print("Actual player:", "X" if current_player == BLACK else "O") if current_player == WHITE: row, col = get_min_max_move(board, current_player, 3) ...
def initialize_board(): board = [[EMPTY] * N for _ in range(N)] board[3][3] = BLACK board[3][4] = WHITE board[4][3] = WHITE board[4][4] = BLACK return board def print_board(board): print(" A B C D E F G H") print(" 0 1 2 3 4 5 6 7") for i in range(N): row = str(i) + " " ...
This function simulates an Othello game between two AI players using Minimax algorithms with different heuristics. It initializes the board, alternates turns between BLACK and WHITE, selects moves via get_min_max_move (heuristic 1 for WHITE) and get_min_max_move_heuristic_2 (heuristic 2 for BLACK), updates the board, a...
def play_othello_AI_vs_AI(): board = initialize_board() current_player = BLACK while True: print_board(board) print("Actual player:", "X" if current_player == BLACK else "O") if current_player == WHITE: row, col = get_min_max_move(board, current_player, 3) ...