dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def load_config(infile): # loads up an input file with open(infile, 'r') as fin: return json.load(fin) def parse_config_create_scan(raw_scan): ''' Parses the input from the json file into one or more MagnetScan objects ''' these_scans = [] for name,x in raw_scan['scans'].items():...
The code exports scan data from a configuration file into multiple JSON files. It loads the input configuration, generates scans, converts each to a specific format, and saves them as separate JSON files with incremental indices. If the output file lacks a .json extension, it is added. Each scan's set points are logged...
def export_scans(infile, outfile): config = load_config(infile) these_scans = parse_config_create_scan(config) exported_scans = [export_scan_to_wavedaq_format(x) for x in these_scans] if('.json' not in outfile): outfile += '.json' for i,x in enumerate(exported_scans): print(f"Export...
def factorial(n): return 1 if (n==1 or n==0) else n*factorial(n-1) def countSame(word): count = [] pos = 0 while pos<len(word): value = word.count(word[pos]) if value>1: count.append(value) pos += value - 1 pos+=1 value = 1 for val in count: ...
This code calculates the lexicographical rank of a given word by sorting its letters, iterating through permutations, and using factorial math to determine its position among all possible arrangements. It validates input, handles recursion for errors, and computes the rank by comparing each character's position in the ...
def start(message = None): print("\n**********************************************************") if message:print(f"{message}\n**********************************************************") word = input("Enter a Word : ") if not len(word):start("Type a Word!") if not word.isalpha():start("Only al...
def get_resources_json_obj(resource_name: str) -> Dict: """ Get a JSON object of a specified resource. :param resource_name: The name of the resource. :returns: The JSON object (in the form of a dictionary). :raises Exception: An exception is raised if the specified resources does not exist. ...
(The main task of the code is to download a gem5 resource to a specified file path, verifying its integrity via MD5 hash and handling unzipping if required. It ensures no duplicate downloads by locking the process, checks for existing files, and replaces outdated or invalid files. The function manages both downloading ...
def get_resource( resource_name: str, to_path: str, unzip: bool = True, download_md5_mismatch: bool = True, ) -> None: """ Obtains a gem5 resource and stored it to a specified location. If the specified resource is already at the location, no action is taken. :param resource_name: The r...
def _instantiate_numerical_pipeline(trial: Trial) -> Pipeline: """ Instantiate and return a pipeline for numerical features. Args: - trial (optuna.trial.Trial): The Optuna trial object. Returns: - Pipeline: An instance of the scikit-learn Pipeline class. """ pipeline = Pipeline([ ...
This function creates a preprocessing pipeline using scikit-learn's ColumnTransformer, combining numerical and categorical data processing pipelines. It optionally applies feature selection to both feature types based on the 'select' parameter. The numerical and categorical pipelines are instantiated with trial paramet...
def _instantiate_processor(trial: Trial, numerical_features: List[str], categorical_features: List[str], select: bool=False) -> ColumnTransformer: """ Instantiate and return a ColumnTransformer for preprocessing. Args: - trial (optuna.trial.Trial): The Optuna trial object. - numerical_features (Li...
def _base(self): return self.BASE_PROMPT.format( tools_str = self._make_tools_str(self.tools), final_goal = self.final_goal, current_tasks = self.current_tasks, final_result = self.final_result, stored_info=self.stored_info ) def load_json(self...
This method processes a completed task's result by updating internal state (tasks, stored info, final results), checking if the goal is achieved, and persisting changes if enabled. It uses an LLM to refine task outcomes, updates tracking variables, and triggers completion logic when the goal is met, returning True if t...
def refine(self, task_name: str, task_result: str): """ Use this after a task has been completed. This will update the current_tasks, final_result, stored_info, and completed_tasks - saving if persist is set. Uses base prompt plus `self.REFINE_PROMPT`. Returns True if goal has been met. :param ...
def _base(self): return self.BASE_PROMPT.format( tools_str = self._make_tools_str(self.tools), final_goal = self.final_goal, current_tasks = self.current_tasks, final_result = self.final_result, stored_info=self.stored_info ) def load_json(self...
The main task of the code is to check if a goal is completed by querying an LLM with a prompt, updating final results and tasks based on the response, and triggering completion handling if the goal is achieved. It updates internal states, outputs progress, and returns True if the goal is completed, otherwise False.
def ensure_goal_complete(self): prompt = self._base() + self.ENSURE_COMPLETE_PROMPT resp = self.llm(prompt) res = self.load_json(resp) if (final_result := res.get('final_result')): if self.verbose: self.output_func(f'[system] new final result: {final_result}'...
def input_matrix(m): matrix = [] for el in range(m): matrix.append(list(map(int, input().split()))) return np.array(matrix) def input_vector(): return list(map(int, input().split())) def first_step_simplex_method(matrix_a, vector_b, m, n): for i in range(m): if vector_b[i] < 0: ...
The code implements the **simplex method** for solving linear programming problems. It reads input parameters (matrix, vectors), applies the first step of the simplex algorithm, and checks the solution's feasibility. The main task is to determine if the problem is **unbounded**, has **no solution**, or is **bounded** w...
def simplex(): m, n = map(int, input().split()) matrix_a = input_matrix(m) vector_b, vector_c = input_vector(), input_vector() vector_x = first_step_simplex_method(matrix_a, vector_b, m, n) if vector_x is None: return "Unbounded" elif len(vector_x) == 0: return "No solution" ...
def input_matrix(m): matrix = [] for el in range(m): matrix.append(list(map(int, input().split()))) return np.array(matrix) def input_vector(): return np.array(list(map(int, input().split()))) def first_and_second_step_simplex_method(matrix_a, vector_b, vector_c): m = len(matrix_a) n = l...
The code implements the simplex method to solve a linear programming problem. It reads the problem's constraints matrix, right-hand side vector, and objective function coefficients. The `first_and_second_step_simplex_method` computes the solution, determining if the problem is unbounded, has no solution, or returns the...
def simplex(): m, n = map(int, input().split()) matrix_a = input_matrix(m) vector_b = input_vector() vector_c = input_vector() vector_x = first_and_second_step_simplex_method(matrix_a, vector_b, vector_c) if vector_x is None: return "Unbounded" elif len(vector_x) == 0: retu...
def getDataFiles(dataFolder, filePrefix=''): """Get the data files generated on maya Args: dataFolder (str): folder path where the files were saved filePrefix (str, optional): prefix name to the saved files Returns: tuple: (inputs (np.array), outputs(np.array)) """ csvIn = ...
The code trains a neural network model on normalized input/output data, saves the trained model in ONNX format, and stores normalization parameters (means/stds) in a zip file for later use in the ml_rivet node. It processes data from `dataPath`, splits it into training/validation sets, configures training hyperparamete...
def train(outPath, dataPath, valPercent=.1, epochs=1000, prefixFileName=''): """train the model with the pre generated data and save the model and normalize data ready to be used on the ml_rivet node Args: outPath (str): folder where to save the model and dat...
def start_to_drognan(): move_and_click(1114, 846) # walk to and interact with drognan move_and_click(1253, 344) def shop_open_weapons_tab(): for btn_weapons_tab_filename in ( 'btn_weapons_tab.png', 'btn_weapons_tab2.png', 'btn_weapons_tab3.png', 'btn_weapons_tab4.png'): btn_weapons_tab ...
This function automates a shopping loop in a game, handling initial setup, repeated item searches, and session limits. It logs durations, manages counters (buy/session limits), and terminates when thresholds are met, with first_walk handling initial steps.
def main_shopping_loop(first_walk=False): time_total_start = time.time() if first_walk is True: time_start = time.time() start_to_drognan() shop_open_weapons_tab() search_items() time_stop = time.time() log_shopping_session(time_stop - time_start) while Tru...
def new_board(): """ The function new board() takes no parameters and returns a fresh board configuration representing the Reversi starting position. """ empty_outer_board = [] empty_inner_board = [] board_length = 8 for i in range(board_length): empty_inner_board.append(0) ...
The main task of the code is to run a two-player Reversi (Othello) game, allowing players to take turns entering moves, validating them, updating the board state, and ending the game when no valid moves remain, with an option to quit at any time. It handles input validation, alternates turns, and displays the board and...
def run_two_players(): print("Welcome to REVERSI |TWO PLAYER !!!!| If you want to quit type 'q'") input_text = " " fresh_board = new_board() while input_text != "q": print(print_board(fresh_board)) if valid_moves(fresh_board, 1) != []: # Checks if its valid player = 1 ...
def new_board(): """ The function new board() takes no parameters and returns a fresh board configuration representing the Reversi starting position. """ empty_outer_board = [] empty_inner_board = [] board_length = 8 for i in range(board_length): empty_inner_board.append(0) ...
The code implements a single-player Reversi (Othello) game where the human player competes against an AI. It alternates turns, validates moves, updates the board, and selects the AI's optimal move by evaluating potential positions. The game ends when no valid moves remain, displaying the final score and a thank-you mes...
def run_single_player(): print("Welcome to REVERSI |SINGLE PLAYER !!!!| If you want to quit type 'q'") input_text = "" fresh_board = new_board() while input_text != "q": print(print_board(fresh_board)) if valid_moves(fresh_board, 1) != []: player = 1 print("Player...
def inbetweenStones(list,currentPlayer): # switch the players around cause the other python files switches it if currentPlayer == 1: currentPlayer = 2 else: currentPlayer = 1 for i in list: gui.create_circle(225 + (i[0] * 50), 175 + (i[1] * 50), 24, screen, currentPlayer) #d...
The code handles a left-click event in a Reversi game, calculating board coordinates to validate and execute moves for the current player (1 or 2). It updates the board state, switches players, visualizes new stones, and updates scores. If no valid moves remain for a player, it transitions to the other player. The game...
def left_click(event): global reversiBoard , player posx=event.x posy = event.y rounded_x = (int((posx - 200) / 50)) rounded_y = (int((posy - 150) / 50)) value_in_tuple = (rounded_x,rounded_y) # if player == 1 and there not more turns then let the other player play its turn if value_in...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--folder_path', type=str, default = "../levels_transposed/", help = 'folder_path') parser.add_argument('--save_folder_path', type=str, default='../levels_prediction_textfiles/',help='Output data file path') parser.add_argument('--...
The code trains a GPT-2 model on text data using specified hyperparameters, evaluates it on validation/test sets, and saves the model when validation loss improves. It loads data, initializes the model/optimizer/scheduler, resumes from checkpoints if available, and logs training/validation/test losses while generating ...
def run_model(): args = parse_args() #writer = SummaryWriter(args.log_path,filename_suffix='MarioGPT',comment=get_hyperparameter_string(args)) data_logger = logging.getLogger('Get-Data') train, val, test, char_indices, indices_char = data_from_text_files(args, data_logger) if args.testchanges: ...
def imgCompare(imageA, symbols_array, im_array,items=False): ssim_array = [] xyz= resizeimage.resize_cover(imageA, [tile_h, tile_w]) xyz.save(temp_path) xyz=cv2.imread(temp_path) xyz=cv2.cvtColor(xyz, cv2.COLOR_BGR2GRAY) if items: xyz = cv2.Canny(xyz,0,10) #xyz = exposure.equalize_ad...
The code processes an image by dividing it into tiles, comparing each tile against predefined symbols/items to identify characters, detecting flags and castles, updating matrices with enemy locations, and handling long tiles. It constructs a 2D matrix representation of the processed image, removes castle columns, and r...
def process_image(im): (maxX,maxY) = im.size maxX=int(maxX/tile_h)*tile_h maxY=int(maxY/tile_w)*tile_w image_matrix = [] image_matrix_horiz = [] flag=False castle_cols=[] n_cols = 0 for x in range (16,maxX,tile_h): local_column = [] counter=0 prev_item=defaul...
def roi_grid_pool(self, batch_dict): """ Args: batch_dict: batch_size: rois: (B, num_rois, 7 + C) point_coords: (num_points, 4) [bs_idx, x, y, z] point_features: (num_points, C) point_cls_scores: (N1 + N2 + N3 +...
The code processes 3D point cloud data through multiple pooling strategies (RoI Grid, Point, Voxel) to extract features for object detection. It fuses these features, applies classification and regression heads, and handles both training (assigning targets, pseudo/valid feature processing) and inference (generating pre...
def forward(self, batch_dict): """ :param input_data: input dict :return: """ targets_dict = self.proposal_layer( batch_dict, nms_config=self.model_cfg.NMS_CONFIG['TRAIN' if self.training else 'TEST'] ) if self.training: targets_d...
def process_data(dir): data = np.loadtxt(dir, delimiter=",", dtype=str) var_names = data[0] var_names = [var_name.replace('"', "") for var_name in var_names] data = data[1:] data = data.astype(float) var_to_indx = {var_name:indx for indx, var_name in enumerate(var_names)} var_to_r = {var_n...
The main task of the code is to find the optimal Bayesian network structure for a given dataset by iteratively evaluating shuffled data, comparing network scores, and updating the best network and score when a higher-scoring structure is found. The function processes input data, initializes a Bayesian network, and refi...
def best_bayesian(file): vars_info, D = process_data(f"data/{file}.csv") G_best, G_best_score = find_bayesian_network(vars_info, D) for i in range(BAYESIAN_ITERATIONS): # RANGE IS SET TO ZERO print("-----------running iteration ", i, " ---------------") shuffled_vars, shuffled_D = shuffle(va...
def get_weights(self): return np.copy(self.weights) def score(self, inputs, targets, alt_weights=None): # FIXME use alt_weights input for temporary weights temp = self.get_weights() if alt_weights is not None: self.weights = alt_weights predictions = self.predict(inpu...
This code trains a model by iteratively adjusting weights using gradient descent. It processes input-output pairs, updates weights when predictions mismatch targets, and tracks performance. Shuffling and multiple epochs are supported. The best weights are retained if they improve the score, and the function returns the...
def fit(self, inputs, targets, learning_rate, do_shuffle=False, deterministic=False, epochs=10): # expect inputs to be an array of arrays of features # expect targets to be an array of targets, one per array of features best_weights = self.get_weights() count = 0 old_score = 0.0 ...
def parseArgs(): ap = argparse.ArgumentParser(description="Convert dull Loki logs to meaningful data and ingest to ElasticSearch!", epilog="Good, wasn't it?!") ap.add_argument("--file", metavar="File to import", required=True, help="Input the logfile to use for an import") ap.add_argument("--host", metavar...
The main task of the code is to parse log files and send them to an Elasticsearch instance, either locally or remotely. It parses command-line arguments, configures the Elasticsearch connection based on the specified mode, reads the log file, and processes the logs using the `parseLogs` function. The script ensures all...
def init(): args = parseArgs() if args['mode'] == "local": esConn = "localhost" #TODO: See if this can be avoided else: esConn = configureElk(args['host'], args['port']) filePtr = open(args['file']) parseLogs(filePtr, esConn, args['mode']) print("INFO: Quitting. All logs hav...
def get_clusters_project_tag(selected_region): clusters_with_projects = [] all_eks_clusters = list_eks_clusters(selected_region) for item in all_eks_clusters: region = item[0] eks_client = init_boto3_client('eks', region) for cluster_name in item[1]: try: ...
The code fetches EKS cluster information based on a specified project and region. It retrieves all clusters if "All" is selected, otherwise filters by the project. For each cluster, it gathers nodegroup details, compiles cluster data, and returns a list of EKS cluster info with region and nodegroups, handling errors gr...
def fetch_all_eks_info(project, selected_region): if project == 'All': all_eks_clusters = get_clusters_project_tag(selected_region) else: all_eks_clusters = filter_clusters_by_project(project, selected_region) print('[INFO] Fetching EKS Clusters Info Related to Project:', project) all_e...
def fetch_all_eks_info(project, selected_region): if project == 'All': all_eks_clusters = get_clusters_project_tag(selected_region) else: all_eks_clusters = filter_clusters_by_project(project, selected_region) print('[INFO] Fetching EKS Clusters Info Related to Project:', project) all_e...
The function processes EKS cluster data by fetching information, analyzing node group configurations, checking scheduled actions for auto-scaling groups, determining cluster states, and generating structured table rows with details like cluster name, region, sizes, status, schedules, and timezone for display.
def process_table_rows(project, selected_region): try: all_eks = fetch_all_eks_info(project, selected_region) rows = [] i = 1 for eks in all_eks: cluster_name = eks[0] region = eks[1] ng_names = [] min_sizes = [] max_sizes =...
def get_classes_idx(im): """ Function that returns buildings and roads indexes in image """ # Threshold and get class idx r = np.where(im == 2, 255, 0) b = np.where(im == 1, 255, 0) class_im = np.stack([r, np.zeros((im.shape[0], im.shape[1])), b]).transpose((1, 2, 0)).astype(np.uint8) bu...
The main task of the code is to generate warped labels by aligning drone or satellite images using correspondence maps. It processes image pairs, resizes them, computes flow fields via NNS, reconstructs labels, and saves outputs. Debug mode visualizes distance maps, flow fields, and scores. The function handles configu...
def main(data_dir, sat_dir, drone_dir, label_dir, output_dir, img_type, ref_type, use_my_rs, use_my_init, debug, itr, p_size, new_w, new_h, img_names=[]): """ Main function for generating the warped labels. """ debug_folder = 'debug_viz' sat_path = os.path.join(data_dir, sat_dir) drone...
def get_btc_symbols(self): symbols = self.get_all_symbols() pattern = re.compile("^([A-Za-z])*BTC$") btc_symbols = [i for i in symbols if pattern.match(i)] return btc_symbols def get_file_name(self,btc_symbol,interval=" 15 minute"): if 'data' in str(pathlib.Path.cwd()): ...
The code downloads Bitcoin (BTC) k-line data for specified time intervals and date ranges. It checks if pre-existing pickle files for each BTC symbol exist; if not, it fetches the k-line data using `get_klines`, then serializes and saves the data into pickle files for storage. The task ensures data is only retrieved wh...
def download_btc_klines(self, interval=Client.KLINE_INTERVAL_15MINUTE, start_str="1 May, 2017", end_str=None): btc_symbols=self.get_btc_symbols() btc_klines = {} for btc_symbol in btc_symbols: filename=self.get_file_name(btc_symbol) if os.path.isfile(filename): ...
def virtual_shortest_move(): global snake, board, snake_size, template_snake, template_board, template_snake_size, food template_snake_size = snake_size template_snake = snake[:] template_board = board[:] reset_board(template_snake, template_snake_size, template_board) food_eated = False while not food_eated: ...
The main task of the code is to determine a safe movement direction for a snake in a game by evaluating reachability to its tail and selecting the shortest safe path if possible, or alternatively following the tail if the shortest path isn't viable.
def find_safe_way(): global snake, board safe_move = ERROR virtual_shortest_move() if is_tail_reachable(): return choose_shortest_safe_move(snake, board) safe_move = follow_tail() return safe_move
def get_available_device(): """ Allows training on GPU if available. Can help with running things faster when a GPU with cuda is available but not a most... Given a device, one can use module.to(device) and criterion.to(device) so that all the computations will be done on the GPU. """ return...
The function trains a log-linear model using one-hot encoded input representations for text classification. It initializes a DataManager with one-hot averaged features, creates a LogLinear model with vocabulary size, trains it for specified epochs with given learning rate and weight decay, plots training metrics, and e...
def train_log_linear_with_one_hot(n_epochs, lr, weight_decay): """ Here comes your code for training and evaluation of the log linear model with one hot representation. """ name = f"Log-linear average one-hot encoding, n_epochs: {n_epochs}, lr: {lr}, weight_decay: {weight_decay}" print("*" * 20) ...
def get_available_device(): """ Allows training on GPU if available. Can help with running things faster when a GPU with cuda is available but not a most... Given a device, one can use module.to(device) and criterion.to(device) so that all the computations will be done on the GPU. """ return...
This function trains a log-linear model using pre-trained Word2Vec embeddings for text classification. It initializes a model with specified hyperparameters (epochs, learning rate, weight decay), loads averaged Word2Vec embeddings via DataManager, trains the model, visualizes training metrics, and evaluates test perfor...
def train_log_linear_with_w2v(n_epochs, lr, weight_decay): """ Here comes your code for training and evaluation of the log linear model with word embeddings representation. """ name = f"Log-linear average Word2Vec encoding, n_epochs: {n_epochs}, lr: {lr}, weight_decay: {weight_decay}" print("*" ...
def get_available_device(): """ Allows training on GPU if available. Can help with running things faster when a GPU with cuda is available but not a most... Given a device, one can use module.to(device) and criterion.to(device) so that all the computations will be done on the GPU. """ return...
This function trains an LSTM model using Word2Vec-encoded sequences, evaluates its performance over specified epochs with given learning rate and weight decay, plots training metrics, and retrieves test results. It initializes the model architecture, loads data via DataManager, and executes training with hyperparameter...
def train_lstm_with_w2v(n_epochs, lr, weight_decay): """ Here comes your code for training and evaluation of the LSTM model. """ name = f"LSTM Word2Vec encoding, n_epochs: {n_epochs}, lr: {lr}, weight_decay: {weight_decay}" print("*" * 20) print(name) print("-" * 20) hidden_dim = 100 ...
def getCurrentCustomer(self, ID): try: self.cIndex = self.customerData['ID'].index(str(ID)) self.currentCustomer = self.customerData['Customers'][self.cIndex] self.cFlag = True except ValueError: print('The selected customer does not exist within the datab...
The code modifies a customer's reservation by updating check-in and check-out dates. It checks if the customer exists, retrieves their booked rooms, cancels the existing reservation, re-adds the customer, and applies new dates. If the update fails, it reverts to the original dates. If no rooms are booked or the ID is i...
def modifyReservation(self, ID, newInDate, newOutDate): #find customer by ID index, go to that customer if self.getCurrentCustomer(ID): rooms = self.currentCustomer.returnCustomerRooms() if rooms: #Store old data incase modification not successful ...
def is_beginning(self, a): return self.order(a) == 0 def is_next(self, a, b): """consecutive within one occurence of one gloss""" return self.s2g(a) == self.s2g(b) and self.order(b) - self.order(a) == 1 def is_exiting(self, a, b): return self.is_ending(a) and self.is_beginning(b) def col...
The code evaluates a sequence of elements to determine a score based on transitions between consecutive elements. It returns 1 if elements are consecutive, applies a penalty (lm(collapsed list)^alpha) if they signal an exit, and returns 0 otherwise. The function checks if a single-element list marks a beginning, using ...
def mslm(l): if len(l) == 1: return self.is_beginning(l[-1]) a, b = l[-2:] if self.is_next(a, b): return 1 elif self.is_exiting(a, b): return lm(self.collapse(l)) ** alpha return 0
def set_pose(self,pose): #Set the character's current pose if pose not in self.images: raise ValueError(f"Pose '{pose}' not found in images.") self.current_pose = pose self.image = self.images[self.current_pose] def updateBoss(self): #handle jumping and gravity ...
The code's main task is to initiate an attack action by setting the character's pose to "attack," updating either the boss or regular state based on the `onFinalBoss` flag, and returning the character's strength parameter (`self.strengthP`) for potential use in damage calculation or state tracking.
def attack(self): self.set_pose("attack") if self.onFinalBoss: self.updateBoss() else: self.update() return self.strengthP
def set_pose(self,pose): #Set the character's current pose if pose not in self.images: raise ValueError(f"Pose '{pose}' not found in images.") self.current_pose = pose self.image = self.images[self.current_pose] def updateBoss(self): #handle jumping and gravity ...
This method handles an attack event by reducing the object's health based on the attack strength, setting a "hurt" pose, and triggering either a boss-specific or standard update to reflect the damage.
def attacked(self,strengthP): self.set_pose("hurt") self.healthP -= strengthP if self.onFinalBoss: self.updateBoss() else: self.update()
def set_pose(self,pose): #Set the character's current pose if pose not in self.images: raise ValueError(f"Pose '{pose}' not found in images.") self.current_pose = pose self.image = self.images[self.current_pose] def updateBoss(self): #handle jumping and gravity ...
The main task of the code is to set the object to a blocking state by enabling `is_blocking`, updating its pose to "block", and conditionally triggering either `updateBoss()` or `update()` based on whether the final boss is active. This likely handles state transitions and animation logic in a game or simulation contex...
def block(self): self.is_blocking = True self.set_pose("block") if self.onFinalBoss: self.updateBoss() else: self.update()
def set_pose(self,pose): #Set the character's current pose if pose not in self.images: raise ValueError(f"Pose '{pose}' not found in images.") self.current_pose = pose self.image = self.images[self.current_pose] def updateBoss(self): #handle jumping and gravity ...
The code's main task is to transition an object from a blocking state to a non-blocking state by setting `is_blocking` to False, resetting its pose to "idle", and triggering either `updateBoss()` or `update()` based on whether it's interacting with a final boss. This handles state management and visual/behavioral updat...
def unblock(self): self.is_blocking=False self.set_pose("idle") if self.onFinalBoss: self.updateBoss() else: self.update()
def threatened(player, opponent, table): if [player["alpha"]["x"], player["alpha"]["y"]] in perimeter(table, opponent["alpha"]["x"], opponent["alpha"]["y"], 1): return True if "omega" in opponent and [player["alpha"]["x"], player["alpha"]["y"]] in perimeter(table, opponent["omega"]["x"], opponent["omega...
The function generates movement and attack orders for a player's units (alpha, omega, normal) in a game, prioritizing fleeing threats, eating nearby food, attacking opponents, and chasing the opponent's alpha, while managing energy levels and spatial positioning.
def get_AI_orders(player, opponent, table, foods): cmd = "" alpha = 0 omega = 0 for ww in player["normal"]: ww["ord"] = 0 # if alpha is threatened (opponent ww in 1 cell perimeter) : pacify if threatened(player, opponent, table) == True: if "omega" in player: cmd += s...
def check_valid_index(ar, i): try: ar[i] return True except IndexError: return False def chopdata(stringy): chopind = 0 workable_data = {} key_place = "" data_place = "" while check_valid_index(stringy, chopind): while stringy[chopind] != '"': chop...
The code parses a string into a tree structure (`ATree`), where nodes store data extracted from the string. It processes the input character by character, collecting text until encountering `{` or `}`. When `{` is found, a new node is inserted into the tree, and parsing continues recursively. The function constructs th...
def new_tree(stringy): tree = ATree() node = tree.insert() textind = 0 while check_valid_index(stringy, textind): # empty node data and empty key placeholder newstring = "" # while no new start of node or end of node while stringy[textind] != "{" and stringy[textind] != "...
def _prepare_interfaces(machine_cidrs: List[str], provisioning_cidrs: List[str], count: int) -> List[Dict[str, str]]: primary_interface = _prepare_interface(_PRIMARY_LOGICAL_INTERFACE, machine_cidrs, count) secondary_interface = _prepare_interface(_SECONDARY_LOGICAL_INTERFACE, provisioning_cidrs, count) ret...
The function generates static network configuration data for a host, creating interface settings, DNS resolver configurations, and routing rules based on provided CIDR ranges. It maps primary/secondary MAC addresses to logical interfaces and returns the configuration as a YAML-formatted string along with the MAC-to-int...
def _prepare_host_static_network_data( primary_mac: str, secondary_mac: str, machine_cidrs: List[str], provisioning_cidrs: List[str], count: int ) -> Dict[str, List[dict]]: interfaces = _prepare_interfaces(machine_cidrs, provisioning_cidrs, count) dns_resolver = _prepare_dns_resolver(machine_cidrs) rout...
def _prepare_bonded_interfaces( machine_cidrs: List[str], provisioning_cidrs: List[str], count: int, num_bonded_slaves: int, bonding_mode: str ) -> List[Dict[str, Any]]: primary_interface = _prepare_bonded_interface("bond0", 0, machine_cidrs, count, num_bonded_slaves, bonding_mode) secondary_interface = _pr...
The function generates a host's bonded static network configuration by creating bonded interfaces, DNS resolver settings, and routing rules. It maps provided MAC addresses to logical NIC names (eth0, eth1, etc.) and returns a dictionary containing YAML-formatted network config and the MAC-to-interface mapping for provi...
def _prepare_host_bonded_static_network_data( primary_macs: List[str], secondary_macs: List[str], machine_cidrs: List[str], provisioning_cidrs: List[str], count: int, num_bonded_slaves: int, bonding_mode: str, ) -> Dict[str, Any]: interfaces = _prepare_bonded_interfaces(machine_cidrs, pr...
def resolved(x): return realpath(abspath(x)) def badpath(path, base): # joinpath will ignore base if path is absolute return not resolved(joinpath(base, path)).startswith(base) def badlink(info, base): # Links are interpreted relative to the directory containing the link tip = resolved(joinpath(base...
This function filters and validates file members, logging blocked entries to a logfile. It checks for illegal paths, invalid hard links, and invalid symlinks, yielding only valid members.
def safemembers(members, logfile): base = resolved(".") for finfo in members: if badpath(finfo.name, base): print(stderr, finfo.name, "is blocked (illegal path)", file=logfile) elif finfo.issym() and badlink(finfo, base): print(stderr, finfo.name, "is blocked: Hard link ...
def build_data(self): """Builds the data used by the bot into the correct format Returns: dict: Dictionary containing codes and price objects """ data = {} for code in self.get_codes(): value = self.call_api(crypto=code) data[code] = { ...
The code processes data from an API call by building and formatting price data, updating current prices, and checking for potential buy/sell opportunities using dedicated methods. It orchestrates data flow through `stat_bot`, updates internal state, and triggers decision-making logic for trading actions.
def process_data(self): """ Processes prices from api call """ data = self.build_data() self.stat_bot.process_incoming(data) self.update_current_prices(self.format_data(data)) self.check_sell(data) self.check_buy(data)
def update_prices(self, code, new_prices): """Helper function which updates the old_prices given new ones Args: old_prices (dict): old prices of a given stock code new_prices (dict): new prices of a given stock code """ old_prices = self.get_price(code) ...
The main task of the code is to process incoming stock data by updating price information, recalculating moving averages, and computing RSI (Relative Strength Index) values for each stock code in the provided dictionary. This function iterates through the input data, applying three key operations to maintain updated fi...
def process_incoming(self, incoming_data): """Process incoming stock codes and their corresponding price actions Args: incoming_data (dict): data of stock codes and price information """ # print(incoming_data) for key in incoming_data: self.update_prices(...
def FormationLinearWander(self, bots): if self.currentlyTurning == True: #if the bot is in the process of turning self.vl = -2.0 self.vr = 2.0 #turns to the left self.turning -= 1 #keep track of how many t...
This function determines a robot's movement behavior based on a formation code. If not faulty, it sets the formation code and executes corresponding strategies: linear wander, random wander, bisector search, quadrant search, or repel behavior, depending on the code value.
def brain(self, bots, code): #AUTHORS: Dept of Computer Sci @ UoN + Yash Suresh , 2023 if self.isFaulty == False: self.formationCode = code if(self.formationCode == 'lw'): self.FormationLinearWander(bots) elif(self.form...
def determine_candidate_numeric_splits(D): # set of training instances D, feature X ######### if DEBUG: print("determine_candidate_numeric_splits()") ######### C = [] if len(D) <= 1: # Leaf node return C for Xi in [0, 1]: # assuming only 2 features D = sort_data...
The code recursively constructs a decision tree subtree by evaluating numeric feature splits. It determines candidate splits, checks stopping criteria (e.g., pure dataset), and selects the best split via gain ratio/info gain. If stopping criteria are met, it returns a leaf node with the majority class. Otherwise, it re...
def make_subtree(D, root=False): # Only used for Section 2 question 3 if root: C = determine_candidate_numeric_splits(D) for c in C: gain_ratio, S, split_feature, split_value = get_gain_ratio_of_C(c, D) info_gain_c = info_gain(D, S) print('candidate split: spl...
def trim_transition_matrix(arm, labeling, new_nodes): assert len(arm.get_transition_matrix()) == len(labeling) for action in [0,1]: for i in range(len(arm.get_transition_matrix())): for j in new_nodes: if not consistent_succ(labeling[i],labeling[j],action): ...
The code simulates a step in a state machine by updating the arm's internal state, tracking histories (state, sensations, actions), updating labeling sequences with sensations and actions, checking for contradictions in labeling, and splitting nodes if contradictions are found. It maintains the arm's transition matrix,...
def step(arm, labeling, state_hist, sense_hist, action_hist, action): state_hist.append(arm.get_current_internal_state()) sense_hist.append(arm.is_desired_position_reached()) labeling[state_hist[-1]].append(dict({'sensations': list([]), 'actions':list([])})) num...
def set_csrf_token(self): params = { 'api_version': '1.0', 'api_token': 'null', 'input': 3, 'method': 'deezer.getUserData' } resp = self.session.post( url=settings.PRIVATE_API_URL, params=params ) if resp.s...
The code processes an album by setting a CSRF token, retrieving album information, downloading the album cover if available, executing step 2 with the album data, and generating SFV/M3U files for media organization.
def run(self): self.set_csrf_token() album_info = self.step_1() if album_info['cover_big']: self.album_art = self.download_album_art(album_info['cover_big']) self.step_2(album_info) self.create_sfv_and_m3u()
def getDF(self): # API if not isinstance(self._df, pd.DataFrame) or self._df.empty: self.setDF() df = self._df if 'alpha' in df: df = df.drop('alpha', axis=1) return df def getPortDF(self): # API return self._portDF.drop(['trades'], axis=1) def getTrades(self): Trades = ...
The code's main task is to create a portfolio by either loading cached results or generating new data from strategies. It processes strategies to calculate performance metrics (PnL, Sharpe ratio), ranks them, and stores results in a DataFrame. The DataFrame is sorted by rank, saved to a cache file, and logged if config...
def createPortfolio(self): args = self.args fss,dfRDCache = [],None if hasattr(self.args,'nodates') and self.args.nodates: fss = glob.glob(PNLPortfolio.dataPath+'/cache/p{}DF_*.pkl'.format(self.Sym)) else: fss = glob.glob(PNLPortfolio.dataPath+'/cache/p{}DF_{}-{}....
def settings(args): # Print a table from the data in the argument file. if args.print != None: if re.search(r"^.+\.csv$", args.print): if path(args.print).is_file(): utilities = Utilities.update(Utilities.read(args.print)) print(utilities) ...
This code processes utility readings (electricity, gas, water) from a CSV file, allowing users to input new readings with date validation, merge data from two files, and save updates. It reads CSV data, validates user inputs, checks for duplicates, and updates the dataset, then outputs the results in a formatted table ...
def main(): # Set the optional arguments. parser = argparse.ArgumentParser(description="This program read and write set of readings of utilities (Electricity, Gas, Water) from the default utilities.csv file") parser.add_argument( "-f", "--file", default="utilities.csv", hel...
def u(x,c,xi,w): #computes u(x) as in eqn (17) dim1,dim2 = xi.shape return np.sum(w*np.reshape(np.exp(-0.5*c*np.linalg.norm(x-xi, axis=1)**2),(dim1,1))) def gradient_u(x,c,xi,w): #computes the gradient vector $\nabla \phi_i(x)$ as in the paper return -c*g(x,c,xi,w) def hessian_u(x,c,xi,w): #comp...
The function `dudt` computes the time derivative $\partial u/\partial t$ using the gradient, Hessian, and Laplacian of a function $u(x;c,\xi,w)$. It applies a weighted combination of the Laplacian of $u$ and a directional curvature term (involving gradient and Hessian), normalized by the gradient's magnitude, then subt...
def dudt(x,c,xi,w,y,lambdas): #computes each entry of the vector $\partial u / \partial t$ in the paper #you may decide to use the automatic differentiation functions for the gradient, Laplacian and Hessian operators uu=u(x,c,xi,w) gu=gradient_u(x,c,xi,w) hu=hessian_u(x,c,xi,w) lu=laplacian_u(x,...
def get_pc(self): return self.updi.load_direct(OCD_PC, data_width=WIDTH_WORD)-1 def set_pc(self, pc: int): self.updi.store_direct(OCD_PC, (pc+1) & 0xFFFF, data_width=WIDTH_WORD) def raw_stepping(self): origregval = self.updi.load_direct(OCD_TRAPENL) self.updi.store_direct(OCD_TRAPENL, or...
This code adjusts the program counter (PC) by decrementing it if non-zero, then performs a raw stepping operation. If the PC remains unchanged after stepping, it executes another raw step, likely handling edge cases or debugging scenarios where the PC doesn't advance as expected, ensuring proper execution flow.
def step(self): # TODO: verify this curpc = self.get_pc() if curpc != 0: self.set_pc(curpc-1) self.raw_stepping() if self.get_pc() == curpc: # PC didn't move; we haven't hit the OCD bug. one more stepping self.raw_stepping()
def __find_server(self): while self.is_alive: try: # wait for options data, address = self.udp_socket.recvfrom(self.buffer_size) message = struct.unpack(self.udp_format, data) except struct.error: continue if mes...
The code initializes a UDP socket to listen for incoming connections, continuously attempts to connect to a server using the found IP and TCP port, and upon successful connection, starts the game loop. It handles connection failures by retrying, ensuring persistent connection attempts until established.
def start(self): self.is_alive = True # open udp listener self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # TODO: SO_REUSEPORT was SO_REUSEADDR self.udp_socket.bind(("", self.udp_port)) ...
def __giveGuildDataIfNotExists(self, guild: discord.Guild): if self.__guildDataExists(guild): return self.__execute("INSERT INTO Configuration VALUES (?, ?)", guild.id, json.dumps({})) def __loadConfig(self, guild: discord.Guild) -> dict|None: # setup self.__giveGuildDataIfN...
This function saves a configuration value for a specific Discord guild by updating its configuration data in a database. It ensures the guild's data exists, loads the current configuration, updates the specified key-value pair, and executes an SQL update to persist the changes.
def save(self, guild: discord.Guild, name: str, value: any): # setup self.__giveGuildDataIfNotExists(guild) # get data config = self.__loadConfig(guild) # none check if config is None: return # save config value config[name] = value ...
def hide_error_message(self): self.ui.email_address_error.setVisible(False) self.ui.no_password_error.setVisible(False) self.ui.to_error.setVisible(False) self.ui.invalid_col_error.setVisible(False) self.ui.invalid_byte_size_error.setVisible(False) def send_email(self, compulsory...
The code initializes a GUI window for an email application, connecting UI components to logic for handling file attachment, email sending, error messages, and status updates. It sets up event handlers for user interactions, links signals from the logic module to error-displaying functions, and integrates with a model f...
def __init__(self, model, logic): QMainWindow.__init__(self) self.logger = logging.getLogger(__name__) self.model = model self.logic = logic self.ui = Ui_MainWindow_Extend() self.ui.setupUi(self) self.close_window = CloseWindow() self.preview_...
def init_camera_pose(self): print("------ initialize camera pose ------ \n") if self.initial_type == "random": initial_view = utils.uniform_sampling(self.radius, self.phi_min) elif self.initial_type == "pre_calculated": self.get_view_list() initial_view = ne...
The code's main task is to initialize a camera's position, iteratively plan and execute sensor movements within a predefined budget limit, and record the experimental results after completing all planned views.
def start(self): self.init_camera_pose() while self.step < self.budget: next_view = self.plan_next_view() self.move_sensor(next_view) self.record_experiment()
def randapplegen(): randappleX = round(random.randrange(0, display_width - applethickness)) randappleY = round(random.randrange(0, display_height - applethickness)) return randappleX, randappleY def message_to_screen(msg, color, y_displace=0, size="small"): textsurf, textRect = text_objects(msg, color, ...
This code implements a Snake game loop using Pygame, handling player input for movement, collision detection with walls/self, apple generation, snake growth mechanics, and game over/restart logic. The loop updates the game state, renders graphics, and maintains the game flow until exit.
def gameloop(): global direction gameExit = False gameOver = False lead_x = display_width / 2 lead_y = display_width / 2 lead_x_change = 0 lead_y_change = 0 snakelist = [] snakelength = 1 randappleX, randappleY = randapplegen() while not gameExit: while gameOver ==...
def get_test_dir(project_name, script_name, id): return f"{projects_dir}/{project_name}/locust/{script_name}/{id}" def create_task_id(project_name, script_name, id): return f"TASK${project_name}${script_name}${id}" def is_port_in_use(port): # checks if a port is in use. used to distribute work with socket....
This code handles Locust load testing project management: uploading projects, setting up virtual environments, running tests, monitoring statuses, managing tasks via subprocesses, and using Redis for caching. It supports test execution, data retrieval, cleanup, and task termination, ensuring proper resource handling an...
def handle(req, no_request=False): global REDIS global EXPIRE # we try the code block here to catch the error and get it displayed with the answer otherwise we get "server error 500" with no information about the error, could be removed after debugging phase try: if not no_request and "file0" in...
def driver_update_available(driver: Driver, drivers_path: str = DRIVERS_PATH) -> bool: """Returns True if no downloaded driver exists which matches latest release""" if not os.path.exists(os.path.join(drivers_path, _get_driver_executable_name(driver))): return True installed = _get_downloaded_versi...
The function `spoof_browser` creates and configures a WebDriver instance for mobile user agent spoofing. It checks for driver updates, initializes the browser with a timeout, disables screenshot-saving if prohibited, and returns the customized WebDriver for mobile device emulation.
def spoof_browser(driver: Driver, headless: bool, drivers_path: str = DRIVERS_PATH, allow_screenshots: bool = False) -> WebDriver: """ Returns appropriate WebDriver... CHROME device is spoofed with specified user agent for mobile """ if driver_update_available(driver, drivers_path): download...
def tmp_check(): ''' creates the tmp file/dir if doesn't exist ''' version_loc = load_config()['version_loc'] version_loc_dir = '/'.join(version_loc.split('/')[:-1]) # version folder doesn't exist, make it if not path.exists( version_loc_dir ): mkdir( version_loc_dir ) # version...
The main task of the code is to determine if an update is available by comparing the last recorded version with the current version. It returns `True` if they differ (indicating an update is needed) and `False` if they match (no update required). The function first calls `tmp_check()` for preliminary checks before perf...
def has_updated(): ''' returns the comparison of last and current versions ''' tmp_check() if last_version() == get_version(): return False return True
def generateSharedKey(selfPrivateKey, publicGenerator, publicKey, bigA, usePlainTextCSV = False, plainTextCSVFileName = ""): '''Generate a shared key given your own private key, the public key, public generator, and the "Big A" value: generator**(other person's private key) % public key''' B = (publicGenerator*...
This code implements a Diffie-Hellman key exchange interface for encrypting/decrypting messages using a Vernam cipher. It allows users to choose between encryption (1) or decryption (2), inputs required parameters (public keys, Diffie-Hellman values), generates a shared key, applies the Vernam transformation to a CSV f...
def mainDiffieHelmanInterface(): print("Encrypt a message [1]") print("Decrypt a message [2]") encryptDecryptGate = input(": ") if encryptDecryptGate == "1": privateKey = 115249 generator = 5 publicKey = input("Other person's public key (Fontaine's is 10007): ") if public...
def get_disjoint_pairs_with_max(keys, max0, max1): for disjoint_pairs in all_disjoint_pairs(keys): if ((max0, max1) in disjoint_pairs) or ((max1, max0) in disjoint_pairs): return disjoint_pairs return [] def create_rows(n, m, keys): rows = [] for _ in range(n * m): rows.appen...
The main task of the code is to generate all possible combinations of parameter values into structured rows, prioritizing pairs with the largest parameter lists. It creates rows by iterating through disjoint pairs, filling combinations of values, and handling remaining pairs with random selections. The function ensures...
def generate_tuples(parameters): if (len(parameters.keys()) % 2 != 0): parameters['dummy'] = [] keys = list(parameters.keys()) max0 = keys[0] max1 = keys[1] for key in keys[1:]: if len(parameters[key]) >= len(parameters[max0]): max1 = max0 max0 = key e...
def get_width(tree): """ :param tree: :return: """ if tree.tb is None and tree.fb is None: return 1 return get_width(tree.tb) + get_width(tree.fb) def get_depth(tree): """ :param tree: :return: """ if tree.tb is None and tree.fb is None: return 0 return ma...
The main task of the code is to generate a visual representation of a tree data structure as a JPEG image. It calculates the image dimensions based on the tree's width and depth, creates a white canvas, draws the tree nodes recursively using `draw_node`, and saves the result to the specified file. The function converts...
def draw_tree(tree, jpeg='tree.jpg'): """ :param tree: :param jpeg: :return: """ w = get_width(tree) * 100 h = get_depth(tree) * 100 + 120 img = Image.new('RGB', (w, h), (255, 255, 255)) draw = ImageDraw.Draw(img) draw_node(draw, tree, w // 2, 20) img.save(jpeg, 'JPEG')
def workflow(self, parameter_list): message = self.filename message += self.separator + str(parameter_list) message += self.separator + str(list(self.my_inputs)) message += self.separator + str(self.my_outputs) if self.origin: message += self.separator + str(self.orig...
The code runs combinatorial experiments based on input parameters, collects results via ZMQ communication, evaluates parameter effectiveness, and iteratively refines experiment sets to determine optimal outcomes, returning decisive results and experiment counts.
def run(self, filename, input_dict, outputs): self.my_inputs = input_dict.keys() self.my_outputs = outputs self.filename = filename self.allexperiments, self.allresults, self.pv_goodness = load_runs(self.filename.replace(".vt", ".adb"), ...
def generate_data_interventions(self,bad_dataframe,good_dataframes): def compute_score(row,b,g): return min(row['score'],abs(row[b]-row[g])) columns = good_dataframes[0].columns max_diff_columns = {} column_dataframes = {} for c in columns: df = pd.Dat...
The code identifies a decisive column and its indices in a 'bad' dataset by iteratively replacing it with data from 'good' datasets, using interventions to detect differences. It narrows down potential candidates through binary search-like key reduction, then returns the column and indices deemed responsible for discre...
def run(self, filename, input_dict, bad_dataset, good_datasets, outputs): bad_dataframe = pd.read_csv(bad_dataset) good_dataframes = [pd.read_csv(file).select_dtypes(include='number') for file in good_datasets] input_dict['dataset'] = bad_dataset self.my_inputs = input_dict.keys() ...
def findallpaths(node): q = queue.Queue() q.put((node, [])) puregoodpaths = [] purebadpaths = [] input_dict = {} while (not q.empty()): current = q.get() if current[0].results is None: key = current[0].col value = current[0].value if key in in...
The code simplifies a decision tree by eliminating redundant paths using the Quine-McClusky algorithm. It converts paths into binary terms, reduces them if the feature count is ≤10, and translates simplified terms into conditions based on input keys. If features exceed 10, it retains original paths. The result is a lis...
def prune_tree(t, keys): """ Simplifies a decision tree by reducing redundant paths by Quine-McClusky. :param t:the decision tree to be simplified :param keys: the name of the parameters represented by the features of the tree. :return results: a list with non-redundant paths of the tree, if possibl...
def register_forward_hook(module: nn.Module, path: ModulePathsLike, hook: Callable) -> RemovableHandleCollection: """Registers forward hooks on submodules of a module. Args: module: The root module to read `named_modules()` from. path: A string or strings indicating which modules to attach ...
This function runs a neural network module, enabling dynamic activation tracking and hook registration for forward/backward passes. It temporarily applies hooks to capture activations, replace values, or record outputs, then executes the module with provided inputs. Afterward, it cleans up hooks and returns the model o...
def run(module: nn.Module, *args, return_activations: ModulePathsLike = None, with_activations: ActivationCacheLike = None, forward_hooks: dict[ModulePathsLike, Callable] = None, forward_pre_hooks: dict[ModulePathsLike, Callable] = None, full_backward_hooks: dict[ModuleP...
def get_formula_int(formula, symbols): symbols = sorted(symbols) symbols_map = dict((symbols[i - 1], i) for i in range (1, len(symbols) + 1)) symbols_int = set(symbols_map.values()) formula_int = [] for clause in formula: formula_int.append(set(get_literal_int(literal, symbols_map) for lite...
The main task of the code is to solve a Boolean formula using the DPLL algorithm with a specified strategy. It converts the input formula and symbols into an internal representation, applies the DPLL algorithm to determine satisfiability, and returns the result as a string.
def solve(strategy, formula, symbols): formula_int, symbols_int = get_formula_int(formula, symbols) result = dpll(strategy, formula_int, symbols_int, {}) return get_result_string(result)
def csv_open(csv_file): '''receives a csv file and returns a df''' return pd.read_csv(csv_file, sep='\t') def list_input_IP(df): '''receives a list of df and returns two lists of lists of tuples containing the GSM and GSM title for each input and IP samples per series (each sublist is...
The main task of the code is to process GEO data by reading a TSV file, extracting input/IP lists, checking GSE similarities, calculating distances, filtering results, and generating a final DataFrame with added columns. The output is saved as a tab-separated CSV file.
def main(): df = csv_open(sys.argv[1]) #GEO-Dataframe tsv path = sys.argv[2] #Output file big_list_input, big_list_IP = list_input_IP(df) checking_similarity_gse(big_list_input,big_list_IP) big_data = create_big_data(big_list_IP) dict_dist = count_dist(big_list_input,big_data) filtered_list...
def __fold(self): """ Simulates the user folding in Texas Hold 'em, where all money in the pot goes to the computer """ self._computerMoney += self._currentPot self._currentPot = 0 self._currentWager = self._MINIMUM_BET_WAGE self._currentBeingRisked = 0 self.__update...
This function handles mouse click events to trigger player actions in a game. It checks if the computer has a turn or if the round has ended, then processes fold, call, raise, or exit actions based on which clickable button is hovered.
def mouseButtonDown(self, x, y): """ This function is called whenever the mouse button is clicked :param x: the x-coordinate of the mouse :param y: the y-coordinate of the mouse """ # You can't execute a turn when it's the computer's turn if self._computerHasTurn:...
def write_attr(self, attr, val): f = open(PWM_BACKLIGHT + '/' + attr, 'wb') f.write(str(val).encode('ascii')) f.close() def on_pwm(self, v): if v: self.write_attr('brightness', PWM_BRIGHTNESS_ON) else: self.write_attr('brightness', PWM_BRIGHTNESS_OFF) def on_gpio(self, v): if v: self.write_string(L...
The code initializes an LCD device by opening it in write-only mode, sets the backlight to on, checks for PWM backlight support, disables auto-brightness, and activates PWM and GPIO controls for backlight management.
def __init__(self, lcd_dev): self.lcd = os.open(lcd_dev, os.O_WRONLY) self._backlight_on = True self.pwm_backlight = os.path.exists(PWM_BACKLIGHT) if self.pwm_backlight: self.write_attr('auto_brightness', 0) self.on_pwm(True) self.on_gpio(True)
def write_string(self, str): self.write(str.encode()) def on_pwm(self, v): if v: self.write_attr('brightness', PWM_BRIGHTNESS_ON) else: self.write_attr('brightness', PWM_BRIGHTNESS_OFF) def on_gpio(self, v): if v: self.write_string(LCD_BACKLIGHT_ON) else: self.write_string(LCD_BACKLIGHT_OFF)
This function controls the LCD backlight by setting its state based on the input value 'v'. If 'v' is True, it sends a home command to the LCD and activates the backlight using either PWM (if enabled) or GPIO. If 'v' is False, it deactivates the backlight through the same methods. The task involves managing backlight s...
def on(self, v): self._backlight_on = bool(v) if v: self.write_string(LCD_RETURNHOME) if self.pwm_backlight: self.on_pwm(v) else: self.on_gpio(v)
def centroids_init(self, k, X): n_samples, n_features = X.shape centroids = np.zeros((k, n_features)) for i in range(k): # random choose a center point in each iteration centroid = X[np.random.choice(range(n_samples))] centroids[i] = centroid return ce...
The code implements the K-means clustering algorithm by iteratively initializing centroids, assigning data points to clusters, updating centroids based on cluster means, and stopping when centroids stabilize or max iterations are reached. It returns cluster labels for the input data.
def kmeans(self, X, k, max_iterations): centroids = self.centroids_init(k, X) for _ in range(max_iterations): clusters = self.create_clusters(centroids, k, X) prev_centroids = centroids centroids = self.calculate_centroids(clusters, k, X) diff = centroid...
def prepare_dataset(df, bool_include, slice_include, exclude): #include_str = '' exclude_str = '' exclude_copy_df = df.copy(deep=True) for i in range(len(exclude)): exclude_copy_df = exclude_copy_df.loc[(exclude_copy_df[exclude[i][0]] != exclude[i][1])] exclude_str += exclude[i][...
The code generates two sets of bar charts comparing algorithm performance (time) on sparse and dense synthetic datasets, varying by density (0.10–0.60). It filters data using input parameters, creates pivot tables for each density level, and plots bar charts in 3x2 grids. Each chart visualizes time across synth_size va...
def two_charts(df, bool_include, slice_include, exclude): df, include_str, exclude_str = prepare_dataset(df, bool_include, slice_include, exclude) #####SPARSE##### sparse_010 = df.loc[(df['sparse'] == 1) & (df['synth_density'] == '0.10')] sparse_020 = df.loc[(df['sparse'] == 1) & (df['sy...
def prepare_dataset(df, bool_include, slice_include, exclude): #include_str = '' exclude_str = '' exclude_copy_df = df.copy(deep=True) for i in range(len(exclude)): exclude_copy_df = exclude_copy_df.loc[(exclude_copy_df[exclude[i][0]] != exclude[i][1])] exclude_str += exclude[i][...
The code generates bar charts comparing algorithm performance across different data densities (0.10 to 0.60) by pivoting time data, reordering columns, and plotting in a 3x2 grid. It filters datasets, prepares subsets, standardizes column order, and visualizes results with shared x-axes, density-specific titles, and a ...
def one_chart(df, bool_include, slice_include, exclude): df = df.loc[(df['algo_name'] != 'gpu_perman_xglobal')] df, include_str, exclude_str = prepare_dataset(df, bool_include, slice_include, exclude) #####SPARSE##### sparse_010 = df.loc[(df['synth_density'] == '0.10')] sparse_020 = df.loc[(d...
def prepare_dataset(df, bool_include, slice_include, exclude): #include_str = '' exclude_str = '' exclude_copy_df = df.copy(deep=True) for i in range(len(exclude)): exclude_copy_df = exclude_copy_df.loc[(exclude_copy_df[exclude[i][0]] != exclude[i][1])] exclude_str += exclude[i][...
This function generates grouped bar charts comparing time (y-axis) across different categories (bars) for varying density (multidimval) values. It processes input data, creates pivot tables, applies column reordering/color schemes, and plots subplots in a grid layout. The visualization highlights how density variations...
def general_graph(df, x, y, bars, multidimname, multidimval, bool_include, slice_include, exclude, title): ##x -> size ##y -> time (accuracy ?) ##multidim -> density df, include_str, exclude_str = prepare_dataset(df, bool_include, slice_include, exclude) df_list = [] for val in multidimval...
def prepare_dataset(df, bool_include, slice_include, exclude): #include_str = '' exclude_str = '' exclude_copy_df = df.copy(deep=True) for i in range(len(exclude)): exclude_copy_df = exclude_copy_df.loc[(exclude_copy_df[exclude[i][0]] != exclude[i][1])] exclude_str += exclude[i][...
The function generates a comparative bar graph visualizing time performance (y-axis) across varying input sizes (x-axis) and algorithm configurations (bars), segmented by a multidimensional parameter (e.g., density). It filters data, creates pivot tables, applies consistent column ordering/colors, and arranges plots in...
def cpus_graph(df, x, y, bars, multidimname, multidimval, bool_include, slice_include, exclude, title): ##x -> size ##y -> time (accuracy ?) ##multidim -> density df, include_str, exclude_str = prepare_dataset(df, bool_include, slice_include, exclude) df_list = [] for val in multidimval: ...
def prepare_dataset(df, bool_include, slice_include, exclude): #include_str = '' exclude_str = '' exclude_copy_df = df.copy(deep=True) for i in range(len(exclude)): exclude_copy_df = exclude_copy_df.loc[(exclude_copy_df[exclude[i][0]] != exclude[i][1])] exclude_str += exclude[i][...
This function generates grouped bar charts comparing time metrics across different density levels (multidim) by slicing data, creating pivot tables, and customizing visual elements like colors, hatches, and legends. It processes input data, organizes subplots, adjusts layouts, and applies specific labeling for multi-di...
def sparse_order_exclusive(df, x, y, bars, multidimname, multidimval, bool_include, slice_include, exclude, title): ##x -> size ##y -> time (accuracy ?) ##multidim -> density df, include_str, exclude_str = prepare_dataset(df, bool_include, slice_include, exclude) df_list = [] for val in mu...
def prepare_dataset(df, bool_include, slice_include, exclude): #include_str = '' exclude_str = '' exclude_copy_df = df.copy(deep=True) for i in range(len(exclude)): exclude_copy_df = exclude_copy_df.loc[(exclude_copy_df[exclude[i][0]] != exclude[i][1])] exclude_str += exclude[i][...
The code generates bar plots comparing metrics (y) across different dimensions (x and bars) for varying density levels (multidimval). It processes filtered data, creates pivot tables, applies color/hatch ordering, and arranges subplots in a grid with shared x-axes. Legends, titles, and axis labels are added for visuali...
def sparses_exclusive(df, x, y, bars, multidimname, multidimval, bool_include, slice_include, exclude, title): ##x -> size ##y -> time (accuracy ?) ##multidim -> density df, include_str, exclude_str = prepare_dataset(df, bool_include, slice_include, exclude) df_list = [] for val in multidi...
def snapping(difference): if difference < 101: snap = 4 elif difference < 201: snap = 2 else: snap = 1 return snap def differing(point_a, point_b): difference = point_b - point_a return difference def snap4_point_check(list, index): i = index n = i + 1 diff1 =...
The code processes a list by iterating through consecutive pairs, applying snapping logic to their difference, and generating new pairs based on the snapping result. It checks for specific snap values (4, 2, or others) to determine how to form 'couple1' and 'couple2', appending these to a new list. The loop advances th...
def go_through_list(list): i = 0 list2 = [] while (i + 1) < len(list): point_a = list[i] point_b = list[i+1] snap = snapping(differing(point_a, point_b)) if snap == 4: couple1 = snap4_point_check(list, i) elif snap == 2: couple1 = sna...
def initial_population(pop_size): population = [] for i in range(0, pop_size): population.append(create_X()) return population def rank_resistors(population): fitness_results = np.zeros(len(population)) for i in range(0, len(population)): fitness_results[i] = Fitness(population[i]).g...
The main task of the code is to implement a genetic algorithm that evolves resistor configurations to minimize error, either by running for a fixed number of generations or until a target error threshold is met. It initializes a population, iteratively generates new generations through selection, crossover, and mutatio...
def geneticAlgorithm(popSize, eliteSize, mutationRate, target_error=0.04, generations=500, runtime='target_error'): pop = initial_population(popSize) gens = [] gens.append(0) error = [] # print(rank_resistors(pop)) error.append(1 / rank_resistors(pop)[0, 1]) print("Initial Error: " + str...
def byte_cast(num_list): byte_list = [] # Find the max required number of bytes. byte_size = 0 for temp_num in num_list: byte_count = byte_len(temp_num) if byte_count > byte_size: byte_size= byte_count # Convert the numbers to signed big endian bytes. for temp_num in num_list: byte_new = temp_num.to_byte...
The main task of the code is to set up shared memory for parallel sorting using multiple child processes. It initializes shared memory segments for data storage, status flags, and a kill signal, configures initial flag states, forks child processes to perform sorting, coordinates their execution, and finalizes by dumpi...
def server_setup(file_data, child_count): # Convert our file data to the least needed byte amount. byte_data, byte_size = byte_cast(file_data) # Figure out the size of our shared memory sectors. mem_size_share = len(byte_data) * byte_size mem_size_flag = math.ceil(len(byte_data) / 100) # Setup our shared memory f...
def smush_cookies(): try: driver.get('https://www.semrush.com/') except TimeoutException: driver.execute_script("window.stop();") folder_path = 'smush_cookies' # Replace with the actual path to your folder # Use os.listdir to get a list of all files and directories in the folder fi...
The main task of the code is to scrape and extract SEO metrics (Authority Score, Organic Search Traffic, and Page Views) from Semrush for each website listed in a DataFrame. It uses Selenium to navigate websites, dynamically clean the page, capture screenshots, and update the DataFrame with extracted data. The code als...
def confirm_after_init(): smush_cookies() for index, row in df.iterrows(): website=False try: website=row['Website'] except: print("Issue: Row Number {index} skiped , can't found website") continue try: website =...
def _push_existing_to_childs(self, node_id: int) -> None: if not self._is_leaf(node_id) and self.arr[node_id] != self.default_func: # push existing function to child and replace with default cur_func = self.arr[node_id] self._push_func(cur_func, 2 * node_id + 1) s...
This function updates the left subtree of a node by recursively applying a function to nodes whose segments are contained within or intersect the desired segment, pushing existing data to children and handling splits in a tree structure.
def _update_left_from_split( self, desired_segment: Segment, cur_node: TreeNode, func: UNARY_FUNC ) -> None: self._push_existing_to_childs(cur_node.node_id) if cur_node.is_segment_contained_by(desired_segment): self._push_func(func, cur_node.node_id) else: r...
def _push_existing_to_childs(self, node_id: int) -> None: if not self._is_leaf(node_id) and self.arr[node_id] != self.default_func: # push existing function to child and replace with default cur_func = self.arr[node_id] self._push_func(cur_func, 2 * node_id + 1) s...
This function recursively updates tree nodes by applying a given function to nodes whose segments are either fully contained within or intersect with a desired segment, pushing the function to relevant child nodes during traversal.
def _update_right_from_split( self, desired_segment: Segment, cur_node: TreeNode, func: UNARY_FUNC ) -> None: self._push_existing_to_childs(cur_node.node_id) if cur_node.is_segment_contained_by(desired_segment): self._push_func(func, cur_node.node_id) else: ...
def _get_to_split_point(self, desired_segment: Segment) -> TreeNode: cur_node = TreeNode(node_id=0, left=0, right=self.num_leaves - 1) while not cur_node.is_leaf(): self._push_existing_to_childs(cur_node.node_id) left_child = cur_node.get_left_child() right_child = ...
This method updates a segment tree by applying a given function to a specified range [left, right]. It identifies the appropriate node to split, checks if it's a leaf or exactly matches the target segment, and applies the function directly if possible. Otherwise, it recursively updates left and right child nodes to pro...
def update(self, left: int, right: int, func: UNARY_FUNC) -> None: """ Applies the given function on the segment [left, right] """ desired_segment = Segment(left, right) split_node = self._get_to_split_point(desired_segment) if split_node.is_leaf() or split_node.is_segme...
def get_info(self): data = {'msg': 'PRODUCT_INFO', 'data': {'option': 0}} self.send_packet(data) def volume_up(self, ): data = {'msg': 'VOLUME_UP'} self.send_packet(data) def volume_down(self, ): data = {'msg': 'VOLUME_DOWN'} self.send_packet(data)
The main task of the code is to adjust the device's volume to a specified level. It first checks if the current volume is initialized, retrieving it if not. If the target volume is higher, it increments the volume step-by-step using `volume_up()`. If lower, it decrements using `volume_down()`. If the volume remains uni...
def set_volume(self, volume): if self.volume is None: self.get_info() time.sleep(1) if self.volume is None: # TODO define custom exception for this raise ValueError('Could not find volume to set it') if self.volume < volume: ...
def get_image(self): os.makedirs("covers/" + self.name.replace(":", ""), exist_ok=True) file_count = get_file_count("covers/" + self.name.replace(":", "")) if file_count == 0: response = requests.get("https://www.mobygames.com/search/?q=" + "%20".join(self.name.lower().split())) ...
This code initializes a class instance with attributes like name, rating, splits, platform, and finished status. It checks if a specific image file exists for the item; if not, it retrieves the image. The code then maps splits, verifies completion status, and constructs the image path. The comments parameter is also as...
def __init__(self, name, rating, splits, platform, finished, comments="a"): self.name = name self.rating = rating self.splits = splits self.platform = platform self.finished = finished self.image_index = 0 self.cover_index = 0 if not os.path.exists("covers...
def process_url(url): headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') text = soup.get_text() return t...
The function extracts text from a URL or uploaded file (handling PDFs with page range and cleaning) and generates a summary filename. It returns both the filename and extracted text, prioritizing URLs, then PDFs, else raw file content.
def get_text_and_summary_file(uploaded_file, url, page_range, clean_document): if url: summary_file = unquote(Path(urlparse(url).path).name) text = process_url(url) elif is_pdf(uploaded_file): summary_file = uploaded_file.name text = process_pdf(uploaded_file, page_range, clean_...
def get_reference(db_manager, modules, months): ticker = modules['default'][0] return get_asset_state(db_manager, ticker, months) def get_asset_state(db_manager, ticker, months): try: return _get_asset_state(db_manager, ticker, months) except NoData: return AssetState(ticker, False, 0, F...
The code retrieves and aggregates the states of specified modules by fetching each module's asset states from a database, combining them with a default state, and returning a structured dictionary of module states.
def get_modules_states(db_manager, modules, months): default_state = get_reference(db_manager, modules, months) res = {} for module, tickers in sorted(modules.items()): states = [ get_asset_state(db_manager, ticker, months) for ticker in tickers ] res[module] = get_mod...
def parse(*args, color=None, label=None): tr = [] style = '-' if len(args) in (1, 2): x = Missing() if len(args) == 1: y = args[0] elif isinstance(args[1], str) or \ isinstance(args[1], (tuple, list)) and len(args[0]) > 0 and \ isinstance(args[1]...
The function `plot` generates or updates a visualization (e.g., line plot, scatter plot) using input data (`*args`), customizable axes scales (logarithmic, datetime), colors, labels, and interactive elements (hover tooltips). It parses data into structured formats, validates consistency (e.g., x/y length, datetime comp...
def plot(*args, p=None, hover=False, mode='plot', hline=None, vline=None, color=None, hline_color='pink', vline_color='pink', xlabel=None, ylabel=None, label=None, legend_loc=None, notebook_handle=False, return_source=False, **kwargs): # print('(plot) FIGURE =', FIGURE) try: #s...
def add_nodes_to_seq(G, source, target, line_node_seq): stops_node_seq = nx.shortest_path(G, source=source.N, target=target.N, weight='length') stops_node_seq = [int(n) for n in stops_node_seq] if len(line_node_seq) != 0: line_node_seq.extend(stops_node_seq[1:]) else: line_node_seq.exten...
This function generates a sequence of nodes along a transit route by connecting stops, creating necessary nodes and links in the graph, and updating associated data structures when existing nodes are missing. It handles four cases: both nodes exist, only source exists, only target exists, or neither. For missing nodes,...
def create_node_seq(G, line_stops, transit_only_nodes_df, transit_only_links_df, transit_only_attributes, shp_id_line, nodes_within_shp_df, new_nodes_from, w_bffr, gtfs_stop_times_df, gtfs_stops_df, route_trip_id): line_node_seq = list() shp_distances = np.arange(0, shp_id_line.length, 30) shp_points = Mult...
def get_context(session_id, key): context = get_context_from_redis(session_id) return context.get(key) def set_response_text(conversation_response, list_of_texts): conversation_response[ANSWER] = list_of_texts[0] if len(list_of_texts) > 1: add_response_text(conversation_response, list_of_texts[...
The main task of the code is to provide a hint for a puzzle by checking the session context for required matrices, parsing user input parameters (row, column, ordinals, numbers), validating input sufficiency, determining values based on the action type, retrieving the correct solution value from the matrix, and setting...
def provide_hint(conversation_response, session_id): if get_context(session_id, PUZZLE_INPUT_MATRIX) is None: set_response_text(conversation_response, [get_response_text_for(I_DONT_HAVE_A_PUZZLE)]) elif get_context(session_id, PUZZLE_SOLUTION_MATRIX) is None: set_response_text(conversation_resp...
def get_context(session_id, key): context = get_context_from_redis(session_id) return context.get(key) def set_response_text(conversation_response, list_of_texts): conversation_response[ANSWER] = list_of_texts[0] if len(list_of_texts) > 1: add_response_text(conversation_response, list_of_texts[...
The main task of the code is to handle an uploaded image file for a puzzle-solving system. It checks if the puzzle has already been solved or exists in the session context. If not, it processes the image by converting it to grayscale, validates it, and triggers further processing if valid. The function updates the conv...
def process_uploaded_file(conversation_response, session_id, image_file, socket): if get_context(session_id, PUZZLE_SOLUTION_MATRIX) is not None: set_response_text(conversation_response, [get_response_text_for(IVE_ALREADY_SOLVED_IT)]) else: if get_context(session_id, PUZZLE_INPUT_MATRIX) is not ...
def set_context(session_id, key, value): context = get_context_from_redis(session_id) context[key] = value put_context_to_redis(session_id, context) def set_response_text(conversation_response, list_of_texts): conversation_response[ANSWER] = list_of_texts[0] if len(list_of_texts) > 1: add_r...
This function processes user input to extract a name or phrase following 'all me', stores it in session context, and generates a response using the extracted value. If no match is found, it uses the full input or a default response.
def call_me(conversation_response, session_id): new_call_me = None input_text = conversation_response[INPUT] if input_text is not None and len(input_text) > 0: found = input_text.find('all me') if found > 0: new_call_me = input_text[found+6:len(input_text)] found = ne...
def set_context(session_id, key, value): context = get_context_from_redis(session_id) context[key] = value put_context_to_redis(session_id, context) def set_response_text(conversation_response, list_of_texts): conversation_response[ANSWER] = list_of_texts[0] if len(list_of_texts) > 1: add_r...
The function updates the conversation response by formatting a predefined message with user input, stores the input in session context, and returns the modified response.
def call_me_fallback(conversation_response, session_id): new_call_me = conversation_response[INPUT].strip() set_context(session_id, PUZZLE_CALL_ME, new_call_me) set_response_text(conversation_response, [get_response_text_for(I_WILL_NOW_CALL_YOU) % new_call_me]) return conversation_response
def get_context(session_id, key): context = get_context_from_redis(session_id) return context.get(key) def set_response_text(conversation_response, list_of_texts): conversation_response[ANSWER] = list_of_texts[0] if len(list_of_texts) > 1: add_response_text(conversation_response, list_of_texts[...
The function solves a Sudoku puzzle by checking if a solution already exists in the session context. If not, it retrieves the input matrix, sends it to a Sudoku solver API, and stores the result. It updates the conversation response to indicate success, failure, or existing solutions, managing session context according...
def solve_puzzle(conversation_response, session_id): if get_context(session_id, PUZZLE_SOLUTION_MATRIX) is not None: set_response_text(conversation_response, [get_response_text_for(IVE_ALREADY_SOLVED_IT)]) else: if get_context(session_id, PUZZLE_INPUT_MATRIX) is None: set_response_t...
def log_sock_request(path, sock): log('>>>>>>>>>>>>>>>>>>>> In websocket %s' % path) remote_ip = sock.environ['REMOTE_ADDR'] remote_port = sock.environ['REMOTE_PORT'] server_name = sock.environ['SERVER_NAME'] server_port = sock.environ['SERVER_PORT'] log('Remote: %s:%s' % (remote_ip, remote_port...
The code handles file uploads via a socket by receiving JSON data containing a filename and session ID, logging the request, processing the uploaded image content, generating bot responses, updating a conversation transcript, and sending HTML updates. It also manages errors, sends fallback messages if processing fails,...
def uploader(sock): try: log_sock_request('/uploader', sock) input_str = sock.receive() input_json = json.loads(input_str) filename = input_json['filename'] session_id = input_json['session_id'] image_contents = sock.receive() log_sock_request('/uploader - fil...
def dvd_split_encode(input_filename, base_filename, folder_name): chapter_breakpoints = dvd_get_chapter_timestamps(input_filename) output_filename_list = [] executor = get_encoding_executor() futures = [] pad_count = len(str(len(chapter_breakpoints) - 1)) for index in range(len(chapter_breakp...
The main task of the code is to convert an input file into a DVD ISO image. It creates a temporary directory structure, splits and encodes the input file into DVD-compatible parts, authors the DVD structure, generates the ISO file, and then cleans up by removing the temporary directory. The function returns the name of...
def create_dvd(input_filename): base_filename = input_filename.rsplit(".", 1)[0] folder_name = base_filename + ".iso.temp" makedirs(f"{folder_name}/dvd", exist_ok=True) file_name_list = dvd_split_encode(input_filename, base_filename, folder_name) dvd_author_disk(folder_name, file_name_list) ...
def encode_all_files(): executor = get_encoding_executor() futures = [] file_list = glob("*.mkv") for file_name in file_list: input_filename = file_name output_filename = file_name.rsplit(".", 1)[0] + ".mkv" futures.append( executor.submit(video_crop_encode, input_...
This script processes video files based on command-line arguments. It either encodes videos into MKV format or creates DVDs, handling single files or batches. The 'encode' command processes input files, while 'make-dvd' generates DVDs using threading for multiple files.
def main(): parser = ArgumentParser(description="Get video information") parser.add_argument("command", help="What Are We Doin?") parser.add_argument("-i", "--input_filename", help="Input filename") args = parser.parse_args() print(args) if args.command == "encode": if not args.input_f...
def set_global(igfile, igcon): global ignore_programs, ignore_contracts ignore_programs = igfile ignore_contracts = igcon def dapp_analyzer(dapp_dic): dapps = [] for key in sorted(dapp_dic): idx, name = key.split('/') dapp = Dapp(name, idx) program_list = dapp_dic[key] ...
The code's main task is to execute an external analysis on dapps by initializing configurations, analyzing dapp structures, and logging results. It sets global variables, processes input files, runs dapp analysis, and triggers external analysis with the obtained data and log file.
def run_external(igfile, igcon): global FILE, EXT_LOG set_global(igfile, igcon) dapps = dapp_analyzer(dapp_init(init(FILE))) print('Dapps analyze finish.') external_analyze(dapps, EXT_LOG)
def set_global(igfile, igcon): global ignore_programs, ignore_contracts ignore_programs = igfile ignore_contracts = igcon def dapp_analyzer(dapp_dic): dapps = [] for key in sorted(dapp_dic): idx, name = key.split('/') dapp = Dapp(name, idx) program_list = dapp_dic[key] ...
The main task of the code is to analyze DApps by initializing configurations, performing analysis, comparing results based on the provided mode, conducting external analysis, and logging outcomes. It uses global variables for file and log handling, processes DApp data, and outputs analysis results with completion messa...
def main(mode, igfile, igcon): global FILE, LOG, EXT_LOG set_global(igfile, igcon) dapps = dapp_analyzer(dapp_init(init(FILE))) print('Dapps analyze finish.') compare(dapps, LOG, mode) external_analyze(dapps, EXT_LOG) print('Done.')
def preprocess(code): # comments filter res = [] i = 0 while i < len(code): line = code[i] j = 0 while j < len(line): word = line[j] if '//' in word: t_idx = word.index('//') if t_idx != 0: res.append(word[...
The main task of the code is to process an input file by initializing and preprocessing its content, creating a Program object with the processed code, analyzing the program structure, and returning the analyzed Program instance for further use or inspection.
def main(file): code = preprocess(init(file)) p = Program(file, code) analyze(p) return p
def find_square(self, c_x, c_y): """ given x and y coordinate, finds which square the left_click is in""" for square in self.squares: if square.in_square(c_x, c_y): return square t_x, t_y = self.find_border(c_x, c_y) for square in self.squares: i...
The code handles left mouse clicks to place colored pieces on a board, checks for valid positions, logs placements, updates the game state, and determines if the game has ended after each move.
def left_click(self, event): """ following certain playable rules, draws pieces onto the board upon left click""" if self.gameover: return color = "black" if not self.turn % 2 else "white" print(f"turn: {color}") square = self.find_square(event.x, event.y) ...