dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_normal_from_wobbles(self, draw_wobbles, input_wobbles, twist): point = self.get_point_from_wobbles(draw_wobbles, input_wobbles, twist) vel = sp.diff(point, draw_wobbles) tan = vector_normalize(vel) curv = sp.diff(tan, draw_wobbles) norm = vector_normalize(curv) ...
This function calculates an edge point from wobbles by determining two candidate points (vec1, vec2) offset from a base point along a normal vector. It compares their distances to the wobble center, then selects the appropriate point using a conditional based on distance comparison and internal parameter. The result is...
def get_edge_point_from_wobbles(self, draw_wobbles, input_wobbles, twist): normal_vec = self.get_normal_from_wobbles(draw_wobbles, input_wobbles, twist) center = self.get_wobble_center(input_wobbles) point = self.get_point_from_wobbles(draw_wobbles, input_wobbles, twist) vec1 = point + ...
def get_twist(self, input_wobbles): p = self.params return -input_wobbles*p.get_rot_per_wobble()*2*np.pi def get_bounding_wobs(self, input_wobbles, twist, point): teeth = self.params.teeth() mid = self.get_nearest_starting_point_wobs(input_wobbles, twist, point) wobbles_per_rot...
This function uses binary search to find the wobble value that minimizes the distance between a target point and an edge point calculated from wobbles. It iteratively adjusts bounds based on velocity direction and error magnitude, returning the optimal wob value when the error falls below a threshold.
def get_nearest_edge_point_wobs(self, input_wobbles, point, twist = None, target_dist=None, target_err = 0.000001, max_depth = 25): if target_dist == None: target_dist = self.params.pin_r if twist == None: twist = self.get_twist(input_wobbles) low_bound, high_bound = sel...
def write_alive_signal(self, status): self.check_pid() elapsed_time = time.time() - self.timeLastAliveSignal if elapsed_time < self.timeToWait and status != self.FINISHED: return self.write_status(status) self.timeLastAliveSignal = time.time() def store_face_names(sel...
The code's main task is to update system status, process face recognition data by dropping a column, log face changes, store recognized face names, and conditionally save face presentations if history retention is enabled.
def write_results(self, df_recognized, df_names): self.write_alive_signal(self.RUNNING) df_names.drop('directory', axis=1, inplace=True) logging.debug("faces have changed or where None before. Storing to file.") self.store_face_names(df_names) if self.keep_history: se...
def get_face_representations(self): # Load stored face representations df = None # pandas.DataFrame that holds all face representations if os.path.exists(self.file_embeddings): if os.stat(self.file_embeddings).st_size == 0: logging.debug("file face representations is...
The code detects faces in images, generates embeddings and facial attributes, updates a DataFrame with results, manages storage with periodic backups, and ensures consistency by identifying and naming unique faces based on their positions. It handles multiple detectors, tracks changes in embeddings, and writes results ...
def detect(self): logging.debug("START DETECTION, CREATION of EMBEDDINGS and FACIAL ATTRIBUTES ---") # get all embeddings and attributes for the images in directory df = self.get_face_representations() # pandas.DataFrame holding all face representation if df is None: df = ...
def check_file_by_display_path(self, file_name, display_dir): if file_name == self.file_name_faces: self.file_faces = None elif file_name == self.file_name_face_representations: self.file_embeddings = None elif file_name == self.file_name_names: self.file_name...
This function checks if face recognition results (df_recognized) differ from stored names in a directory. If so, it filters data by active models, removes invalid faces, reduces results using the most effective method, compares with current names, and writes updated results if changes are detected. It avoids redundant ...
def store_face_names_if_changed(self, df_recognized, faces_dir, most_effective_method): if self.check_file_by_display_path(self.file_name_face_representations, faces_dir) is False: return if self.check_file_by_display_path(self.file_name_faces, faces_dir) is False: return ...
def check_file_by_name(self, file_name): if file_name == self.file_name_face_representations: self.file_embeddings = None elif file_name == self.file_name_faces: self.file_faces = None elif file_name == self.file_name_names: self.file_names = None que...
The main task of the code is to process image detection in a specified directory by preparing required files, performing cleanup of outdated or irrelevant data, and executing face detection on all images. It verifies file accessibility, removes obsolete faces, and triggers detection when the channel matches the provide...
def process_dir(self, own_channel_id): logging.debug("Start detection with directory " + self.folder + " / channel " + str(self.channel)) # ------------------------------------------------------------- # Prepare files # # read absolute paths of some files from the database and c...
def get_csv_reader(csv_file): dialect = csv.Sniffer().sniff(csv_file.readline()) csv_file.seek(0) return csv.reader(csv_file, dialect) def refactor_header(header): return [hm_header_transformations[h] if h in hm_header_transformations else h for h in header] def check_for_required_headers(header): r...
The code processes a CSV file by validating and cleaning data rows, using optional synonyms databases. It checks for required headers, replaces invalid IDs, handles blanks, converts chromosome values, and verifies data types. Rows passing checks are written to an output file or logged if `--print_only` is enabled. Logs...
def main(): argparser = argparse.ArgumentParser() argparser.add_argument('-f', help='The name of the file to be processed', required=True) argparser.add_argument('-o', help='The name of the output file', required=True) argparser.add_argument('-db', help='The name of the synonyms database. If not provid...
def loadCsv(filename): lines = csv.reader(open(filename, "rt")) dataset = list(lines) bl=["No","Yes"] for i in range(1,len(dataset)): for j in range(10,36): if (j<20): dataset[i][j] = getVal(dataset[i][j]) elif((j>=22 and j<=31) or j==33): ...
The code implements a Gaussian Naive Bayes classifier to predict student psychology data. It loads a CSV dataset, splits it into training (67%) and test sets, trains the model by summarizing class distributions, generates predictions on the test set, calculates accuracy, and verifies predictions against the training da...
def main(): filename = 'student psychology.csv' splitRatio = 0.67 dataset = loadCsv(filename) trainingSet, testSet = splitDataset(dataset, splitRatio) print('Split {0} rows into train={1} and test={2} rows'.format(len(dataset), len(trainingSet), len(testSet))) # prepare model summaries ...
def eval_merged_models(no_cuda=False): use_cuda = not no_cuda and torch.cuda.is_available() device = torch.device("cuda" if use_cuda else "cpu") models_dir = os.path.join(PROJECT_DIR, 'models') model_folders = glob.glob(os.path.join(models_dir, '*')) for model_folder in model_folders: ...
This function evaluates all saved models in the project directory by identifying their type (e.g., Hsieh, MobileNetV2, Custom), loading associated configuration arguments, and executing the corresponding evaluation function for each model. It handles multiple folds, defaulting to 'all' if unspecified, and processes mod...
def eval_saved_models(): eval_merged_models() model_pattern = os.path.join(PROJECT_DIR, 'models', '**', '**.pt') model_paths = glob.glob(model_pattern) folds = tuple( pd.Series(model_paths) .apply(lambda path: Path(path).stem) .str.extract('((?<=fold)\d)', expand=False) ...
def fun_A(l1, ans , error_index): if(len(l1)==4): try: ans+= '0'*2 ans+= dict_reg[l1[1]] ans+= dict_reg[l1[2]] ans+= dict_reg[l1[3]] except: # print(search_index(l1)) print("line",error_index, end=": ") ...
This function validates and processes assembly instructions by checking opcodes, handling 'mov'/'mov1' syntax, categorizing instructions (A-F), and appending processed results to a list while exiting on errors. It verifies structure, applies type-specific processing, and enforces constraints like 'hlt' placement.
def func_check(temp_list1, error_index, i): if(temp_list1[0] == "mov1"): # print(search_index(temp_list1)) print("line",error_index, end=": ") print(errors[1]) exit() if(temp_list1[0]== "mov"): try: dollar = temp_list1[2] if ('$' == dollar[0]): ...
def check_variables(file): count = len(variables) check_count = 0 for i in range(0, len(file)): if(file[i] == ''): continue if(file[i].split()[0] == "var"): check_count += 1 else: break if(check_count == count): # No err...
The main task of the code is to validate a list of assembly-like instructions by checking for correct 'hlt' placement, handling labels, skipping 'var' lines, and using `func_check` to verify instruction syntax. It ensures the last instruction is 'hlt', prints errors for violations, and processes labels by splitting and...
def main(): a = "" count = 0 l1 = l3.copy() check_variables(l1) # l1 = ins.copy() --------------------------------------------------marked # print(l3) # print(l1) for i in range(0, len(l1)): # changes ------------- # temp = l1[i].split() # if(temp[...
def reset_game(self): '''Resets level and lives for a new game''' self.lives = 3 self.level = 1 self.victory = False self.game_over = False def fire_ball(self): '''Called when ball is fired from the cannon. Motion is set to the angle of the cannon at that time. P...
The code defines a game loop handling Pygame events for quitting, restarting, controlling cannon movement, firing cannonballs, and drawing shapes. It processes keyboard inputs for color changes, cannon firing, and direction, while mouse inputs enable shape drawing. The loop updates the game state and renders the displa...
def game_loop(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: # ESC always quits the game if event.key == K_ESCAPE: pygam...
def _build_encoder(self): encoder_input = self._add_encoder_input() conv_layers = self._add_conv_layers(encoder_input) bottleneck = self._add_bottleneck(conv_layers) self._model_input = encoder_input self.encoder = Model(encoder_input, bottleneck, name='encoder') def _build_decod...
The main task of the code is to construct the components of an autoencoder by sequentially building the encoder, decoder, and the autoencoder itself. This typically involves defining neural network layers and connectivity for tasks like feature extraction, reconstruction, or generative modeling.
def _build(self): self._build_encoder() self._build_decoder() self._build_autoencoder()
def manual(self): if not self.manual_mode_init: self.set_desired_states_to_current() self.update_initial_state() self.manual_mode_init = True self.x_offset = np.zeros(3) self.yaw_offset = 0.0 print('Switched to manual mode') ...
This function determines the operational mode of a system and executes corresponding actions. If in manual mode, it triggers manual control. For other modes (idle, warm-up, take-off, land, stay, circle), it calls specific methods to set desired states or perform actions like takeoff, landing, or circular movement. The ...
def calculate_desired(self): if self.manual_mode: self.manual() return if self.mode == 0 or self.mode == 1: # idle and warm-up self.set_desired_states_to_zero() self.mark_traj_start() elif self.mode == 2: # take-off self.take...
def get_services(service, compose_services): service_names = [] for service_name in compose_services: if service in service_name: service_names.append(service_name) if len(service_names) < 2: print("Nothing to do") return blue_service = '' green_service = '' ...
This function performs a canary rollout for a service by incrementally shifting traffic from the blue to the green version using weighted routing in a docker-compose configuration. It modifies the AWS CloudFormation resources section, adjusts target group weights in 10 steps (10% increments), applies changes via compos...
def rollout_canary(service, shifting_time_seconds): with open("docker-compose.yml") as yaml_in_stream: compose_file = yaml.safe_load(yaml_in_stream) compose_services = compose_file['services'] compose_resources = compose_file['x-aws-cloudformation']['Resources'] try: blue_servic...
def create_green(): aws_config = Config( region_name=os.environ.get('AWS_ECR_REGION'), signature_version='v4', retries={ 'max_attempts': 10, 'mode': 'standard' } ) ecr_client = boto3.client('ecr', config=aws_config) ...
This code defines a command-line interface for deployment tasks, allowing users to specify one of four actions: creating a green deployment, rolling out a green deployment, rolling back a green deployment, or rolling out a canary deployment. The 'rollout_canary' option requires an optional time parameter for canary upd...
def main(): parser = argparse.ArgumentParser( description='Which stage of deployment needs to be executed' ) parser.add_argument('function', choices=[ 'create_green', 'rollout_green', 'rollback_green', 'rollout_canary' ], help='which action do you want to take') parser.add_argume...
def create_green(service): if service not in MICROSERVICES: raise Exception tag = "0.1.0" ecr_images = ecr_client.describe_images( repositoryName=f'ik-{service}-microservice').get('imageDetails') if ecr_images: tag = list(sorted(ecr_images, key=lambda im...
This script defines a deployment orchestration tool for blue/green and canary strategies. It accepts command-line arguments to execute specific deployment stages (create, rollout, rollback) for designated microservices. The parser validates inputs against predefined options, then routes execution to corresponding funct...
def main(): parser = argparse.ArgumentParser(description='Which stage of blue/green needs to be executed') parser.add_argument('function', choices=['create_green', 'rollout_green', 'rollback_green', ...
def load_settings(): dir_path = 'Config' file_name = 'user_settings.yaml' file_path = os.path.join(dir_path, file_name) # Default settings settings = { 'stash_path': './', 'post_limit': 0, # 0 downloads all posts from the artist, it's the default value 'disk_limit': 0, # 0...
The main task of the code is to download a file from a given URL to a specified folder, checking if the file type and size meet predefined criteria, ensuring sufficient disk space, and avoiding redundant downloads. It uses a temporary file for the download process, updates a progress bar, and renames the file upon comp...
def download_file(url, folder_name, file_name, artist_url, artist_name): # Load settings settings = load_settings() # Check file type if not is_file_type_allowed(file_name, settings['file_type_to_download'], settings['file_type_extensions']): print(f"Skipping download: {file_name} is not a sele...
def fetch_creator_data(): # Fetching creator data from kemono and coomer using the new API endpoint kemono_data = requests.get("https://kemono.su/api/v1/creators.txt").json() coomer_data = requests.get("https://coomer.su/api/v1/creators.txt").json() return kemono_data + coomer_data def find_and_return_...
The main task of the code is to retrieve and validate user data based on an input username by fetching creator data, searching for matches, and prompting the user to correct input if no matches are found. If successful, it collects associated URLs, extracts the username, and returns the JSON file path from the first ma...
def main(input_username): combined_data = fetch_creator_data() matched_entries = find_and_return_entries(combined_data, input_username) # Example URL and username for demonstration example_url = "https://kemono.su/patreon/user/19627910" example_username = "otakugirl90" while not matched_entrie...
def load_settings(): dir_path = 'Config' file_name = 'user_settings.yaml' file_path = os.path.join(dir_path, file_name) # Default settings settings = { 'stash_path': './', 'post_limit': 0, # 0 downloads all posts from the artist, it's the default value 'disk_limit': 0, # 0...
The code processes a list of URLs to download and organize content (e.g., images, files) from platforms like Discord, using configurable settings for storage paths and download limits. It avoids duplicates, structures data into folders, tracks downloaded posts per artist, and saves artist metadata to JSON files.
def run_with_base_url(url_list, data, json_file): if url_list is None or len(url_list) == 0: print("No URLs to process. Exiting function.") return processed_users = set() current_artist = None current_artist_url = None previous_url = None previous_artist_id = None # Explicit...
def extract_table(self): table_soup = [] for item in self.table_subtypes: url = f"{self.config['base_url']}/{self.sport}" \ f"{self.tables[self.table]['source_url']}{item[list(item.keys())[0]]['url']}" print(f"Scraping {url}...") subtype_soup = self....
The code's main task is to scrape and process data updates for specified sports and tables by extracting, transforming, and loading structured data, iterating through configured sports and tables, handling subtypes if defined, and printing transformed results for verification.
def scrape(self): for sport in self.sports: self.sport = sport for table in self.tables: self.table = table print(f"Fetching updates to {sport}_{table}...") self.table_subtypes = self.config["sports"][sport]["tables"][table]["subtypes"] ...
def add_teacher_info(t_db): print('Please enter new teacher details below') # print('in add_teacher_info') # teacher_dict={'fname':'','lname':'', # 'gender':'','title':'','qualification':'','primary_subjet':'','seconday_subject':'','phno':'','email_id':'' # } # print(teacher_dict) teacher_di...
The code presents a menu for managing teacher data, allowing users to add, view, modify, or delete teacher information. It prompts the user to select an option and executes the corresponding function based on their choice, using conditional logic to handle each operation.
def main(): operations_list=['add teacher','view teacher info','modify teacher info','delete teacher'] print("Please select the operation") for i,op in enumerate(operations_list): print(str(i+1)+'. '+op) user_option=int(input('Please select an option: ')) print('you have selected:'+(operatio...
def _find_zone_and_host(self, domain): """ Find the zone and host for a given domain. :param str domain: The domain for which to find the zone_id. :returns: The zone name and host name, if found. :raises certbot.errors.PluginError: if no zone_id is found. """ zon...
The main task of the code is to delete a specific TXT record using provided domain, record name, and content details. It ensures accurate deletion by verifying both the record's name and content to avoid unintended removals. The function handles errors silently, logs failures, and uses an API to delete the record if fo...
def del_txt_record(self, domain, record_name, record_content): """ Delete a TXT record using the supplied information. Note that both the record's name and content are used to ensure that similar records created concurrently (e.g., due to concurrent invocations of this plugin) a...
def cell_calculations(): global cellID global cellData # we're really starting from Cell 0 because of indices. but it's easier for the client to start from 1 #figure.canvas.manager.set_window_title("Cell %d" %(cellID + 1)) # figure.canvas.toolbar.pack_forget() cell = cellData.columns[cellID] ...
The code processes cellular data by iterating through columns, performing calculations on each, and updating a global DataFrame. It sets up interactive plot controls for user input, replots data for visualization, and exports results to a CSV file. The main tasks include data analysis, user interaction handling, and fi...
def main(): # uncomment below line for debugging only (and be sure to close stdout at the end) # this redirects print() output to output.txt, which you will find in the Fiji.app directory after program finishes # sys.stdout = open('output.txt', 'w') # sorry about the globals. it's for a good cause, I p...
def pgd_l1_topk(model, X,y, epsilon = 12, alpha = 0.05, num_iter = 50, k = 20, device = "cuda:1", restarts = 1, version = 0): #Gap : Dont attack pixels closer than the gap value to 0 or 1 gap = alpha max_delta = torch.zeros_like(X) delta = torch.zeros_like(X, requires_grad = True) for t in range (n...
This function generates worst-case adversarial examples by applying PGD attacks under L1, L2, and L∞ norms separately, then selects the perturbation that maximizes the model's loss for each input sample. It combines three attack strategies, evaluates their effectiveness, and returns the most successful perturbation in ...
def pgd_worst_dir(model, X,y, epsilon_l_inf = 0.03, epsilon_l_2= 0.5, epsilon_l_1 = 12, alpha_l_inf = 0.003, alpha_l_2 = 0.05, alpha_l_1 = 0.05, num_iter = 100, device = "cuda:0"): #Always call version = 0 delta_1 = pgd_l1_topk(model, X, y, epsilon = epsilon_l_1, alpha = alpha_l_1, device = device) de...
def pgd_l1_topk(model, X,y, epsilon = 12, alpha = 0.05, num_iter = 50, k = 20, device = "cuda:1", restarts = 1, version = 0): #Gap : Dont attack pixels closer than the gap value to 0 or 1 gap = alpha max_delta = torch.zeros_like(X) delta = torch.zeros_like(X, requires_grad = True) for t in range (n...
The function `triple_adv` trains a neural network using adversarial examples generated with three perturbation norms (L1, L2, Linf) via PGD attacks. It iterates through a data loader, applies each attack to inputs, computes loss with cross-entropy, updates model parameters via an optimizer (if provided), and accumulate...
def triple_adv(loader, lr_schedule, model, epoch_i, attack, criterion = nn.CrossEntropyLoss(), opt=None, device= "cuda:0", epsilon_l_1 = 12, epsilon_l_2 = 0.5, epsilon_l_inf = 0.03, num_iter = 50): train_loss = 0 train_acc = 0 train_n = 0 for i,batch in enumerate(loader): ...
def listify_table(table): """Parse html table into list of lists.""" data = [] rows = table.find_all('tr') for row in rows: cols = row.find_all(['th', 'td']) cols = [parse_cell_value(ele) for ele in cols] data.append(cols) return data def build_cast_frame(cast_tables): "...
The main task of the code is to parse specific tables from a Wikipedia page for a given season of "Are You the One?" and convert them into structured DataFrames. It extracts cast details, progress, correct matches, and truth booth data, adding the season identifier to each DataFrame for organization. The code handles H...
def main(season): """Parse data from Wikipedia.""" if season not in AVAILABLE_SEASONS: raise NotImplementedError(f"Season {season} not available.") base_url = f'https://en.wikipedia.org/wiki/Are_You_the_One%3F_(season_{season})' response = requests.get(base_url) soup = BeautifulSoup(respons...
def mean_pad(x, pad): x_zero_pad = F.pad(x, pad, "constant") mask = F.pad(torch.zeros_like(x), pad, "constant", 1.0) return x_zero_pad + mask * x.mean(dim=[2, 3], keepdim=True) def stratified_sample(strata_begin, strata_end, shuffle=True): assert strata_begin.shape == strata_end.shape assert strata_...
The code performs stratified and uniform sampling to generate multiple cropped regions from an input image, preprocesses them, encodes via a model, and returns a spherical average of the embeddings for robust feature representation.
def forward(self, x): n, c, h, w = x.shape min_size = min(self.cut_size) max_size = min(w, h) pad_size = max(w, h) pad_w, pad_h = (pad_size - w) // 2, (pad_size - h) // 2 x = mean_pad(x, (pad_w, pad_w, pad_h, pad_h)) # Stratified sampling of crop sizes di...
def download_file(url, root, expected_sha256): root.mkdir(parents=True, exist_ok=True) target = root / Path(url).name if target.exists() and not target.is_file(): raise RuntimeError(f"{target} exists and is not a regular file") if target.is_file(): if hashlib.sha256(open(target, "rb")....
The main task of the code is to generate images using a diffusion model guided by CLIP (Contrastive Language-Image Pretraining) text and image prompts. It parses command-line arguments, loads a diffusion model and CLIP models, processes prompts, and performs diffusion sampling with CLIP guidance to produce an output im...
def main(): p = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter ) p.add_argument("prompt", type=str, default="", help="the text prompts") p.add_argument( "--checkpoint", type=Path, help="the diffusion model checkpoint t...
def valid_operands(operands, need, line_no, error): if operands and not need: error.append('Line {}:\'{}...\' is redundant' .format(line_no, operands[0])) return False if not operands and need: error.append('Line {}:Expected more operand(s)' .for...
This function validates operands for assembly instructions based on the operation type, ensuring they meet specific criteria like register names, immediate values, labels, or offsets. It checks operand counts, types, and ranges, appending error messages for invalid cases.
def parse_op(op, operands, line_no, error): if op.upper() in {'ADD', 'AND'}: if not valid_operands(operands, True, line_no, error): return else: is_reg_operand(operands[0], line_no, error) if not valid_operands(operands[1:], True, line_no, error): return ...
def parse_line(line): line = line.split(';')[0] line = line.strip() if not line: return None line = line.replace(',', ' ') elements = line.split() return elements def is_label(element): if element.upper() not in Opcode \ and element.upper() not in Pseudo_ops \ ...
The code performs the first pass of an assembler, processing input lines to build a symbol table, validate labels, check for syntax errors, and track memory usage. It initializes a location counter (LC), checks for required directives like `.ORIG` and `.END`, validates operands, and handles pseudo-ops. Errors such as m...
def pass1(file): LC = [-1] # Location Counter error = [] symbol_table = dict() beyond_memory = False start = False instructions = [] line_no = 0 for idx, line in enumerate(file): line_no = idx + 1 parse_result = parse_line(line) if parse_result is None: ...
def create_widgets(self): self.create_frame() self.create_textbox() self.create_button() self.create_hotkey() self.create_footer() self.create_menu() def new(self): if not self.save_changed(): return self.inputbox.delete(1.0, 'end') sel...
This code initializes a GUI for an LC-3 assembler tool, setting up the main window with a specified size, title, and font. It creates UI components via `create_widgets()`, initializes a new file state with `new()`, and starts a continuous process with `always_run()`, preparing the interface for assembly tasks.
def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.master.geometry('600x650') self.maintitle = 'LC-3 Assembler' self.font = ('Courier New', 10) self.file_saved = True self.create_widgets() self.new() ...
def bwlabel(inputMatrix): num = 0 res = 1 * inputMatrix # convert boolean to 1 or 0 flag = inputMatrix.copy() x = len(res) y = len(res[0]) for i in range(x): for j in range(y): if not flag[i, j]: continue res[i, j] = label_list[num] DFS(res, i, j, flag...
The code processes a binary matrix to identify and analyze connected regions. It labels regions, calculates their areas, and filters out small regions (area ≤ 3). For each remaining region, it detects endpoints, extracts coordinates, and segments them into chunks. The result is a list of segmented point coordinates for...
def convertBinaryToLists(binaryMatrix): connectedRegionMatrix, numOfConnectedRegions = bwlabel(binaryMatrix) # plt.figure(200) # plt.imshow(connectedRegionMatrix) # print('numOfConnectedRegions', numOfConnectedRegions) List_AreaOfConnectedRegions = countAreaOfRegion(connectedRegionMatrix, numOfConn...
def bwlabel(inputMatrix): num = 0 res = 1 * inputMatrix # convert boolean to 1 or 0 flag = inputMatrix.copy() x = len(res) y = len(res[0]) for i in range(x): for j in range(y): if not flag[i, j]: continue res[i, j] = label_list[num] DFS(res, i, j, flag...
This function converts a binary matrix into coordinates of points by identifying the largest connected region, extracting its boundary points, and returning them along with coordinates of smaller regions. It uses image processing techniques to label regions, calculate areas, and detect endpoints for path tracing. The o...
def convertBinaryToPoints(binaryMatrix): connectedRegionMatrix, numOfConnectedRegions = bwlabel(binaryMatrix) # print(numOfConnectedRegions) List_AreaOfConnectedRegions = countAreaOfRegion(connectedRegionMatrix, numOfConnectedRegions) Dict_Regions = {0: 0} for i in range(1, len(List_AreaOfConnected...
def assert_type(obj, obj_type, message): if not isinstance(obj, obj_type): raise SpecRunException(message) def merge_spec_envs(spec, state, all_scopes=False): if not isinstance(spec, dict): raise SpecRunException("spec passed to merge_spec_envs is not a dictionary") if not isinstance(state,...
The function processes a step in a specification by validating dependencies, managing environment variables, and executing the step based on its type (e.g., command, semver). It checks for circular dependencies, ensures dependencies are completed, and marks the step as completed after execution.
def process_spec_v1_step(step_name, step, state): # Validate action type assert_type(step, dict, "Step is not a dictionary") # Create a new scope state parent_state = state state = ScopeState(parent=parent_state) # Merge environment variables in early merge_spec_envs(step, state) # ...
def assert_type(obj, obj_type, message): if not isinstance(obj, obj_type): raise SpecRunException(message) def merge_spec_envs(spec, state, all_scopes=False): if not isinstance(spec, dict): raise SpecRunException("spec passed to merge_spec_envs is not a dictionary") if not isinstance(state,...
This function processes a given action by validating its structure, merging environment variables, extracting and validating steps, and executing each step using a processor. It creates a new scope state, checks action type, ensures steps are valid, resolves step references, and invokes the step processor for each step...
def process_spec_v1_action(action, state): # Create a new scope state state = ScopeState(parent=state) # Validate action type assert_type(action, dict, "Action is not a dictionary") # Merge environment variables in early merge_spec_envs(action, state) # Capture steps for this action a...
def assert_type(obj, obj_type, message): if not isinstance(obj, obj_type): raise SpecRunException(message) def assert_not_emptystr(obj, message): if obj is None or (isinstance(obj, str) and obj == ""): raise SpecRunException(message) def merge_spec_envs(spec, state, all_scopes=False): if not...
This function processes a specified action from a given specification by validating inputs, setting up execution state, merging environment variables, checking action existence, and executing the action while logging progress.
def process_spec_v1(spec, action_name, action_arg): # Make sure we have a dictionary for the spec assert_type(spec, dict, "Specification is not a dictionary") # State for processing state = ScopeState() state.common.spec = spec # Make sure we have a valid action name assert_not_emptystr(ac...
def parse_inputs(): # Command line arguments p = argparse.ArgumentParser() p.add_argument('--test_dir', type=str, help='path to test set', default=None) p.add_argument('--test_annotation', type=str, help='test annotations (pickle/...
The code tests a gaze estimation model (GazeNet) on a dataset by loading a pre-trained model, resuming from a checkpoint, preparing test data, and predicting gaze points on random images. It retrieves image paths, eye positions, and bounding boxes, runs inference to generate heatmaps and coordinates, then visualizes re...
def main(): args = parse_inputs() # Load Model net = GazeNet() # net = ModelSpatial() net.cuda() resume_path = args.resume_path net, optimizer, start_epoch = resume_checkpoint(net, None, resume_path) #Prepare dataloaders test_images_dir = args.test_dir test_pickle_path = args...
def parse_inputs(): # Command line arguments p = argparse.ArgumentParser() p.add_argument('--test_dir', type=str, help='path to test set', default=None) p.add_argument('--test_annotation', type=str, help='test annotations (pickle/...
The main task of the code is to test a gaze estimation model (ModelSpatial) on a dataset of images, visualize predicted gaze points, and save results. It loads a pre-trained model checkpoint, prepares test data using GooDataset, processes random image samples, infers gaze coordinates via test_on_image, and draws result...
def main(): args = parse_inputs() # Load Model # net = GazeNet() net = ModelSpatial() net.cuda() resume_path = args.resume_path net, optimizer, start_epoch = resume_checkpoint(net, None, resume_path) # Prepare dataloaders test_images_dir = args.test_dir test_pickle_path = args...
def model_forward(X, parameters): caches = [] A = X L = len(parameters) // 2 # 1 w, 1 b for l in range(1, L): A, cache = linear_activation_forward(A, parameters["W" + str(l)], parameters["b" + str(l)], "relu") caches.append(cache) A_last, cache = linear_activation_forward(A, paramet...
This function performs one training iteration of a neural network by executing forward propagation, computing the cost with L2 regularization, backpropagation to calculate gradients, and updating parameters using the specified optimizer (gradient descent or momentum). It returns the computed cost.
def one_iteration_of_network(X, Y, parameters, learning_rate, l2_lambda, optimizer="gd", velocities=None, beta=.9): A_last, caches = model_forward(X, parameters) cost = compute_cost_with_regularization(A_last, Y, parameters, l2_lambda) grads = model_backward(A_last, Y, caches, l2_lambda) if optimizer ==...
def dayname_from_date(date): # Get day of week as name from datetime object return date.strftime("%A") def string_from_date(date): # Convert datetime object to string return date.strftime("%Y-%m-%d") def plot_map(df, title, area_prefix="", area_suffix="", filename=None, show=False, frame_time=100, norma...
The main task of the code is to process and visualize COVID-19 case and test data. It loads population data, ingests case/test data from files, processes weekly aggregations, calculates positive rates and their changes, and generates maps for daily/weekly case trends, percentage changes, and positive rate metrics. Resu...
def main(): # %% # Load population data population = pd.read_csv("Population/ONS-population_2021-08-05.csv") pop_lookup = pd.Series(dtype=int) for i, group in population.groupby("areaCode"): pop_lookup[i] = group[group.category == 'ALL'].population.values[0] # Ingest case data (download...
def parse_ltla(ltla_zone): ltla_code = ltla_zone.record[1] current_zone = ltla_zone ltla_name = current_zone.record[2] return current_zone, ltla_code, ltla_name def distance(p1, p2): p1 = np.asarray(p1).reshape(-1, 2) return ((p1[:,0] - p2[0]) ** 2 + (p1[:,1] - p2[1]) ** 2) ** 0.5 def simplify_...
This function simplifies the polygonal boundary of a Local Authority (LTLA) by identifying and merging shared boundary segments with neighboring regions. It uses spatial proximity checks (KDTree) to detect matching points between zones, then iteratively constructs a simplified boundary by reusing precomputed segments f...
def simplify_boundary(data, neighbors, ltla_zone, progress=False): """Simplifies the boundary of an ltla Data is a reference to the dictionary containing the completed boundaries Neighbors is a reference to the dictionary containing the neighbors of the completed boundaries Both will be modi...
def apply_additional(self, rule: Rule) -> None: self.count_warn += 1 txt = rule['message'] + '. ' + rule['information'] response = self.format_response('warning', txt, c.R_ADDITIONAL) self.response['result'].append(response) def apply_difficulty(self, rule: Rule, difficulty: int) -> Non...
The main task of the code is to apply a set of predefined rules to a query, evaluate each rule's conditions, track success/failure/warning counts, and return a structured response with the evaluation status, counts, and results. It processes rules categorized by type (e.g., difficulty, period, region), executes corresp...
def apply_rules(self, query: QueryParams) -> tuple[int, dict]: self.count_all = 0 self.count_fail = 0 self.count_warn = 0 self.response.clear() self.response['result'] = [] rules = self.database.get_rules(query.tvk.upper()) if rules is not None: for ...
def rest(self): self.velocity = self.delta_v = (0, 0) self.omega = self.delta_omega = 0 def can_rest(self): return ((self.velocity[0]**2 + self.velocity[1]**2 < 0.01) and (self.delta_v[0]**2 + self.delta_v[1]**2 < 0.01) and -0.05 < self.omega < 0.05 ...
This method updates the object's state by transitioning between GRABBED, RELEASED, MOVING, and REST states. It triggers rest() when conditions are met, applies physics when moving, and manages state changes based on current status, ensuring proper behavior during interactions like grabbing, releasing, and movement.
def update(self): if self.state == CardState.GRABBED: self.rest() if self.state == CardState.RELEASED: self.state = CardState.MOVING if self.state == CardState.MOVED: self.state = CardState.GRABBED if self.state == CardState.MOVING: if s...
def authenticate(): token = requests.post(AUTH_URL, data=AUTH_HEADERS) content = json.loads(token.content) global access_token, conversation access_token = content["access_token"] conversation = content["session_state"] def get_prices(src, dst, passenger="paxa", age=42, half_fare=True, date="2019-09...
The code retrieves trip details including weather information for destinations. It authenticates, fetches trip prices, extracts destination coordinates, requests weather data for each arrival time, and appends weather details to trip records. The function returns annotated trip data with temperature, conditions, and ic...
def get_trip_details(src, dst, time_back, half_fare): authenticate() picked_trips = get_prices(src=src, dst=dst, time_back=time_back, half_fare=half_fare) if picked_trips is None or picked_trips[0] is None or picked_trips[1] is None: return None for picked_trip in picked_trips: destinat...
def log(*v, **kw): _log(*v, **kw) sys.stdout.flush() def added_object(self, o): log('++>', oid(o), '@', o.metadata.creation_timestamp) self.resolve_handler('added', o) def start_scanning(self, o): tags = [ t.tag for t in o.tags ] self.pool.apply_async( klar, ...
(The code processes a collection of objects, logging their count and type. If in booting mode, it adds each object and initiates scanning for 'ClairReport' objects in 'Scanning' status. Otherwise, it delegates processing to a handler resolved via 'process' method. The main task is handling object initialization/scannin...
def process_objects(self, objs, kind, booting=False): log('>>> Processing {} {} objects'.format(len(objs), kind)) for uid, o in objs.items(): #log('>>>', oid(o)) if booting: self.added_object(o) if o.kind == 'ClairReport' and o.status == 'Scanning'...
def log(*v, **kw): _log(*v, **kw) sys.stdout.flush() def start_scanning(self, o): tags = [ t.tag for t in o.tags ] self.pool.apply_async( klar, args=(o.metadata.uid, o.image_repository, tags, self.dockercfg), callback=self.on_scan_finished, error_c...
The code processes a ClairReport object by initiating or reconciling scans based on its status. If the status is 'Creating', it starts a scan. If 'ScanFinished', it checks for an existing scan (via UID); if absent, it starts a new scan, otherwise it reconciles tags between the report and the existing scan.
def process_clairreport(self, o): log('Processing ClairReport: {} {}'.format(o.metadata.name, o.status)) if o.status == 'Creating': self.start_scanning(o) elif o.status == 'ScanFinished': scan = self.scans.get(o.metadata.uid) if scan is None: ...
def imagestream_tags_has_changed(old, new): old_tags = imagestream_tags(old) new_tags = imagestream_tags(new) old_tags_names = set([ t.tag for t in old_tags ]) if old_tags_names != set([ t.tag for t in new_tags ]): return True for old_tag in old_tags: new_tag = imagestream_tag(new,...
The code detects changes in an ImageStream's tags. If changed, it triggers ClairReport scanning for existing reports or creates a new one if none exist, then logs each tag's Docker image reference for monitoring or processing.
def modified_imagestream(self, old, new): if not imagestream_tags_has_changed(old, new): return log('ImageStream has changed {}/{}'.format(new.metadata.namespace, new.metadata.name)) for cr in self.clairreports(new): log('ClairReport found... starting scan {}/{}'.format...
def clean_data(col_name, stop_list, file_name): """Cleans data: - Removes duplicates - Eliminates links, non alphanumerics, and punctuations. - Transforms all text to lowercase. :param col_name: (str) Name of column with text. :param stop_list: (arr) List of stop words. :param file_name: (f...
The main task of the code is to recommend similar articles by analyzing document descriptions using NMF topic modeling. It cleans text data, extracts topics, and identifies similar articles based on topic distributions, with configurable parameters like number of topics and target article indices.
def recommend(): stop_list = STOPWORDS.union(set(['data', 'ai', 'learning', 'time', 'machine', 'like', 'use', 'new', 'intelligence', 'need', "it's", 'way', 'artificial', 'based', 'want', 'know', 'learn', "don't", 'things', 'lot', ...
def get_cached_repo_path(self, repo: str) -> tuple[Path, Path]: repo_path = self.root_path / sanitize_path(repo) repo_pkl_path = repo_path / f"{sanitize_path(repo)}.pkl" return repo_path, repo_pkl_path def get_repo(self, repo: str) -> Repository | None: repo_path, repo_pkl_path = self.g...
The function retrieves a commit object from a specified repository, either by loading a cached pickle file or fetching it from the repository. It handles rate limits by retrying after an hour and logs errors for other exceptions, returning None if unsuccessful.
def get_commit(self, repo: str, commit_hash: str) -> Commit | None: repo_path, _ = self.get_cached_repo_path(repo) commit_pkl_path = repo_path / f"{commit_hash}.pkl" if commit_pkl_path.exists(): with commit_pkl_path.open("rb") as fp: commit_obj = pickle.load(fp) ...
def safe_load_files(self) -> None: """ Load the files in the commit only if they are not loaded yet :return: None """ if not hasattr(self, 'files'): self.load_files() def get_commit2vec_files_path(self, path_: str) -> Path: """ Get the path to where th...
The function saves pre-commit and post-commit states of files to specified paths, returning whether any pairs were successfully saved. It first checks for existing files; if none, it iterates through each file, retrieves its pre-commit state (using the raw commit) and post-commit state, then saves them as separate file...
def save_pre_post_files(self, path_: str) -> bool: """ Save the pre and post versions of files, return if any pair was saved :param path_: The root to all commit2vec files :return: Boolean representing if any pre post was found """ self.safe_load_files() commit2ve...
def safe_load_files(self) -> None: """ Load the files in the commit only if they are not loaded yet :return: None """ if not hasattr(self, 'files'): self.load_files() def save_pre_post_files(self, path_: str) -> bool: """ Save the pre and post versions...
The code saves pre and post versions of files only when both states exist. If no valid pair is found, it deletes the directory containing these files.
def save_pre_post_files_pairs(self, path_: str | Path): """ Save the pre and post versions of files but only if both states exists :return: None """ self.safe_load_files() pair_found = self.save_pre_post_files(path_) if not pair_found: self.get_commit...
def compute_doc_embeddings(self, df: pd.DataFrame) -> Dict[Tuple[str, str], List[float]]: """ Create an embedding for each row in the dataframe using the OpenAI Embeddings API. Return a dictionary that maps between each embedding vector and the index of the row that it corresponds to. "...
The main task of the code is to generate a response to a question using a long context. It constructs a prompt based on whether a query-passage match flag is enabled, either by analyzing paragraph embeddings or directly using context. The prompt is then passed to an OpenAI completion API to produce an answer, which is ...
def get_ans_long_context(self, context: str, ques: str) -> str: ''' ''' COMPLETIONS_API_PARAMS = { # We use temperature of 0.0 because it gives the most predictable, factual answer. "temperature": self.temperature, "max_tokens": self.max_tokens, "mod...
def get_source_and_reactions(self, event_name): source_tweets = self.get_data({'bool': {'must': [{'match': {'event_name': event_name}}], 'must_not': [{'exists': {'field': 'source_tweet_id'}}]}}, 'created_at:asc') conve...
This code processes conversations related to a specific event by extracting time frames, rumor status, and representations. It iterates through each conversation, compiles source tweets and reactions into frames, collects rumor labels, and generates representations. The function returns these structured outputs for fur...
def get_all_cij(self, event_name, t): conversations = self.get_source_and_reactions(event_name) frames = list() rumors = list() representations = list() for cij in conversations: pre_frame = list() pre_frame.append(cij["source_tweet"]) rumors.a...
def clear(self): """Reset the data variables for this instance.""" self.data = {'id': None} def load(self, objid, update=False, nowait=False): """Load a record from the target table identified by ID.""" with closing(self.conn.cursor(cursor_factory = DictCursor)) as c: c.exe...
(The main task of the code is to initialize an object with a database connection and optionally load data by ID or provided data. It clears internal state, then loads a record using `load()` if an ID is given, or `load_dict()` with provided data. Parameters like `update` and `nowait` influence loading behavior, ensurin...
def __init__(self, conn, id = None, data = None, update=False, nowait=False): """Arguments: db connection. Optional: id or data to load/preload a specific record.""" self.conn = conn self.clear() if id != None: self.load(id, update, nowait) elif data != None...
def init_device(self): self.device = t.device("cpu") def init_hp_ranges(self, d: Dict[str, tuple[float, float]]): self.hp_ranges = d self.key_to_index = dict() self.index_to_key = dict() self.num_hps = len(self.hp_ranges) self.hp_lb = t.zeros(self.num_hps) self...
The code initializes a Bayesian optimization framework by setting up a model, hyperparameter ranges, and initial data points (X and y). It configures the optimizer with a given model function, device settings, and named identifier, preparing it for iterative optimization tasks like hyperparameter tuning or function app...
def __init__(self, d: Dict[str, tuple[float, float]], model: Callable[[Dict[str, float]], t.Tensor], name=None): self.name = "BayesOpt_{}".format(name if name is not None else time.time()) self.model = model self.init_device() self.init_hp_ranges(d) self.init_X() self.in...
def make_frequency_dict(self, nparray): # get 1d np array frequency = {} for number in nparray: if not number in frequency: frequency[number] = 0 frequency[number] += 1 return frequency def make_heap(self, frequency): for key in frequency: ...
This code compresses a 2D numpy array using Huffman coding. It calculates symbol frequencies, builds a priority heap, generates codes, encodes the array into bits, pads the bits for byte alignment, converts to a byte array, and returns the compressed data along with encoding mapping information.
def compress(self, nparray): # 2d nparray frequency = self.make_frequency_dict(nparray.flatten()) self.make_heap(frequency) self.merge_nodes() self.make_codes() encoded_bits = self.get_encoded_bits(nparray.flatten()) padded_encoded_bits = self.pad_encoded_bits(en...
def __pre_processing(arg_img_path: str) -> np.ndarray: img = cv.imread(arg_img_path) gray_scale_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # (3,3) is the kernel size and 5 is the sigma value blur_gray_scale_img = cv.GaussianBlur(gray_scale_img, (3, 3), 5) threshold_img = cv.adaptiveThreshold(blur_gra...
This function converts a Sudoku image into a 2D number array by preprocessing the image, detecting cells, and mapping initialized numbers. It raises an error if the Sudoku board isn't detected. Input: image path and initialized numbers; Output: 2D Sudoku array.
def get_sudoku_board_as_array_from_img(arg_img_path: str, arg_initialized_numbers_in_sodoku_by_order: List[int]) -> List[List[int]]: """ This is a function that gets img path and the numbers that were initialized in sodoku by order from left to right and top to bottom, and returns 2D array of numbers t...
def get_default_email_subject() -> str: return f"[Update] {get_wedding_name()}" def check_if_valid_email(test_email) -> bool: if not test_email: return False regex = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" return bool(re.fullmatch(regex, test_email)) def _send_plaintext_email( ...
The function sends a message (email) to valid guests of a party, filtering out guests with invalid emails. It collects valid guests, sends a plaintext email with the provided message, subject, and optional image attachments to their emails, and returns the list of valid guests. If no valid guests are found, it returns ...
def send_message( self, party: Party, message: str, subject: str = get_default_email_subject(), img_paths: Optional[List[Path]] = None, ): valid_guests = [] for g in party.get_guests(): if not check_if_valid_email(g.email): print(f"...
def load_database(self): try: with open('database.bin', 'rb') as file: data = self.enc.decrypt(file.read()) data = pickle.loads(data) except self.enc.InvalidToken: data = False except FileNotFoundError: data = {'version':__versi...
The code removes a specified key from a database by loading the database, identifying the key, deleting it from the 'keys' dictionary, and saving the updated database, returning a success message upon completion.
def remove_key(self, key_name=None): data = self.load_database() keys = data['keys'].keys() key_name = self.load_key(key_name)[0] data['keys'].pop(key_name) self.write_database(data) return 'Key removed successfully.'
def east(lines: tuple[tuple[str]]) -> tuple[tuple[str]]: return transpose(south(transpose(lines))) def south(lines: tuple[tuple[str]]) -> tuple[tuple[str]]: return north(lines[::-1])[::-1] def west(lines: tuple[tuple[str]]) -> tuple[tuple[str]]: return tuple(shift(line) for line in lines) def north(lines: t...
The code applies four directional transformations in sequence—north, west, south, and east—to the input lines, returning the final transformed result.
def cycle(lines: tuple[tuple[str]]) -> tuple[tuple[str]]: return east(south(west(north(lines))))
def _reset_game_settings(self): """Reset the game settings.""" self.settings.initialize_dynamic_settings() self.level_is_set = False def _reset_game_stats(self): """Reset the game statistics.""" self.stats.reset_stats() self.stats.game_active = True se...
This method checks if the play button is clicked (via mouse position or default trigger) and initiates a new game when the game is inactive. It resets game settings, stats, visuals, and audio, hides the mouse cursor, and plays startup sounds to restart the game session.
def _check_play_button(self, mouse_pos=None): """Start new game when the player clicks Play.""" if mouse_pos: button_clicked = self.play_button.rect.collidepoint(mouse_pos) else: button_clicked = True if button_clicked and not self.stats.game_active: ...
def _fire_bullet(self): """Create a new bullet and add it to the bullets group""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) #Shoot sound FX if self.stats.game_activ...
This function handles keydown events in a Pygame game, mapping specific keys to actions: right/left arrow for ship movement, spacebar to fire bullets, 'q' to exit and update high score, and 'p' to pause/resume or start the game based on current state.
def _check_keydown_events(self, event): """Respond to keypress.""" if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_SPACE: self._fire_bullet() ...
def _check_fleet_edges(self): """Responds appropiately if any aliens have reached an edge.""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _ship_hit(self): """Respond to the ship being hit by an a...
This method updates alien positions, checks for collisions with the player's ship, and detects if aliens reach the screen bottom. It first checks fleet edges, updates alien movement, triggers ship hit response on collision, and verifies if aliens have reached the screen's lower boundary.
def _update_aliens(self): """Update the positions of all aliens in the fleet""" self._check_fleet_edges() self.aliens.update() #Look for alien-ship collisions. if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() #Look...
def _check_keydown_events(self, event): """Respond to keypress.""" if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_SPACE: self._fire_bullet() ...
The code handles keyboard and mouse events in a Pygame application. It exits on QUIT, processes key presses/releases via _check_keydown_events and _check_keyup_events, and checks mouse clicks. For mouse clicks, it determines the position and triggers play, level, or help buttons based on whether the level is set, using...
def _check_events(self): """Watch for keyboard and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pyg...
def _check_events(self): """Watch for keyboard and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pyg...
The code's main task is to run the game's main loop, continuously checking for events, updating on-screen elements when not paused, pausing background music if paused, and refreshing the display. It maintains game state, handles user input, manages audio, and ensures real-time rendering of game elements.
def run_game(self): """Start tha main loop for the game""" while True: self._check_events() if not self.is_paused: self._update_elements_on_screen() else: self.sound.pause_background...
def handle_events(self): """ This one handles the events * if event is keypress 's', then toggle game pause * if event is keypress 'r', then randomize grid * if event is keypress 'q', then quit game """ for event in pygame.event.get(): if event.type =...
The code defines a main game loop that displays the grid, handles events, updates the grid for the next generation (if not paused), draws the updated grid, and caps the frame rate to maintain performance.
def run(self): """ THis is the main game loop first we display the grid then listen of events then we update the grid for the next generation lastly, we draw the next generation """ pygame.display.flip() while True: self.handle_events() ...
def CreateNewPopulation(size): population = [] for x in range(size): newGenome = Genome() newGenome.chromosomes = random.sample(range(1, citySize), citySize - 1) newGenome.chromosomes.insert(0, 0) newGenome.chromosomes.append(0) newGenome.fitne...
The code implements a genetic algorithm to optimize a problem by evolving a population over generations. It initializes a population, iteratively selects parents, creates offspring via crossover, removes weak individuals below a fitness threshold, tracks the best genome's fitness, and visualizes results. The goal is to...
def GeneticAlgorithm(popSize, maxGeneration): allBestFitness = [] population = CreateNewPopulation(popSize) generation = 0 while generation < maxGeneration: generation += 1 for i in range(int(popSize / 2)): # Select parent, make crossover and ...
def _update_agent_location(self, agent_id, action): x, y = self.agents[agent_id].x, self.agents[agent_id].y if action == TOP and y > 0 and self.wall_map[y - 1, x] == 0: self.agents[agent_id].y -= 1 elif action == BOT and y < self.grid_size - 1 and self.wall_map[y + 1, x] == 0: ...
The main task of the code is to process an action in a multi-agent environment by updating agent positions, checking door status, calculating rewards, and determining if the episode is done. It returns the observation (agent positions and door state), reward, and done flag for the next step in a reinforcement learning ...
def step(self, action): assert not self.done, "error: Trying to call step() after an episode is done" obs = [] for agent_id, agent in enumerate(self.agents): self._update_agent_location(agent_id, action[agent_id]) obs.extend([agent.x, agent.y]) self._update_door_s...
def normalize_time (frame): t = frame["world_timestamp"].values length = len(frame["world_timestamp"]) k = t[0] frame.world_timestamp = frame.world_timestamp - k def getAcclerationsTimes (frame): velocities = getVelocitiesTimes(frame)[0] times = getVelocitiesTimes(frame)[1] length = len(velo...
This code processes eye-tracking data from 17 CSV files, filtering by confidence and eye ID, calculating accelerations, and determining focus percentages using the AccFocused function. It prints the maximum focus percentage between left and right eyes for each file, with parameter 'v' influencing focus calculations.
def allAccFocus (v): print(v) for i in range (17): pupils = pd.read_csv("/Users/munte029/Desktop/eye_tracking/data" + str(i) + ".csv", usecols=["world_timestamp","eye_id", "norm_pos_x", "confidence", "norm_pos_y"]) normalize_time (pupils) pupils_l = pupils.loc[pupils["co...
def check_types(config, types): for type in types: if type not in config: raise ValueError(f'Required field {type} not found in config') def get_clip(self, config): # config['type'] == 'wav': # load the binary data (WAV) self.check_types(config, ['path']) ...
This code constructs a Song object from a configuration dictionary. It validates required keys, initializes the Song with BPM and sample rate, populates clips, instruments, and patterns by processing each config entry through respective helper methods, then returns the fully configured Song instance.
def get_song(self, config): self.check_types(config, ['bpm', 'sample_rate', 'clips', 'instruments', 'patterns']) song = Song(config['bpm'], config['sample_rate']) for key, value in config['clips'].items(): song.clips[key] = self.get_clip(value) for key, value in config['instr...
def _get_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Convert mypy output to codeclimate json format") parser.add_argument("--version", action="version", version="%(prog)s " + __version__) parser.add_argument( "input", metavar="INPUT", type=_get_...
The main task of the code is to parse command-line arguments, load and convert input data, save the results to the specified output, and handle errors by exiting with a fatal code if exceptions occur during the process.
def main() -> NoReturn: parser = _get_parser() args = _parse_args(parser) try: exit_code = _load_convert_and_save(args.input, args.output) except Exception as e: print(f"Error: {e}", file=sys.stderr) # noqa: T201 exit_code = MypyExitCode.FATAL sys.exit(exit_code.value)
def junta(self, junta, cuerpos, ancla): junta.attach(*cuerpos) # joint junta.setAnchor(ancla) def getBodyRelVec(b, v): """Returns the 3-vector v transformed into the local coordinate system of ODE body b.""" return rotate3(traspuesta(b.getRotation()).reshape(9), v) def norm3(v): """Retur...
This function creates a ball joint between two bodies in a physics simulation, setting anchor points, orientation axes, and rotational limits. It calculates orthogonal vectors for joint alignment, stores constraints (flex/twist limits and forces), and returns the configured joint.
def addBallJoint(self, body1, body2, anchor, baseAxis,\ baseTwistUp, flexLimit = pi,\ twistLimit = pi, flexForce = 0,\ twistForce = 0): anchor += array(self.offset) # create the joint joint = BallJoint(self.world) self.junt...
def addBody(self, p1, p2, radius, name): """Adds a capsule body between joint positions p1 and p2 and with given radius to the ragdoll.""" global cuerpos, nCuerpo (p1, p2), body = (p1, p2) + self.offset, Body(self.world) # cylinder length not including endcaps, make capsules ov...
This code initializes a ragdoll physics model by creating body parts (chest, limbs, etc.) and connecting them with joints (ball, hinge, universal) to simulate flexible movement. It assigns geometric shapes, masses, and joint constraints for realistic physics behavior in a simulation environment.
def __init__(self, world, space, density, offset = zeros(3)): """Creates a ragdoll of standard size at the given offset.""" self.world, self.space, self.density, self.bodies,\ self.geoms, self.joints, self.totalMass,\ self.offset, k = world, space, density, [],\ ...
def gcd(a, b): if (a == 0): return b return gcd(b % a, a) def sum_fraction(arr1, arr2): num1, den1 = arr1 num2, den2 = arr2 lcd = lcm(den1, den2) num1 *= (lcd / den1) num2 *= (lcd / den2) res_num = num1 + num2 return [int(res_num), int(lcd)]
The function `helper` computes and updates transition probabilities between states in a matrix, simplifying fractions using the greatest common divisor (gcd). It tracks visited states to avoid cycles, accumulating probabilities for stable states (where `row_sum[col] == 0`) and recursively propagating probabilities to s...
def helper(row, pre_prob, track): for col in range(size): num = m[row][col] den = row_sum[row] # check if the numerator is not 0 if num != 0: cur_prob = [num * pre_prob[0], den * pre_prob[1]] # simplify the form com_div = gcd(cur_prob[0], cur_prob[1]) cur_prob...
def check_item(self, item): check_key = self._check_key(item) if check_key: idx = Hash(item[0]) if item[1] in self.table[idx][item[0]]: return True return False def _check_key(self, item): idx = Hash(item[0]) keys = list(self.table[idx].keys()) if item[0] in keys(): ret...
The code's main task is to add an item to a hash table. It checks if the item already exists; if so, it prints a message. If not, it calculates an index using the item's first element, then either appends the item's value to an existing key's list or creates a new entry if the key doesn't exist. This ensures data is st...
def add(self, item): item_check = self.check_item(item) if item_check: print(f"{item} exists in the table") else: key_check = self._check_key(item) idx = Hash(item[0]) if key_check: self.table[idx][item[0]].append(item[1]) else: self.table[idx][item[0]] = item[1...
def classPredictions(X,W): predictedLabels = [] for x_i in X: predictedLabels.append(sigmoid(x_i, W)) return np.array(predictedLabels) def nextW(predictedLabels, trueLabels, samples, prevW, alpha, C, D): grad_W_MSE = np.zeros((C,D+1)) for k in range(len(samples)): grad_gk_MSE = predi...
The main task of the code is to train a linear classifier by iteratively updating a weight matrix $ W $ using predicted and true labels, samples, and parameters like learning rate ($ \alpha $) and regularization terms ($ C, D $). It computes error rates and mean squared errors (MSE) every 50 iterations for evaluation, ...
def trainLinearClassifier(trueLabels, samples, W_0, alpha, iterations, C, D): W = W_0 errorRates = [] MSEValues = [] for m in range(iterations): predictedLabels = classPredictions(samples,W) W = nextW(predictedLabels, trueLabels, samples, W, alpha, C, D) # Samples MSE value and e...
def removeFeatures(dataSet, featureIndexes,D): removedFeatureIndexes = [] for c in featureIndexes: if c.isdigit(): removedFeatureIndexes.append(int(c)) removedFeatureIndexes.sort() if len(removedFeatureIndexes) > 0: D = D-len(removedFeatureIndexes) newDataSet = dataS...
The code implements a linear classifier for the Iris dataset, allowing users to configure feature removal, train the classifier with tunable alpha values, and evaluate performance via confusion matrices and error rates. It also provides options to visualize feature histograms, alpha decision plots, and scatter plots of...
def main(): irisDataSet = load_iris() print(""" LINEAR CLASSIFIER FOR THE IRIS DATA SET""") ans = '-1' while ans != '0': C = 3 # number of classes D = 4 # number of features classSize = 50 print(""" (0) QUIT (1) CONFIGURE LINEAR CLASSIFIER ...
def _validate_arg(validator, value): try: return validator(value) except ValueError as e: print(e, file=sys.stderr) exit(1) def _read_key_file(dir_path, filename, key_type): key_path = path.join(dir_path, filename) with open(key_path, 'rb') as f: file_octets = f.read() ...
The code generates a Certificate Signing Request (CSR) for Tor v3 onion services, adhering to CA/Browser Forum standards. It parses command-line arguments, validates inputs, reads private/public keys from a directory, constructs a certification request with a nonce, signs it, and outputs the PEM-encoded CSR.
def _main(): parser = argparse.ArgumentParser(description='Create CSRs suitable for validation of Tor v3 Onion Domain Names ' 'according to Appendix B of the CA/Browser Forum Baseline ' 'Requirements', prog='onionmaker...
def get(clientId, topicName, socket, client_message_id): topicIndex = findTopicIndex(topicName) if topicIndex == -1: # Topic does not exist msg = f'-1/Unable to perform GET operation, topic = {topicName} does not exist!' sendMsg(socket, msg) return -1 messages = topicFile[topicI...
The main task of the code is to parse incoming messages from a socket by splitting them into components (client ID, operation, topic name, and optional message), then routing the operation to corresponding handler functions (GET, PUT, SUB, UNSUB, Node) or sending an error for invalid formats. It decodes messages, valid...
def parse_msg(socket, message): print(message) message = message.decode('utf-8') tokens = message.split(" ") if(len(tokens)<3): return client_id = tokens[0] operation = tokens[1] topic_name = tokens[2] if operation == "GET": message_status = tokens[3] ...
def find_nearest_available_car(customer: Customer, available_cars: QuerySet) -> Car: """ Return the Car which is 1) available AND 2) nearest to the customer AND 3) lowest car id """ if len(available_cars) == 0: return None # Find the list of cars with the lowest distance to customer lowest_distance = get_lo...
The code processes a request to find the nearest available car for a customer's ride, calculates the total time for the car to pick up and transport the customer, and returns the car ID and total time in JSON format. It parses input coordinates, creates a customer object, identifies the closest free car, computes trave...
def book(request): """ given a customer of source (x1,y1) and destination (x2,y2) return the nearest car id and the total time needed for the car to 1) pick up the customer 2) send the customer to their destination expects a json in the request body of { "source": { "x": x1, "y": y1 }, "d...
def get_zenith_utc(self, year, month, day): _, zenith_utc = self.get_sun_max_elevation(year, month, day) return zenith_utc def get_gnomon_shadow_angle_zenith(self, year, month, day): """ Returns the angle (in radians) between the gnomon shadow and the X axis (the East) at the zenith. ...
The main task of the code is to calculate and return the angles between a gnomon's shadow and the East (X) axis for each hour of a given day, starting with the zenith angle. It uses the zenith time as a reference, then computes hourly angles by shifting the zenith time by one-hour intervals (3600 seconds) and appending...
def get_all_gnomon_shadow_angle_degrees(self, year, month, day): """ Returns all (each hour) angles (in degrees) between the gnomon shadow and the X axis (the East) beginning with the zenith angle. Parameters ---------- year : int Year. month : int ...
def get_zenith_utc(self, year, month, day): _, zenith_utc = self.get_sun_max_elevation(year, month, day) return zenith_utc def get_gnomon_shadow_angle_zenith(self, year, month, day): """ Returns the angle (in radians) between the gnomon shadow and the X axis (the East) at the zenith. ...
This function calculates the gnomon shadow angles relative to the East (X-axis) for each hour of a given date, starting with the zenith angle. It uses the zenith UTC time, computes the initial zenith angle, and iteratively calculates subsequent hourly angles by shifting the zenith time by one hour (3600 seconds) for 11...
def get_all_gnomon_shadow_angle(self, year, month, day): """ Returns all (each hour) angles (in radians) between the gnomon shadow and the X axis (the East) beginning with the zenith angle. Parameters ---------- year : int Year. month : int ...
def load_csv_data(self, file_path): with open(file_path, 'r') as file: reader = csv.reader(file) data = list(reader) num_rows = len(data) num_columns = len(data[0]) if data else 0 self.table_widget.setRowCount(num_rows) self.table_widget.setColumnCount(nu...
The code initializes a GUI application to display and search CSV data. It sets up a window with a table widget, loads data from a file, configures the table, and prepares search functionality to navigate through filtered results.
def __init__(self, width, height, file_path): super().__init__() self.setWindowTitle("Customer Database Viewer") self.resize(width, height) self.table_widget = QtWidgets.QTableWidget() self.setCentralWidget(self.table_widget) self.load_csv_data(file_path) self.set...
def handle_person_search(request, query, choice): person = tmdb_api.get_data_by_query(f"/search/person", query, "name") person_id = tmdb_api.lookup_id_in_data_by_query(person, query) if choice == "movie_credits": return render_person_movie_credits(request, person_id) return render_person_tv_cr...
The code processes a search request by extracting query parameters (query, type, choice), validating the query's presence, normalizing the query to lowercase, and routing the search to specific handlers based on the media type (person, movie, or TV). It returns appropriate results or an error if the query is missing.
def search(request): query = request.GET.get("query") media_type = request.GET.get("type") choice = request.GET.get("choice") if not query: return render(request, "error.html") query = query.lower() if media_type == "person": return handle_person_search(request, query, choice)...
def get_client(subscription: str, tenant: str, client_id: str, client_secret: str) -> ResourceManagementClient: credential = ClientSecretCredential(tenant, client_id, client_secret) return ResourceManagementClient(credential, subscription) def deploy_multiple(client: ResourceManagementClient, resource_group_nam...
This code deploys Azure Logic Apps from JSON templates. It checks if the input path is a directory or file, validates existence and format, initializes an Azure client, and deploys either multiple Logic Apps (from directory) or a single one (from file) using the provided credentials and resource group.
def main(args): # Initialize args path = args.path resource_group_name = args.resource_group_name subscription = args.subscription tenant = args.tenant client_id = args.client_id client_secret = args.client_secret # Check if path exists if os.path.exists(path) is False: sys....
def check_regex(self): #regex 7... are incorrectly invalidated self.regex = self.regex.replace(' ', '') if self.regex == 'N': return if self.regex[0] in self.operators: raise InvalidExpression('Regex cannot start with an operator') prev = '' paren = [] for char in self.regex: # e must be included...
The code initializes a RegEx object by reading a regex from a file, constructs a syntax tree, converts the regex to an NFA, and then transforms the NFA into a DFA for pattern recognition. It processes the input regex, builds a transition table, and generates a deterministic finite automaton (DFA) to efficiently recogni...
def __init__(self, filename): """ Initializes a RegEx object from the specifications in the file whose name is filename. """ self.operators = {'|', '*'} self.alphabet = {'e': 'e'} file1 = open(filename, 'r') temp = file1.readline()[:-1] for char in temp: self.alphabet[char] = char self.regex = f...
def display_genres(self, move=False): """ Write the elements of lst_genres on the screen Write the elements of lst_genres on the screen height = genres_height, and as lst_genres has an odd number of elements, write the middle one differently move --True if the last user...
The function updates the UI based on movement along a specified axis. It refreshes the screen, updates movement status, adjusts album lists when the 'x' axis moves, and displays genres/albums accordingly. It handles navigation logic for UI elements like albums and genres, resetting indices and redrawing content based o...
def display_ui(self, axis='', movement=None): """ Set movement attributes and display albums based on which axis moved axis -- which axis was moved movement -- True if down, right and False if up, left """ self.screen.refresh() self.screen.clear() if mov...
def cache_gradient(self, x_grad: ti.types.ndarray(), v_grad: ti.types.ndarray(), C_grad: ti.types.ndarray(), F_grad: ti.types.ndarray()): for p in range(self.n_particles[None]): for i in ti.static(range(self.dim)): ...
The code retrieves a cached state from memory, resets gradients of particle attributes (position, velocity, etc.), applies the retrieved state, performs substeps for computation, and prepares gradients for backpropagation, ensuring gradient isolation between steps.
def pop_from_memory(self): if self.dtype == ti.f32: dtype=torch.float32 else: dtype=torch.float64 x_grad = torch.zeros([self.n_particles[None], self.dim], dtype=dtype) v_grad = torch.zeros([self.n_particles[None], self.dim], dtype=dtype) C_grad = torch.zer...
def pop_from_memory(self): if self.dtype == ti.f32: dtype=torch.float32 else: dtype=torch.float64 x_grad = torch.zeros([self.n_particles[None], self.dim], dtype=dtype) v_grad = torch.zeros([self.n_particles[None], self.dim], dtype=dtype) C_grad = torch.zer...
This code performs a gradient computation substep in a simulation, handling grid operations, SVD, and projections. It processes data chunked by `cuda_chunk_size`, deactivating grids, computing temporary values, performing SVD, projection, and grid operations. It then clears SVD gradients and computes gradients for `p2g...
def substep_grad(self, s): local_index = s % self.cuda_chunk_size if local_index == self.cuda_chunk_size-1: self.pop_from_memory() self.grid.deactivate_all() self.compute_F_tmp(local_index) self.svd() self.project_F(local_index) self.p2g(local_index) ...
def __lowest_max_dist(self, b_idx): """Compute lowest max dist of a given bin""" lowest_max_dist = None for s in self.seeds: max_dist = self.__max_distance(s, b_idx) if not lowest_max_dist or max_dist < lowest_max_dist: lowest_max_dist = max_dist r...
This method assigns points to a bin by determining the lowest maximum distance for the bin, identifying candidate points within that distance, and then assigning those points to the bin.
def __assign_bin_seeds(self, b_idx): """Assign a bin to its correspondent seeds""" lowest_max_dist = self.__lowest_max_dist(b_idx) candidates = self.__bin_candidates(b_idx, lowest_max_dist) self.__assign_bin_points(b_idx, candidates)
def __get_nonzero_bins(self): """Get all the non empty bins and their indexes""" nozero_idx = np.where(self.bins != 0) nozero_bins = self.bins[nozero_idx] return nozero_bins, nozero_idx[0] def __assign_bin_seeds(self, b_idx): """Assign a bin to its correspondent seeds""" ...
This function assigns data points in non-zero bins to their respective cluster seeds and recalculates the seed positions based on the assigned points, forming part of an iterative clustering algorithm like k-means.
def __center_assignment(self): """Assign points to their respective seeds""" self.seed_points = [[] for _ in range(len(self.seeds))] self.seeds_prev = np.copy(self.seeds) _, nonzero_idxs = self.__get_nonzero_bins() for b_idx in nonzero_idxs: self.__assign_bin_seeds(b...
def __quantization(self, X): """Quantize the input data""" self.__init_bins(X) bin_idxs = np.apply_along_axis(self.__quantize_sample, axis=1, arr=X) for idx, p in zip(bin_idxs, X): self.bins[idx] += 1 self.bins_points[idx].append(p) def __center_initialization(sel...
The code performs clustering by iterating until convergence or max iterations, initializing cluster centers, assigning data points to clusters, and checking stopping criteria based on a threshold. It quantizes input data, updates cluster centers, and tracks iterations, returning the trained model once criteria are met.
def fit(self, x): """Start clustering process untill ending criteria is met""" self.n_iter_ = 0 end_value = self.thr + 1 self.__quantization(x) self.__center_initialization(self.n_seeds) while end_value > self.thr and self.n_iter_ < self.max_iter: self.__cente...
def __createCoefMatrix(self, df): corr = np.zeros(shape=(settings.n, settings.n)) conv = self.__createConvMatrix(df) for i in range(settings.n): for j in range(settings.n): corr[i][j] = self.__calcCorrelationCoef(conv[i][i], conv[j][j], conv[i][j]) return cor...
The function generates a graph structure from a given data window by creating a correlation matrix (with optional shrinkage), converting it to a distance matrix, and constructing a specified graph type (MST, threshold graph, or minimal edges graph). It returns the correlation matrix, distance matrix, and graph componen...
def __pickWindowResults(self, window, graph_type=GraphTypes.MST, shrinkage_type=ShrinkageTypes.NO_SHRINKAGE): corrMatrix = np.zeros(shape=(settings.n, settings.n)) if shrinkage_type == ShrinkageTypes.NO_SHRINKAGE: corrMatrix = self.__createCoefMatrix(window) elif shrinkage_type == Sh...
def extract_img_feat(self, img, img_metas): """Extract features of images.""" input_shape = img.shape[-2:] # update real input shape of each single img for img_meta in img_metas: img_meta.update(input_shape=input_shape) if img.dim() == 5 and img.size(0) == 1: ...
The code computes the total loss for training a multi-branch model that processes images, point clouds, and their fusion for 3D object detection. It extracts features from images and points, calculates losses for each branch (image, point cloud, fused features), and combines them into a final loss for optimization.
def forward_train(self, img, img_metas, points, coords_list, gt_bboxes2d_cam_list, gt_labels2d_cam_list, gt_bboxes_3d_cam_list, centers2d_cam_li...
def extract_img_feat(self, img, img_metas): """Extract features of images.""" input_shape = img.shape[-2:] # update real input shape of each single img for img_meta in img_metas: img_meta.update(input_shape=input_shape) if img.dim() == 5 and img.size(0) == 1: ...
The function performs 3D object detection by separately processing image and LiDAR data, then fusing their features. It extracts image features for camera-based predictions, processes LiDAR points for point-cloud predictions, and combines both modalities for fused results. Each prediction uses corresponding heads (img_...
def simple_test(self, imgs, img_metas, points, coords_list, rescale=False, **kwargs): """Test function without test-time augmentation. Args: img (torch.Tensor): Images with shape (N, C, H, W). img_metas dict: image information. rescale (bool, optional): Whether to re...
def move_ee_to_pre_grasp(self, ee_pos, ee_orientation): # pre grasp is 15cm back from the object in end effector coordinates # get orientation rotation matrix: R = scipy.spatial.transform.Rotation.from_euler('xyz', ee_orientation).as_matrix() # get pre grasp position in world coordinates...
The code attempts to grasp an object using specified end-effector parameters by moving to a pre-grasp pose, transitioning to a grasp pose, closing the gripper, and simulating the action. It compares the object's initial and final positions to determine grasp success, returning a boolean result.
def try_grasp(self, ee_pos_table, ee_orientation) -> bool: ''' try a grasp with the current object pose and a given grasp parameters, return whether successful''' ee_pos = table2world(ee_pos_table) start_time = time.time() initial_obj_pos = self.m_obj.get_position().copy() # TO...
def zip_coords(self, values: list) -> list: """ Combines list in to [x, y] coordinates Parameters ---------- values: list - a list of values, parsed from input text file Returns ------- coordinates: list - list of coordinates e.g. [[x1, y1], [x2, y2]...] """ # col or x is second value in list, hen...
This code reads a text file to initialize a game board object. It parses lines for board dimensions, walls, boxes, storage locations, and player start position. Data is converted to integers, stored as attributes, and plotted on a 2D board array. The function handles file paths, error exceptions, and sets initial game ...
def read_file(self, path: str = "") -> None: """ Parses data from input text file. Initializes object from file data Parameters: ---------- path: str - path to input file """ try: file = open(path) lineNum = 0 for line in file: data = line.split(" ") data = [int(x) for x in data] # cast ...
def isValid(self, coords, move) -> bool: """ Checks if move is into a wall or if move is out of bounds of environment Parameters: ----------- coords: list in [x, y] format starting at index 1 move: "u" | "d" | "l" | "r" Returns: ------- isValid: bool - if move coordinates + move are valid """ mo...
The code moves a player on a grid in a specified direction, updates their coordinates, and checks for valid moves. It handles collisions with boxes by attempting to move them if valid, calculates rewards based on box movements and storage interactions, updates the game board state, and returns the reward along with a t...
def move(self, move: str=None, coords: list = None): """ Moves the players coordinates in a given direction Parameters ---------- move: str - "u" | "d" | "l" | "r" e.g. direction in which the player is to move objectCoords: list - list of [x, y] coordinates for object. Intended objects are those that...
def _determine_majority_vote(self, y): """ Finds the most common label from the target labels. Parameters: y (numpy.ndarray): target labels of the data Returns: (float): the most common label value """ counts = np.bincount(y.astype(int)) ...
This function recursively constructs a decision tree using the ID3 algorithm by selecting the optimal feature and threshold to split the dataset. It checks termination conditions like maximum depth, uniform labels, or insufficient samples, then recursively builds left and right subtrees. The process continues until lea...
def _build_tree(self, X, y, depth=0): """ Recursively builds a decision tree using the ID3 algorithm. Parameters: X (numpy array): Feature matrix of shape (n_samples, n_features). y (numpy array): Label matrix of shape (n_samples,) depth (int, optional): Curr...