dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def deal(deck,playerList): """Deals 2 cards to each player, removing them from the deck""" for player in playerList: if not player.busted: player.holeCards += drawX(2,deck) def bettingRound(playerList,highestBet,activePlayer,pot,limit,printing = True): """Handles a betting round of a sin...
The function `gameRound` simulates a complete round of poker, handling blinds, betting rounds (preflop, flop, turn, river), community card dealing, determining winners via hand comparison, and resolving pot distribution. It supports both multi-player and heads-up scenarios, with optional printing and analysis features ...
def gameRound(*args): """Performs one full round of poker""" deck = args[0] playerList = args[1] bigBlind = args[2] buttonPos = args[3] limit = args[4] printing = args[5] analysing = args[6] pot = 0 if len(playerList) > 2: activePlayer = (buttonPos + 3) % len(playerL...
def can_generate_cycling_graph(mongodb): return {'restaurants_view', 'segments_view', 'junctions_view'}.issubset(mongodb.list_collection_names()) def _connect_to_graph(): return Graph( os.environ.get('NEO4J_URI'), auth=(os.environ.get('NEO4J_USERNAME'), os.environ.get('NEO4J_PASSWORD')), ...
The main task of the code is to generate a cycling graph from MongoDB data. It checks if generation is possible, connects to a graph database, clears existing data, initiates a transaction, creates the graph using MongoDB data, commits the transaction, and confirms completion. The function ensures a clean graph state b...
def generate_cycling_graph(mongodb): if can_generate_cycling_graph(mongodb): print('Generating cycling graph...') graph = _connect_to_graph() graph.delete_all() transaction = graph.begin() _generate_cycling_graph(mongodb, transaction) graph.commit(transaction) ...
def display_welcome(self): print("Welcom to Robots vs. Dinosaurs") def battle(self): while len(self.herd.dinosaur) > 0 and len(self.fleet.robot) > 0: self.robo_turn() self.dino_turn() def diplay_winners(self): if len(self.fleet.robot) > len(self.herd.dinosaur): ...
The main task of the code is to execute a game sequence: display a welcome message, initiate the battle mechanics, and finally show the winners. The method orchestrates the game flow by sequentially calling three functions—`display_welcome()` to greet the player, `battle()` to handle gameplay logic, and `diplay_winners...
def run_game(self): self.display_welcome() self.battle() self.diplay_winners()
def _log(level, text): ''' logging function ''' global LOG_STATE if type(level) is str: level = _LOG_STATES[level] if level < LOG_STATE: return if level == _LOG_STATES['DEBUG']: print('[d: ---') print(text) print('--]') input('↵ to continue') else:...
The main task of the code is to train a neural network model with configurable parameters, including seed setting, parallel processing, TensorBoard logging, and model saving. It initializes the environment, loads datasets, creates the model, configures optimizers, and trains the model if specified. Debugging logs and p...
def main(args): ''' main body ''' if args.seed is not None: _log('STATUS', f'Setting seed as {args.seed}') torch.manual_seed(args.seed) generate_run_name(args) if args.tensorboard: writer = initialise_tensorboard_writer(args.run_name) if args.parallel: # this doesn't work...
def prepare_dataset_loader(args): ''' ''' _log('VERBOSE', 'Setting up dataset for prediction') transforms = DefaultTransformation( args.nb_patches, args.patch_size, args.crop_size) image_folder = generate_predict_dataset( args.base_dir, is_valid_file=is_valid_file, trans...
The main task of the code is to evaluate a machine learning model on a dataset. It prepares a data loader, creates a model with specified classes, selects a computation device (CPU/GPU), evaluates the model's performance, and saves the resulting class predictions. The process includes logging status and debugging infor...
def main(args): ''' main body ''' predict_loader = prepare_dataset_loader(args) model = create_model(args, args.nb_classes) # generate device device = torch.device('cuda' if torch.cuda.is_available() else "cpu") _log('STATUS', f'Using device {device}') _log('DEBUG', 'Is this right ?') ...
def pelvis_dense_text_control_example(n_frames=120, raw_mean=None, raw_std=None, index=0): text = [ # pelvis 'a person plays a violin with their left hand in the air and their right hand holding the bow', 'a person plays a violin with their left hand in the air and their right hand holding t...
The code generates multiple sets of text prompts and spatial control signals (hints) for motion generation, based on the specified dataset (humanml/kit). It loads normalization parameters, calls various motion-control example functions (e.g., pelvis, wrist, head movements, unnatural motions), concatenates their outputs...
def collate_all(n_frames, dataset): if dataset == 'humanml': spatial_norm_path = './dataset/humanml_spatial_norm' elif dataset == 'kit': spatial_norm_path = './dataset/kit_spatial_norm' else: raise NotImplementedError('unknown dataset') raw_mean = np.load(pjoin(spatial_norm_path,...
def Rand(start, end, num): res = [] for j in range(num): res.append(random.randint(start, end)) return res def qsort(arr): return arr if len(arr) <= 1 else qsort([x for x in arr[1:] if x < arr[0]]) + [arr[0]] + qsort([x for x in arr[1:] if x >= arr[0]]) def insertionSort(arr): for i in range...
The main task of the code is to compare the performance of quicksort, insertion sort, and a hybrid sorting algorithm across varying input sizes (1 to 100 items). It runs each algorithm 5,000 times per input size, averages their execution times, and generates a plot to visualize the average runtime differences. The goal...
def main(): NUM_ITEMS_LIST = [] quick = [] insert = [] hyb = [] random_lists = [] num_iterations = 5000 for NUM_ITEMS in range(1,101): NUM_ITEMS_LIST.append(NUM_ITEMS) random_lists = [] for i in range(num_iterations): random_lists.append(Rand(1, 9000, ...
def gini(rows): # Calculate the Gini Ipurity for a list or rows. # there are many ways to find the Gini. # See: https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity counts = class_counts(rows) impurity = 1 for lbl in counts: prob_of_lbl = counts[lbl] / float(len(rows)...
The function identifies the optimal feature-value split in a dataset to maximize information gain, using Gini impurity as the measure of uncertainty. It iterates through all features and their unique values, partitions the data, calculates the gain from each split, and returns the split with the highest gain and corres...
def find_best_split(rows): # Find the best question to ask by iterating over every feature/value # and calculating the information gain. best_gain = 0 # keep track of the best infromration gain. best_question = None # keep train of the feature/value that produced it current_uncertainty = gini(rows...
def find_best_split(rows): # Find the best question to ask by iterating over every feature/value # and calculating the information gain. best_gain = 0 # keep track of the best infromration gain. best_question = None # keep train of the feature/value that produced it current_uncertainty = gini(rows...
This function constructs a decision tree by recursively partitioning a dataset based on the attribute-value that yields the highest information gain. It splits the data into true/false subsets, builds branches for each, and returns a decision node with the optimal question and its resulting branches. If no further spli...
def build_tree(rows): # Try partitioing the dataset on each of the unique attribute, # calculate the information gain, # and return the question that produces the highest gain. gain, question = find_best_split(rows) # Since there ara no more questons, going to return the leaf. if gain ...
def stepwiseRegression (trainingFaces, trainingLabels, testingFaces, testingLabels): features = 5 range_setter = range(0,24) best_feature = None best_predictor = None target_score = [] predictors = [] for _ in range(features): best_feature = None best_predictor = None ...
The main task of the code is to evaluate the performance of a stepwise regression model across varying training sample sizes (400, 800, ..., 2000). For each sample size, it trains predictors using training data, measures training and testing accuracies, and prints results. Finally, it visualizes selected features and r...
def createOutput(trainingFaces, trainingLabels, testingFaces, testingLabels): #Sample sizes start_time = time.time() sample_n = [400,800,1200,1600,2000] predictors = None print("n trainingAccuracy testingAccuracy") for _ in sample_n: #Which predictors where used predictors ...
def get_sites_for_state(state_abbr): state_abbr = state_abbr.upper() for stateInfo in master: if (stateInfo[0] == state_abbr): stateUrl = stateInfo[1] #CACHING npsStateId = create_id("States", "Parks", stateUrl) cache_file = "parks.json" cache = Cache(cache_file) stateRe...
The main task of the code is to provide a menu-driven program that allows users to search for national parks by state abbreviation, find nearby parks using zip codes, plot parks on a map, or exit. It handles user input validation, retrieves park data, and interacts with functions to display results or generate visualiz...
def main(): print("Welcome to the program! This program allows you to browse national parks near you!") print("-------------Instructions for Commands-------------") print("1. Find National Parks in the State you specify:") print("Please input the abbreviation of a state to give you a list of all nationa...
def _moviento_completo(self): zh=self.env.user.tz product="and sm.product_id=%s" local_des = "" location_id = "" compan="and sm.company_id=%s " if self.aplica == "todas": local_des = "and sm.location_dest_id >%s" location_...
This function retrieves product movement data from a database using dynamic SQL queries, filters records by date ranges and location, extracts detailed transaction information (quantities, costs, dates, users), links related invoices, and updates kardex records with this data to track inventory movements and financial ...
def _movimiento_producto(self): query_total = self._moviento_completo() query_movimiento = """ select * from ( """ + query_total + """ ) as mov where date >=%s and date <=%s """ producto = self.product.id ubicacion = 0 compan=self...
def load_model_at_epoch(self, epoch='best'): model_name, self.best_loss_epoch, self.best_loss =\ get_epoch_and_loss(self.args.work_dir, epoch=epoch) model_found = False try: loaded_vars = torch.load(os.path.join(self.args.work_dir, model_name)) self.model.load...
The code trains a model by iterating through epochs, performing training and evaluation phases, and saving models based on loss updates or intervals. It optionally loads a pre-trained model from a specified epoch or the best-performing one, adjusting the starting epoch accordingly. During training, it logs progress, co...
def train(self): if self.args.load_last_best: model_found = self.load_model_at_epoch(epoch=self.args.start_epoch) if not model_found and self.args.start_epoch is not 'best': print('Warning! Trying to load best known model: '.format(self.args.start_epoch), end='') ...
def getMessInfo(self, messFile): with open(messFile, encoding='latin-1') as csvFile: csvReader = csv.reader(csvFile, delimiter=';') data = [] for row in csvReader: data.append(row) monitor = data[1][-1] time = data[7][-1] time = time....
The code fits Gaussian or double-Gaussian profiles to monitor data files, extracting beam parameters (mean, width) and uncertainties. It processes multiple files, applies curve fitting with initial guesses, handles specific monitors (e.g., G3DG3G, H3DG3G), and stores results for plotting or further analysis.
def fitProfiles(self, monitor, showProfiles=False, skipShots=1, plot=True): """ Fits the monitor profiles with a Gauss peak """ # Uncomment to plot beam profiles # showProfiles=True gitterFiles = glob.glob((self.monitorPath+monitor+'/*')) gitte...
def get_server_status(): url = f'https://turbiditech.fly.dev/api/device-records/{DEVICE_ID}' r = requests.get(url, auth=(EMAIL, PASSWORD)) if r.status_code == 200: data = r.json()[-1] v_stat = data['valve_status'] w_stat = data['water_status'] return v_stat, w_stat else: return r.status_co...
The main task of the code is to monitor a server for valve status changes, check water turbidity via `get_device_water_status()`, and control a solenoid valve (via `led`) based on server and water conditions. If the server commands the valve "off," it complies. If "on," it only activates the valve when water is clean, ...
def main(): # assign pin for solenoid valve led = {'value': 1} while True: # check server for changes in the valve status print('getting server valve status.') server_v_stat, server_w_status = get_server_status() # the valve is normally turned ON # if valve was turned off turn off valve...
def validate(self): # def validate(): #TODO # assert isinstance(pipeline, Pipe) # if not bool(pipeline.steps): # raise ValueError(f"There are no steps for run...") pass def build_pipe(self) -> Pipe: pipe_instance = Pipe( name = self.settingsp...
The code's main task is to initialize and deploy a pipeline. It first validates input parameters, constructs a pipeline using `build_pipe()`, and then publishes the pipeline for execution or distribution. This sequence ensures proper preparation and deployment of the pipeline workflow.
def start(self): self.validate() pipe = self.build_pipe() self.publish(pipeline=pipe)
def setMiRNAs(self, maturefagz_path, seedStart, seedEnd, minor=True, p5=True, p3=True): # Read in miRNAs: miRNAs are labeled by the hsa-* names and grabbing 2-8bp ### Could merge these as they come in so that don't do redundant, and also so that the labels are together with gzip.open(maturefagz_...
The code initializes a miRvestigator analysis to evaluate microRNA (miRNA) seed sequence matches against 3' UTRs using position-specific scoring matrices (PSSMs). It trims miRNA sequences into 6mer, 7mer, and 8mer variants, filters valid k-mers present in 3' UTRs, and employs multiprocessing to compute match scores. Re...
def __init__(self, pssms, seqs3pUTR, maturefagz_path, seedModel=[6, 7, 8], minor=True, p5=True, p3=True, textOut=True, wobble=True, wobbleCut=0.25, baseDir='', outName='', use_multiprocessing=True): print('\nmiRvestigator analysis started...') ...
def get_access_token(): return find_one(settings.token_collection_name, {'_id': TOKEN_ID}) def insert_one(collection_name: str, query: dict) -> None: db[collection_name].insert_one(query) def update_one(collection_name: str, query: dict, update: dict): collection = db[collection_name] update['modified_...
This function stores or updates an access token in a database. It assigns a unique ID, adjusts the expiry time by subtracting 5 seconds, and either inserts the token if none exists or replaces the existing entry with the updated token data.
def store_access_token(token: dict): token['_id'] = TOKEN_ID token['expiry_date'] = datetime.utcnow() + timedelta(0, token['expires_in'] - 5) if not get_access_token(): insert_one(settings.token_collection_name, token) else: update_one(settings.token_collection_name, {'_id': TOKEN_ID}, t...
def load_config(self): ''' Called to ensure the config is kept up to date even when loading a previous save point ''' # Load configuration. self.config = configparser.ConfigParser() self.config.read('mario.config') self.enable_human_intervention = self.config['DEFAULT'].getboolea...
The code runs a NEAT-based evolutionary algorithm for up to 150 generations, evaluating genome fitness, tracking the best genome, detecting stagnation, and enabling human intervention. It iterates through populations, updates generations, saves statistics, and checks for mid-point stagnation to optimize neural network ...
def run(self, fps=-1, gen_stats=True): ''' The main loop ''' # Reload the configuration in case it has changed from the previous run. self.load_config() prev_best_fitness = None stagnation_count = 0 while True: if self.neat.generation > 150: ...
def load_true_labels(dataset_name): traindev_path = os.path.join("semeval_2017task8", "semeval2017-task8-dataset", "traindev") data_files = {"a_dev": os.path.join(traindev_path, "rumoureval-subtaskA-dev.json"), "a_train": os.path.join(traindev_path, "rumoureval-subtaskA-train.json"), ...
The code preprocesses social media data by converting tweet and comment texts into vector representations, organizing claims and their associated comments with corresponding labels (a and b), and saving them as structured numpy files for training and evaluation. It separates true/false claims, maps user IDs, and ensure...
def preprocess_data(): # Load tweetid and labels a_train = load_true_labels("a_train") a_dev = load_true_labels("a_dev") a_test = load_true_labels("a_test") dataset = {} dataset['train'] = a_train.keys() dataset['dev'] = a_dev.keys() dataset['test'] = a_test.keys() b_train = load_t...
def learned_affinity(preds, n_people): A = np.zeros((n_people, n_people)) idx = 0 for i in range(n_people): for j in range(n_people): if i == j: continue A[i,j] += preds[idx]/2 A[j,i] += preds[idx]/2 idx += 1 return A def vector_climb(A, allowed, n_people, thres=1e-5): x = np.random.uniform(0,1,n_p...
The function groups individuals based on predicted affinities, iteratively removing detected groups from consideration until only one remains, then processes these groups for output. It uses an affinity matrix, filters connections based on allowed individuals, and applies a vector-climbing method to identify cohesive s...
def ds(preds, n_people, thres=1e-5): allowed = np.ones(n_people) groups = [] A = learned_affinity(preds, n_people) while (np.sum(allowed) > 1): A[allowed == False] = 0 A[:,allowed == False] = 0 if (np.sum(np.dot(allowed,A)) == 0): break x = vector_climb(A, allowed, n_p...
def length(rule): return len(rule)-1 def closed(rule): return rule[-1] == 1 def pca_confidence(rule): sup, pca_num = support(rule, PCA=True) return (sup/pca_num)
This function checks if adding an element to a rule increases its confidence. It creates a modified "parent" rule by removing the second-to-last element, adjusts it if closed, then compares the confidence of the original "child" rule against the parent's confidence. Returns True if child confidence exceeds parent confi...
def conf_increase(rule): if length(rule) == 2: return True parent = deepcopy(rule) del parent[-2] if closed(rule): parent[-1] = 0 parent_conf = pca_confidence(parent) child_conf = pca_confidence(rule) return child_conf>parent_conf
def closed(rule): return rule[-1] == 1 def length(rule): return len(rule)-1 def support(rule, PCA=False): lenth = length(rule) close = closed(rule) if lenth == 2: r0 = rule[0] r1 = rule[1] if close: sup = len(r2ht[r0].intersection(r2ht[r1])) else: ...
The function `decodeRules()` processes association rules from a queue, formatting and printing each rule's details. It retrieves rules from `outputQ`, verifies their closure, constructs human-readable rule strings, and prints metrics like support, HC, and PCA confidence. It counts and reports the total number of learne...
def decodeRules(): num_rules = 0 print('RULE SUPP HC CONF_pca') while not outputQ.empty(): rul = outputQ.get() num_rules += 1 assert closed(rul) rul_rs = deepcopy(rul) del rul_rs[-1] rule_str = '' for i,r in enumerate(rul[:-1]): r =...
def closed(rule): return rule[-1] == 1 def pca_confidence(rule): sup, pca_num = support(rule, PCA=True) return (sup/pca_num) def conf_increase(rule): if length(rule) == 2: return True parent = deepcopy(rule) del parent[-2] if closed(rule): parent[-1] = 0 parent_conf = pca_confide...
The main task of the code is to determine whether a given rule meets specific criteria for acceptance. It checks if the rule is closed, has PCA confidence above a threshold (minConf), and shows confidence improvement. If all conditions are satisfied, the rule is accepted for output.
def acceptedForOutput(rule): if not closed(rule): return False elif pca_confidence(rule) < minConf: return False elif not conf_increase(rule): return False else: return True
def length(rule): return len(rule)-1 def acceptedForOutput(rule): if not closed(rule): return False elif pca_confidence(rule) < minConf: return False elif not conf_increase(rule): return False else: return True def closed(rule): return rule[-1] == 1 def addingDang...
The code processes rules from an input queue, filtering those with length >1 and acceptable for output, then generating new rules by adding atoms if the current rule isn't closed and under a max length, placing them back in the input queue. It terminates when the input queue is empty, signaling task completion.
def task(inputQ, outputQ): while True: if not inputQ.empty(): rule = inputQ.get() if length(rule)!=1 and acceptedForOutput(rule): outputQ.put(rule) if length(rule)<maxLen and not closed(rule): for rul in addingDanglingAtom(rule): inputQ...
def tinydecrypt(code,key): try: keyi = code2indexlist(key) codelen=len(code) keylen=len(keyi) eachchar=code[0] keyoffset=keyi[0] lencode=cryptchar(eachchar,keyoffset,DECRYPT) totlen=mychars.index(lencode) encind=mychars.index(code[0]) textlen=(...
This function processes nested list data structures, allowing users to encode/decode values using a provided key. It recursively handles lists, treating even-indexed elements as labels and odd-indexed elements as data to edit. Users can input passwords, encode data, decode values, or proceed through a menu system. Erro...
def dataedit(data, key, level=0): '''update data based on key and input''' if type(data) == type([]): if len(data) == 0: print("ERROR - empty list",data) elif (len(data) % 2) == 1: print("ERROR - not even number of list members",data) else: for i,v in ...
def chosen_direction(self): output_vector = self.compute_layers() max_index = np.argmax(output_vector) return max_index def check_for_apple(self): environment = self.environment individual = self.individual if individual.snake_head_coordinates != environment.apple_positi...
This method updates a snake's position based on its chosen direction, adjusts its body coordinates, checks for apple consumption or collisions with borders/self, and terminates the snake if necessary while calculating fitness. It also updates the snake's heading, manages its lifespan, and prepares data for the neural n...
def update_individual_epoch(self): individual = self.individual environment = self.environment #Call the method that handles the choosing of the snakes next position direction = self.chosen_direction() #Based on the current state of the snake and given the new direction that it...
def parse(datafile): adj_list = [] with open(datafile) as f: num_vertices, num_edges, weighted = map(int, f.readline().split()) for i in range(num_vertices): adj_list.append(map(int, f.readline().split())) return adj_list def create_graph(adj_list): G = nx.Graph() for i in range(len(adj_list)): for j in a...
The code solves the vertex cover problem using a branch-and-bound algorithm on a graph derived from an input file. It reads the graph, computes an approximate vertex cover solution with a time cutoff, filters out invalid nodes, and writes the solution and execution times to specified output files. The task involves gra...
def main(inputfile, output_dir, cutoff, randSeed): #READ INPUT FILE INTO GRAPH adj_list = parse(inputfile) # CONSTRUCT THE GRAPH BASED ON ADJACENT LIST g = create_graph(adj_list) # datafile = '../Data/karate.graph' # adj_list = parse(datafile) # g = create_graph(adj_list) print('No of nodes in G:', g.numbe...
def get_readings(line): return eval(line) def get_all_detectors_speeds_readings(readings): detector_ids = list(readings.keys())[1:] speed_readings = {} for id in detector_ids: speeds = get_speed_readings(readings[id]) speed_readings[id] = speeds return speed_readings def get_all_dete...
The main task of the code is to process a line of data by extracting time-stamped speed readings from detectors, calculate their mean speeds, and append the results to a global DataFrame (`data`) for aggregation. If no valid mean speeds are found, the function exits early. The process involves parsing input data, compu...
def populate_data(file_line): readings = get_readings(file_line) current_time = readings['time'] speed_readings = get_all_detectors_speeds_readings(readings) mean_speeds = get_all_detectors_mean_speeds(speed_readings) if mean_speeds == {}: return global data data.columns = reading...
def hour_reached(self): if self.is_hour_reached() and not self.is_week_reached(): if self.current_reading['time'] != 0: self.current_hour += 1 if self.current_hour != 0: self.update_hourly_reading() detector = self.simulator.get_detector_by...
The code updates the current reading with incoming data and triggers checks for whether an hour, day, or week threshold has been reached, likely to initiate corresponding actions or updates.
def update(self, data): self.current_reading = data self.hour_reached() self.day_reached() self.week_reached()
def premade_inventory(self)-> inventory: """Premade Inventory that will be assigned to player at the start of the game""" invent = inventory(self.premade_item('axe')) return invent def premade_location(self,location_name:str)->Location: """Pre defined Location to be assigned""" i...
This code initializes a game entity with attributes like health, inventory, location, hydration, energy, and experience. It sets starting values, prepares actions (e.g., 'scout', 'inventory'), and initializes game state variables (turn, day, subject) for gameplay mechanics.
def __init__(self,max_hp): super().__init__(max_hp) self.inventory=self.premade_inventory() self.location:Location=self.premade_location('wild') self.turn = 0 self.equip:item or None = None self.hydration = (self.hp)/10 self.energy = (self.hp)/10 self.xp =...
def change_xaxis(self): """Change the x-axis scale of the initial empty chart to mimic the underlying data.""" axis_label = self.xaxis_comboBox.currentText() if axis_label != 'None': values = self.data[axis_label] self.axis_x = self.utility.change_axis(axis_label, values,...
This function manages axis settings based on the selected plot type. If the plot type is "None", it updates the x or y axis. Otherwise, it applies date-specific settings for x, y, or group_by axes, then triggers data plotting for the specified axis.
def slot_manager(self, axis): if self.plot_type_comboBox.currentText() == "None": if axis == "x": self.change_xaxis() else: self.change_yaxis() else: if axis == "x": self.change_xaxis_date_setting() elif axis...
def __setup_dist(): if not os.path.exists("dist"): os.mkdir("dist") copy_tree("root", "dist") def __copy_static(): if os.path.exists("./static"): copy_tree("./static", "dist/static") if os.path.exists("./templates/robots.txt"): copy_file("./templates/robots.txt", "dist/robo...
The main task of the code is to generate a website by reading site data, setting up directories, copying static assets, generating HTML pages, CSS files, sitemaps, and bundling resources. It orchestrates the build process through a sequence of helper functions to create a fully structured static site.
def generate(): site = read_site() __setup_dist() __copy_static() __generate_pages(site) __generate_css(site) __generate_pages(site) __generate_sitemap(site) __generate_bundle(site)
def print_card(): number_value = (numberdic[random.randint(1,13)]) suit_value = (numberdic[random.randint(14,17)]) return [number_value, suit_value] def call_fold(chose_call_fold): if chose_call_fold == "fold" or chose_call_fold == "Fold": print("You have folded, thus you lose automatically. The...
The code simulates a simplified poker game by generating 7 unique cards, displaying 3 base cards and 2 of the player's cards, then processing a call/fold decision to reveal house cards and execute game logic if the player calls.
def play_poker(options): if (options == "start") == True: #make cards card_list = [] while len(card_list) < 7: a = print_card() if a not in card_list: card_list.insert(0,a) #card list dc1 = card_list[0] dc2 = card_list[1] ...
def next(): nextIndex = selected_index + 1 if nextIndex < songs.count(): select(nextIndex) def previous(): nextIndex = selected_index - 1 if nextIndex >= 0: select(nextIndex) def togglePlay(): global playing if not selected_midi: return playing = not playing upd...
The code continuously monitors three GPIO pins for button presses. When a button (NEXT, PREV, or PLAY) is pressed, it triggers corresponding actions: `next()`, `previous()`, or `togglePlay()`. The loop runs indefinitely, checking pin states every 0.2 seconds to ensure real-time responsiveness while preventing excessive...
def buttons(): while True: if (GPIO.input(NEXT_PIN) == False): next() if (GPIO.input(PREV_PIN) == False): previous() if (GPIO.input(PLAY_PIN) == False): togglePlay() time.sleep(0.2)
def var_validation(): """Validate variables.""" if SUBDOMAIN in ["", "accuhive"]: print( f'\nThe subdomain "{SUBDOMAIN}" in {BASE_URL} needs to be updated to ' "your Kandji tenant subdomain..." ) print("Please see the example in the README for this repo.\n") ...
The code retrieves device inventory and parameters from the Kandji API, aggregates device details with parameter data, and exports the results to a CSV report. It validates inputs, iterates through devices to collect parameter assignments, counts devices with parameters, and generates a dated report file.
def main(): """Run main logic.""" # validate vars var_validation() print("") print(f"Base URL: {BASE_URL}") print("") # dict placeholder for params passed to api requests params_dict = {} # Get all device inventory records print("Getting device inventory from Kandji...") d...
def program_arguments(): """Return arguments.""" parser = argparse.ArgumentParser( prog="installed_apps", description=( "Generates a report containing devices with a specific app installed or a " "report containing all installed apps." ), allow_abbrev=Fals...
The main task of the code is to generate a CSV report of app installations on devices from Kandji. It processes command-line arguments, validates inputs, fetches device inventory data, filters installed apps (specific or all), creates a structured report payload, and writes the output to a CSV file named based on the i...
def main(): """Run main logic.""" # Return the arguments arguments = program_arguments() var_validation() print(f"Version: {__version__}\n") print(f"Base URL: {BASE_URL}\n") # dict placeholder for params passed to api requests params_dict = {} # Report name if arguments.name:...
def program_arguments(): """Return arguments.""" parser = argparse.ArgumentParser( prog="devices_report", description=( "This tool is used to generate a device report based on the GET Devices " "API endpoint for all devices in a Kandji tenant. If you're looking for " ...
The main task of the code is to generate a CSV report of device inventory data from Kandji, either for a specified platform or all devices. It processes command-line arguments, validates inputs, retrieves device records, compiles device details, and exports the results to a CSV file with platform-specific naming. The s...
def main(): """Run main logic.""" # Return the arguments arguments = program_arguments() var_validation() print(f"\nRunning: {SCRIPT_NAME} ...") print(f"Version: {__version__}\n") print(f"Base URL: {BASE_URL}\n") # dict placeholder for params passed to api requests params_dict = {...
def program_arguments(): """Return arguments.""" parser = argparse.ArgumentParser( prog="device_details", description=( "Generate reports containing information from the device details API." ), allow_abbrev=False, ) query_options = parser.add_argument_group( ...
The main task of the code is to generate a CSV report of device details from Kandji, filtering by parameters like ADE eligibility, auto-enrollment, activation locks, OS versions, and more. It processes command-line arguments, queries device inventory, extracts relevant details, and compiles the data into a report with ...
def main(): """Run main logic.""" # Return the arguments arguments = program_arguments() # validate vars var_validation() print(f"\nScript Version: {__version__}") print(f"Base URL: {BASE_URL}") # holds params passed to devices enpoint device_params = {} # holds params used ...
def var_validation(): """Validate variables.""" if SUBDOMAIN in ["", "accuhive"]: print( f'\nThe subdomain "{SUBDOMAIN}" in {BASE_URL} needs to be updated to ' "your Kandji tenant subdomain..." ) print("Please see the example in the README for this repo.\n") ...
The code's main task is to retrieve device secrets (e.g., FileVault keys, unlock PINs, bypass codes) from Kandji based on user-specified criteria (serial number, blueprint, platform, etc.), generate a CSV report with the results, and save it locally. It processes command-line arguments, queries device inventory, extrac...
def main(): """Run main logic.""" # validate vars var_validation() # Return the arguments arguments = program_arguments() print(f"\nVersion: {__version__}") print(f"Base URL: {BASE_URL}\n") device_params = {} secrets = [] looking_for = [] report_name_items = [] if arg...
def var_validation(): """Validate variables.""" if SUBDOMAIN in ["", "accuhive"]: print( f'\nThe subdomain "{SUBDOMAIN}" in {BASE_URL} needs to be updated to ' "your Kandji tenant subdomain..." ) print("Please see the example in the README for this repo.\n") ...
The code generates a CSV report detailing the status of devices in Kandji's inventory that match a specified search term, derived from either a library item or parameter. It validates inputs, retrieves device data, filters results, and writes the report if matches are found, using date-stamped filenames for output.
def main(): # validate vars var_validation() # Return the arguments arguments = program_arguments() print(f"\nVersion: {__version__}") print(f"Base URL: {BASE_URL}\n") # dict placeholder for params passed to api requests params_dict = {} # Report name if arguments.library_ite...
def var_validation(): """Validate variables.""" if SUBDOMAIN in ["", "accuhive"]: print( "\nPlease update the SUBDOMAIN varialble with your Kandji tenant subdomain." ) print("Please see the example in the README for this repo.\n") sys.exit() if TOKEN in ["api_key...
The main task of the code is to update Kandji device records using a CSV input file. It validates arguments, loads and deduplicates serial numbers from the CSV, checks each device's enrollment status (enrolled or awaiting enrollment) via the Kandji API, and constructs payloads to update records. Errors like missing fil...
def main(): """Run main logic.""" var_validation() arguments = program_arguments() print(f"\nVersion: {__version__}") print(f"Base URL: {BASE_URL}\n") # Validate program arguments if arguments.template: # Try to load the contents of the csv file. # If unable to do so let th...
def update_scale(self, height, width): if self.window_height == height and self.window_width == width: return self.window_height = height self.window_width = width self.cell_size = round(self.get_cell_size()) self.scale_images() def get_margins(self): # returns (side...
This method repaints a game board and score on the screen by validating the board's dimensions, updating graphics scaling, clearing the display, drawing the background, rendering filled cells with adjusted positioning, and displaying the current score at the top margin.
def repaint(self, board, score): if board.shape != (self.rows, self.cols): raise ValueError("Board shape does not match graphics board shape") self.update_scale(self.screen.get_height(), self.screen.get_width()) self.screen.fill((250, 250, 250)) side_margin, top_margin = self...
def check_gameover(win, board, strikes): end_menu(win) if strikes == 3: print("Game over, too many errors") Tk().wm_withdraw() # to hide the main window messagebox.showinfo('Sorry!', 'You made too many mistakes, try again!') return True if board.is_finished(): print(...
The main task of the code is to implement a Sudoku game using Pygame. It initializes a game window, handles user input (number keys, delete, return), allows players to sketch and place numbers on a grid, tracks playtime and strikes for incorrect inputs, checks game completion, and redraws the board dynamically. The 's'...
def main(): win = pygame.display.set_mode((540,600)) pygame.display.set_caption("Sudoku") board = Grid(sudoku) key = None run = True start = time.time() strikes = 0 while run: play_time = round(time.time() - start) if check_gameover(win, board, strikes): run ...
def is_directory_or_file(self, path): if path is None: return None elif os.path.isdir(path): return "directory" elif os.path.isfile(path): return "file" def transcribe_file(self, source_dir, source_file, output_path, add_timestamps=False, translate=False): ...
This function transcribes audio from files, directories, or YouTube URLs, generating text transcripts with optional timestamps and translation. It aggregates results, saves them to specified output paths or Hugging Face datasets, and optionally cleans up temporary files.
def transcribe(self, source_path, output_path=None, hf_save_dataset_options=None, youtube_urls=[], add_timestamps=False, translate=False, cleanup=True): source_path_type = self.is_directory_or_file(source_path) transcriptions = [] # Structure: keys: audio_entry: str | dict, transcription: dict...
def median_cut(image, flat_im): red_average = np.mean(flat_im[:, 2]) green_average = np.mean(flat_im[:, 3]) blue_average = np.mean(flat_im[:, 4]) for pixel_point in flat_im: pixel_list[(pixel_point[0],pixel_point[1])]=(red_average,green_average,blue_average) def red_channel_range(image_array): ...
This function recursively splits an image into color boxes using a median cut algorithm. It identifies the color channel (red, green, or blue) with the largest range, sorts the image data by that channel, splits at the median, and recursively processes each half to generate `num_colors` distinct color boxes for quantiz...
def split_into_boxes(image_array, flat_image, num_colors): if len(flat_image) == 0: return if num_colors == 0: median_cut(image_array, flat_image) return red_range = red_channel_range(image_array) green_range = green_channel_range(image_array) blue_range = blue_channel_rang...
def median_cut_with_dithering(image, flat_im): red_average = np.mean(flat_im[:, 2]) green_average = np.mean(flat_im[:, 3]) blue_average = np.mean(flat_im[:, 4]) red_average = np.uint8(red_average) green_average = np.uint8(green_average) blue_average = np.uint8(blue_average) arr.append((red...
The function performs a recursive median cut algorithm to split an image's color space into boxes for color quantization. It sorts pixels by the channel (red, green, or blue) with the highest intensity range, finds the median, and recursively divides the image into two parts until the specified number of colors is achi...
def split_into_boxes(image_array, flat_image, num_colors): if len(flat_image) == 0: return if num_colors == 0: median_cut_with_dithering(image_array, flat_image) return red_range = red_channel_range(image_array) green_range = green_channel_range(image_array) blue_range = bl...
def pay_tf_data(self): self.payload_position =[] self.payload_status =[] self.temp =[] for i in range(len(payload_idx)-len(uris)): if sum(drone[i])==1: payload_ = [mission_position[i][0][0],mission_position[i][0][1],0.0] elif sum(drone[i])==2: ...
This code initializes a ROS node for a Crazyflie drone, setting up communication drivers, a cached factory for drone connections, and initializes publisher/subscriber nodes for data transmission and reception. It prepares the system to interact with the drone, handle transformations, and start operations.
def __init__(self): super().__init__('minimal_publisher') cflib.crtp.init_drivers() self.factory = CachedCfFactory(rw_cache='./cache') self.pay_tf_data() self.publishernode() self.SubcriberNode() self.start()
def __searchingForOptions(self, ui): if len(ui)>0: if ui[0] == self.optionSpecialChar: return True return False def __searchOptions(self, ui): opt = ui[1:].lower() optList = [] if len(opt) == 0: for o in self.options: optList.append(o) else: for o in self.options: if opt in o["name"].lo...
The code performs a search operation based on user input (ui), clears existing list boxes, determines search type (options or account), retrieves results, updates the display area size, and renders the search results on the canvas.
def __search(self, ui): self.canvas.delete(self.listBoxB) self.canvas.delete(self.listBox) if self.__searchingForOptions(ui): l = self.__searchOptions(ui) else: l = self.__searchingAccount(ui) self.__searchDisplayArea(len(l[:3])) self.__displayElements(l)
def infinite_system_dmrg(self, l, m): print("***** Infinite System DMRG *****") while 2 * self.sys_block.length < l: print(f"L = {2 * self.sys_block.length + 2}") new_block, energy = single_dmrg_step( self.sys_block, self.env_block, self.hamiltonianParameters, m ...
This code performs finite-system DMRG by iteratively applying DMRG steps with specified sweep parameters. It initializes with an infinite-system DMRG, then alternates system/environment blocks, computes energy, and stores results. The task is to return the final left/right blocks representing the ground state for a sys...
def finite_system_dmrg(self, l, m_warmup, m_sweep_list): # ***** Code below copied from `simple_dmrg_02_finite_system.py` ***** assert l % 2 == 0 self.infinite_system_dmrg(l, m_warmup) print("***** Finite System DMRG *****") for m in m_sweep_list: while Tru...
def pprint(*args): # print with UTC+8 time time = '['+str(datetime.datetime.utcnow()+ datetime.timedelta(hours=8))[:19]+'] -' print(time, *args, flush=True) if global_log_file is None: return with open(global_log_file, 'a') as f: print(time, *args, flush=True, fil...
The code trains and evaluates a forecasting model with a weight model using reinforcement learning, employing early stopping. It initializes models, sets up data loaders, trains over multiple epochs, validates, and tests the model. Metrics like MSE, IC, and ICIR are computed and saved. The best model parameters are sto...
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) suffix = "%s_dh%s_dn%s_drop%s_lr%s%s_bs%s_seed%s%s_%s_step%s"%( args.model_name, args.hidden_size, args.num_layers, args.dropout, args.fore_lr, args.weight_lr, args.batch_size, args.seed, args.annot, args.label_name, ar...
def pprint(*args): # print with UTC+8 time time = '['+str(datetime.datetime.utcnow()+ datetime.timedelta(hours=8))[:19]+'] -' print(time, *args, flush=True) if global_log_file is None: return with open(global_log_file, 'a') as f: print(time, *args, flush=True, fil...
The code trains a neural network model for time series prediction tasks, using cross-validation and early stopping. It initializes the model, loads data, trains over multiple epochs, evaluates performance on train/valid/test sets, saves the best model, and computes metrics (MSE, Rank IC, ICIR) for each dataset. Results...
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) suffix = "%s_dh%s_dn%s_drop%s_lr%s_bs%s_seed%s%s_%s%s"%( args.model_name, args.hidden_size, args.num_layers, args.dropout, args.lr, args.batch_size, args.seed, args.annot, args.label_name, args.label ) if args.l...
def get_xml_zipped(categories): """ Method to get the links from the sitemap for the given category Params - 1. categories - list of categories to get xml files for Returns - list with all xml links """ # ping request to sitemap.xml of APKPure xml_url = base_url + '/sitemap.xml' r = req...
The code scrapes app data from apkpure.com by sampling XML links for specified categories, unzipping them, and extracting a set number of apps per category to a given output directory. It iterates through categories, processes XML files, and stores sampled app data in the specified path.
def run_scraper(categories, num_apps,outpath): """ Run web scraper to get apps from apkpure.com Params - 1. categories - list of all categories 2. num_apps - number of apps per category 3. outpath - data directory file path """ #gets all xml links xml_links = get_xml_z...
def getItemID(tableName,itemID_parent,selectNum): idName_parent = getParentIDName(tableName) cursor.execute("SELECT * FROM {tableName} WHERE {idName_parent} = \"{itemID_parent}\"".format(tableName=tableName,idName_parent=idName_parent,itemID_parent=itemID_parent)) selectNum = int(selectNum) count = 0 ...
This function allows users to modify attributes of a subtask in a database table via a menu. It retrieves the subtask's details, presents options to rename, update duration, timestamp, status, or due date, and applies changes using corresponding database update functions. The loop exits when the user selects the exit o...
def modifySubtask(tableName,itemID_parent,itemNum): if itemNum == -1: return itemID = getItemID(tableName,itemID_parent,itemNum) idName = getIDName(tableName) itemName = getItemName(tableName,itemID) modifySubtask_menu_exit = False while not modifySubtask_menu_exit: modify_menu ...
def setup(): global pwm, mp_drawing, mp_face_detection, angle, max_angle, count, face_in_center_count GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) # values mp_face_detection = mp.solutions.face_detection mp_drawing = mp.solutions.drawing_utils # freq = 25 pwm = GPIO.PWM(17, 50) ...
The main task of the code is to execute a sequence of operations: initializing setup, performing face detection, and concluding with end-of-life procedures. The `main()` function orchestrates these steps in order, likely for a facial recognition or analysis system, ensuring proper resource allocation, detection process...
def main(): setup() faceDetect() end_of_life()
def __get_list_buff_data(self, hash_names: [str]) -> dict: """ Gradually requests buff for items by hash names in given dictionary. If request for item failed, data will be string of exception. :param hash_names: list of hash names to search for. :return: Dictionary[hash name] = ...
The main task of the code is to scan and parse items from Buff and the market using a saved list name. It retrieves item hashes, fetches data from both sources, handles errors during data retrieval and parsing, and compiles valid items with errors into a structured CsItemsList object for return.
def scan_list(self, list_name: str) -> CsItemsList: """ Scans buff and market for items by saved list name. ScanningException can be raised. :param list_name: Name of saved list. :return: Parsed CsItemsList. """ try: hash_names = ItemsScaner.__get_hashes_by_sc...
def make_arrows(config, entities) -> List[Arrow]: arrows = [] arrows.extend(make_guessed_arrows_from_attr_string_values(config, entities)) arrows.extend(make_arrows_from_python_refs(config, entities)) return arrows def combine_arrows(arrows_: List[Arrow]) -> List[DotArrow]: index = make_index(arrows...
The code generates a diagram in DOT format by creating nodes and arrows based on configuration and entity data, then combining and rendering them into a structured graph representation.
def diagram(config, entities): arrows = make_arrows(config, entities) dot_arrows = combine_arrows(arrows) nodes = make_nodes(config, entities) return render_to_dot(nodes, dot_arrows)
def get_passports(data): passport_str = [i.replace("\n", " ") for i in data.split("\n\n")] passport_dict = [dict(field.split(":") for field in passport.split(" ")) for passport in passport_str] return passport_dict def part1(data): passports = get_passports(data) counter = 0 for passport in pass...
The code processes passport data from a file, validates them using two criteria (part1 and part2), and prints the counts of valid passports. It reads input, splits into passports, checks validity, and outputs results.
def main(): with open("inputs/day4.txt", "r") as f: data = f.read().rstrip() get_passports(data) print(f"valid passports: {part1(data)}") print(f"valid passports: {part2(data)}")
def add_user(): print() l=[] ID = int(input("Enter User ID :: ")) with open("Employees.csv","r") as file: rows=list(csv.reader(file)) x=len(rows) for i in range(x): l=rows[i] if l[0]==str(ID): print(f"ID already exists") ret...
The code implements a menu-driven Leave Management System, allowing users to add users/admins, log in as user/admin, or exit. It continuously displays options, processes user input, and calls corresponding functions for registration/login, with a loop terminating upon selecting the exit option.
def main(): print("WELCOME TO LEAVE MANAGEMENT SYSTEM") ch = 0 while ch != -1: print("Press 1 to Add User") print("Press 2 to Login into User") print("Press 3 to Add Admin") print("Press 4 to Login into Admin") print("Press 5 to Exit") ch = int(input("Enter Yo...
def get_ldap_manager(self) -> LDAPManager: return get_ldap_manager(self.domain) def get_ldap_user(self, attributes: Optional[Iterable[str]] = None, refresh_cache: bool = False) -> Entry: """ Query LDAP for related user entry. LDAP User entry is saved as cache in process memory to avoid u...
This code synchronizes a Django User with an LDAP User by updating fields, flags, and group memberships based on domain-specific LDAP settings. It queries LDAP data, maps attributes to Django fields, checks user roles via group membership, adds/removes groups dynamically, and updates the Django user if changes are dete...
def sync(self) -> None: """ Synchronizes Django User against related LDAP User. Fields are synchronized using USER_FIELD_MAP from the domain's LDAP Settings. User flags are using SUPERUSER_GROUPS, STAFF_GROUPS and ACTIVE_GROUPS settings. Group membership is replicated using GROU...
def get_superuser_groups(self): return _get_group_list(self.SUPERUSER_GROUPS) def get_staff_groups(self): if self.PROPAGATE_GROUPS: return list({*_get_group_list(self.STAFF_GROUPS), *self.get_superuser_groups()}) else: return _get_group_list(self.STAFF_GROUPS) def get_act...
The code generates a dictionary mapping user flags (e.g., 'is_superuser', 'is_staff') to lists of associated groups. It combines direct method calls for core flags with processed entries from `self.FLAG_MAP`, applying `_get_group_list` to each value to standardize group representations. The result consolidates user per...
def get_flag_map(self): return { "is_superuser": self.get_superuser_groups(), "is_staff": self.get_staff_groups(), "is_active": self.get_active_groups(), **{ k: _get_group_list(v) for k, v in self.FLAG_MAP.items() } ...
def print_welcome(): print("\n ") print(r"_____/\\\\\\\\\\\___________________________________________________________________") print(r" ___/\\\/////////\\\_________________________________________________________________") print(r" __\//\\\______\///______/\\\_________________________________________...
The main task of the code is to execute a Python script ("SteamBlockButBetter.py") with elevated administrative privileges using PowerShell. It first prints a welcome message, ensures a text file exists, locates the script's directory, identifies the Python interpreter, constructs a PowerShell command to run the script...
def start_steamcuck(): print_welcome() check_create_txt_file() current_directory = os.path.dirname(os.path.realpath(__file__)) path = current_directory + r"\SteamBlockButBetter.py" pythonpath = search_for_python_exe() powershell_command = f'Start-Process -Verb RunAs {pythonpath} "{path}"' tr...
def browse_img (self, function): filename = filedialog.askopenfilename (filetypes = ( ('PNG', '*.png'), ('BMP', '*.bmp'), ('All files', '*.*'))) if filename == '': return else: ext_short = ('.bmp', '.png') ext = ('.bmp', '.png', '.jpg'...
The main task of the code is to reset GUI components and variables based on the 'function' parameter ('encode' or 'decode'), clearing text fields, hiding widgets, reconfiguring buttons, and rebinding events to prepare the interface for encoding or decoding operations.
def clear (self, function): if function == 'encode': self.img_file_to_en = '' self.secret_en = '' self.kind_en = '' self.output_path = '' self.l5e.config (text = '') self.l5e.place_forget () ...
def browse_img (self, function): filename = filedialog.askopenfilename (filetypes = ( ('PNG', '*.png'), ('BMP', '*.bmp'), ('All files', '*.*'))) if filename == '': return else: ext_short = ('.bmp', '.png') ext = ('.bmp', '.png', '.jpg'...
This code initializes a GUI application for encoding and decoding secret data into images. It creates a window with two tabs: one for encoding (selecting an image, entering a secret, and saving the encoded result) and another for decoding (selecting an encoded image and retrieving the hidden data). The interface includ...
def __init__ (self): self.img_file_to_en = '' self.img_file_to_de = '' self.secret_en = '' self.kind_en = '' self.output_path = '' self.gui_window = TkinterDnD.Tk () self.gui_window.focus_set () self.gui_window.resizable (F...
def train(self, act, index): self.model.train() self.optimizer.zero_grad() pred,loss0,feat_coars = self.model((act, index)) label = np.array([self.net_label[index]]) label = torch.LongTensor(label).to(self.device) loss=F.nll_loss(pred, label)#+loss0 loss.backward(...
The code performs a training step by updating the model with the given action and index, computes the next state via a transition function, evaluates validation accuracy, calculates a reward as the difference between current accuracy and a moving average benchmark, then returns the next state, reward, and accuracy for ...
def step(self, action, index): feat_coars = self.train(action, index) next_state = self.transition(feat_coars,index) val_acc = self.eval() benchmark = np.mean(np.array(self.past_performance[-self.benchmark_num:])) self.past_performance.append(val_acc) reward = val_acc - b...
def _init_hyperparameters(self): """ Initializes the hyperparameters from the config file. """ self.hparams["lr"] = self.hparams[ "learning_rate" ] = self.learning_rate = self.config["learning_rate"] self.data_path = self.config["data_config"]["data_path"] ...
This code initializes a training setup by configuring hyperparameters, models, datasets, and a trainer, while optionally enabling hyperparameter tuning with Optuna. It stores key parameters for later use in training or logging.
def __init__(self, config: NCPTrainingConfig, trial: optuna.trial.Trial = None): super().__init__() self.config = config self.tuning = config["tuning"] self.trial = trial self._init_hyperparameters() self._init_models() self._load_datasets() self._load...
def _sendLIST_REPLY(self, sock : Socket.socket, address: (str, int)): print("\nSending list "); files = ';'.join(self._getDir(os.path.abspath(self.input_DIR))).encode(encoding='utf-8') message = Message().fromKind(MessageType.LIST_REPLY, files) self._sendTo(sock, address, message.raw())...
The main task of the code is to process incoming messages of different types (LIST, LIST_REPLY, GET, PUT, ERROR, WRONG_FILE, OK) by performing corresponding actions such as sending replies, parsing payloads, handling file operations, or error recovery. It routes each message to specific internal methods for processing ...
def processMessage(self, mess : Message, sock : Socket.socket = None, address : (str, int) = None) : if mess.kind == MessageType.LIST: return self._sendLIST_REPLY(sock,address) if mess.kind == MessageType.LIST_REPLY: return print("\n".join(self._parseLIST_REPLY(mess.payload))) ...
def opp_in_check(): all_attacked = [] my_king_pos = 0 # to avoid error with if for x in range(8): for y in range(8): piece_reviewed = game.activeBoard[(x, y)] if piece_reviewed == -1 * game.current_turn: my_king_pos = (x, y) # find where my king is ...
This function determines if the current player has checkmated the opponent by verifying if all possible moves leave the opponent in check. It iterates through every piece on the board, simulates each valid move, and checks if the opponent remains in check. If any move allows the opponent to escape check, it returns Fal...
def checkmate(): if opp_in_check(): for x in range(8): for y in range(8): piece = game.activeBoard[(x, y)] if piece / game.current_turn < 0: alternatives = get_destination_squares( piece, (x, y), checkmate_test=True ...
def opp_in_check(): all_attacked = [] my_king_pos = 0 # to avoid error with if for x in range(8): for y in range(8): piece_reviewed = game.activeBoard[(x, y)] if piece_reviewed == -1 * game.current_turn: my_king_pos = (x, y) # find where my king is ...
The function checks if the current player is in stalemate by verifying if any legal move exists that doesn't leave the opponent in check. It iterates through all pieces, simulates moves, and checks for valid alternatives. If no such move exists, it returns True (stalemate); otherwise, False.
def stalemate(): if not opp_in_check(): for x in range(8): for y in range(8): piece = game.activeBoard[(x, y)] if piece / game.current_turn < 0: alternatives = get_destination_squares( piece, (x, y), checkmate_test=True ...
def checkmate(): if opp_in_check(): for x in range(8): for y in range(8): piece = game.activeBoard[(x, y)] if piece / game.current_turn < 0: alternatives = get_destination_squares( piece, (x, y), checkmate_test=True ...
The function checks for chess game end conditions like checkmate, stalemate, insufficient material, threefold repetition, and the 50-move rule. It updates the game's winner and move log accordingly, returning True if an end condition is met, otherwise False.
def end_conditions(): if checkmate(): print("checkmate!") game.winner = int(game.current_turn) game.move_log[-1][-1] = game.move_log[-1][-1].replace("!", "#") elif stalemate(): print("stalemate!") game.winner = 0 # draw elif insufficient_material(): game.winn...
def update_cell(r, c, value, cell, parent): now = find_parent(convertNum(r,c), parent) cell[now] = value def update_data(value1, value2, cell): for i in range(1, 2501): if cell[i] == value1: cell[i] = value2 def merge_data(r1, c1, r2, c2,cell, parent): parent2 = find_parent(convertNu...
The code processes spreadsheet commands (UPDATE, MERGE, UNMERGE) on a 50x50 grid, using union-find to manage merged cells. It tracks cell values and parent pointers, returning queried cell values after operations.
def solution(commands): answer = [] cell = ["EMPTY" for i in range(2501)] parent = [j for j in range(2501)] for cmd in commands: prom = cmd.split(' ') if prom[0] == "UPDATE": if len(prom) == 4: update_cell(int(prom[1]), int(prom[2]), prom[3], cell, parent...
def set_eval(self): """Convert all models to testing/evaluation mode """ for m in self.models.values(): m.eval() def process_batch(self, inputs): """Pass a minibatch through the network and generate images and losses """ for key, ipt in inputs.items(): ...
The code validates the model on a single minibatch by switching to evaluation mode, fetching input data, processing it to compute outputs and losses, handling depth loss calculations if applicable, logging validation metrics, and resetting the model to training mode afterward.
def val(self): """Validate the model on a single minibatch """ self.set_eval() try: inputs = self.val_iter.next() except StopIteration: self.val_iter = iter(self.val_loader) inputs = self.val_iter.next() with torch.no_grad(): ...
def set_eval(self): """Convert all models to testing/evaluation mode """ for m in self.models.values(): m.eval() def process_batch(self, inputs): """Pass a minibatch through the network and generate images and losses """ for key, ipt in inputs.items(): ...
The function validates the model on a single minibatch using the provided data loader. It disables gradient calculations, processes each batch to compute outputs and losses, conditionally computes depth losses if applicable, accumulates average loss across batches, and returns the average loss while switching back to t...
def val_only_encoder(self, val_loader): """Validate the model on a single minibatch """ self.set_eval() with torch.no_grad(): loss_avg = 0 batch = 0 for batch_idx, inputs in enumerate(val_loader): outputs, losses = self.process_batch(i...
def set_train(self): """Convert all models to training mode """ for m in self.models.values(): m.train() def process_batch(self, inputs): """Pass a minibatch through the network and generate images and losses """ for key, ipt in inputs.items(): inp...
The code runs a single training epoch, processing batches to compute model outputs and losses, performing backpropagation, and logging training metrics. It evaluates model performance on day/night datasets, computes depth-related errors, and saves results. If in depth-encoder-only mode, it validates on day/night data a...
def run_epoch(self): """Run a single epoch of training and validation """ self.model_lr_scheduler.step() print("Training") self.set_train() for batch_idx, inputs in enumerate(self.train_loader): before_op_time = time.time() outputs, outputs_nig...
def create_options_dict(options_list): options_dict = {} for count, text_angle in enumerate(range(23,383,45)): option_number = f'option_{count+1}' options_dict[option_number] = (options_list[count], text_angle) return options_dict def create_wheel(blank_wheel, length, height, options_dict): ...
The main task of the code is to generate rotated wheel images at every 1-degree angle (0-360°) and save them as PNG files. It creates a base wheel using given parameters, checks if current options differ from stored reference data, and regenerates all rotated versions if needed. The process ensures updated wheels are s...
def create_new_wheel_files(blank_wheel, options_list, length, height): options_dict = create_options_dict(options_list) original_wheel = create_wheel(blank_wheel, length, height, options_dict) reference = shelve.open('reference') try: if reference['options'] != options: for angle in ...
def get_files(path): files = [] try: files = os.listdir(path) except FileNotFoundError: logger.error(f"Path not found: {path}") return files def sort_files(files, path, dict, basename): for file in tqdm(files, desc=f'Sorting assets from \'{basename}\' directory', total=len(files), di...
The function collects and organizes media assets (series, movies, collections) from specified paths, prioritizing override paths. It sorts files, normalizes titles, merges override data into main assets, and returns structured asset information with file lists and normalized titles for processing.
def get_assets_files(assets_path, override_paths): asset_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']} override_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']} if assets_path: files = get_files(assets_path) basename = os.path.ba...
def get_assets_files(assets_path, override_paths): asset_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']} override_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']} if assets_path: files = get_files(assets_path) basename = os.path.ba...
The main task of the code is to log configuration settings, process media management instances (Plex/Radarr/Sonarr), and generate notifications. It checks dry-run status, collects asset files, validates instance configurations, processes media data, and sends results via Discord. The code handles conditional execution ...
def main(): data = [ ["Script Settings"], ] create_table(data, log_level="debug", logger=logger) logger.debug(f'*' * 40) logger.debug(f'{"Dry_run:":<20}{config.dry_run if config.dry_run else "False"}') logger.debug(f'{"Log level:":<20}{log_level if log_level else "INFO"}') logger.deb...
def iv(header, data): ''' Information Value based feature selection ''' neg,pos = 0,0 probs=np.zeros((9,5,2)) for datum in data: score_bin=get_bin_from_score(float(datum[9])) if(score_bin==0): neg+=1 else: pos+=1 for i in range(9): ...
The main task of the code is to read training data from 'data.csv', parse it into features (regressors) and target variables, and execute feature-selection methods (IV, ANOVA, or mutual information) based on a command-line argument. It processes numerical data, separates headers, and routes input to appropriate analysi...
def main(): ''' reads training data and calls appropriate method for feature-selection ''' data,regressors,target = [],[],[] with open('data.csv','r') as csv_file: csv_reader=csv.reader(csv_file,delimiter=',') for row in csv_reader: data.append(row) header=data[0...
def show_and_hide_cards(self, show=()): for i in range(len(self.player_frames)): self.clear_frame(self.player_frames[i]) if i not in self.ousted_players: if i not in show: self.display_back_cards(self.player_frames[i], len(self.player_map[i].get_cards(...
This code handles the "BS" game logic by validating a player's hand claim, determining if it's successful, updating game state, and displaying outcomes. It checks hand types (e.g., single, full house), sets validation parameters, evaluates the table's card state, identifies the losing player, increments strike counts, ...
def handle_bs(self): self.show_and_hide_cards(show=tuple(self.get_participating_players())) if self.current_claim in [0,1,3,7,8,9,12,13]: hand_type = "single" if self.current_claim == 0: count_bound = 1 elif self.current_claim == 1: count_bound = 2 elif se...
def turn_input_even_more(self,data,n): ''' turns the input n times clockwise. ''' for i in range(n): data=self.turn_input_data(data) return data def enemy_sensor(self,cell): ''' same as above. return list ordered s.t. cells close to the agent rather co...
The main task of the code is to aggregate sensor data from the environment (enemy, food, obstacles, energy, movement, collision) into a binary list for neural network input. The `direction` parameter influences processing via `turn_input_even_more`, which likely adjusts data formatting or prioritization based on moveme...
def get_data(self,direction = 0): ''' returns all relevant data for the nn as a binary list. ''' return self.turn_input_even_more(self.enemy_sensor(self.I)+self.food_sensor(self.I)+self.obstacle_sensor(self.I)+self.energy_sensor()+self.prev_move_sensor()+self.collision_sensor(),direction...
def log(message): line_number = sys._getframe(1).f_lineno.__str__() with open(os.path.join(SCRIPT_DIRECTORY, LOGS['folder_name'], LOGS['log_file_name']), "a") as log_file: log_file.write(time.strftime("%Y-%m-%d %H:%M:%S") + " -...
The main task of the code is to set up and launch a PHP server, handling automatic PHP installation (detecting system bitness), Laravel project creation or fallback setup, and launching a GUI application. It checks for PHP and Laravel project existence, prompts user input for installation or project creation, downloads...
def create_php_server(): try: global PHP_SERVER global PHP_SERVER_THREAD global PHP_SERVER_RUNNING start_time = time.time() try: if not os.path.exists(PHP_EXECUTABLE) or not os.listdir(PHP_BINARIES): log(LANG["PHP executable not found so it will ...
def cancel_modals(site_details: Dict): first_item = browser.find_elements(By.CLASS_NAME, site_details["job_list"])[0] browser.execute_script("arguments[0].click()", first_item) if "indeed" in site_details["url"]: cancel_single_modal( site_details["cancel_cookies"]["by"], sit...
The main task of the code is to scrape job listings from a paginated website by navigating through pages, extracting job details, handling pagination buttons, and closing modals. It uses a browser automation loop to repeatedly click "next" buttons, extract job data, and stop when no further pages exist, ultimately quit...
def scrape_pages(site_details): (url, job_list, prev_button_details, next_button_details,) = [ site_details[key] for key in ( "url", "job_list", "prev_button", "next_button", ) ] browser.get(url) browser.implicitly_wait(10) canc...
def ID3(self,x,y,row_index,depth): tree = dict() subset_x = x.iloc[row_index,:] subset_y = y.iloc[row_index] if(len(list(set(subset_y))) == 1): tree['terminal']=y[0] return(tree) if(depth == 0): nums = dict() for i in y: ...
This function trains a decision tree by selecting an appropriate algorithm based on the data types of input features (X) and target variable (Y). It constructs the tree using ID3 for categorical data, specialized methods for mixed data types, and real-real handling for continuous variables, assigning the resulting tree...
def fit(self, X, Y): if(str(X.dtype) == "category" and str(Y.dtype) == "category"): print(1) for crit in self.criterion: if(crit == "information_gain"): self.tree = self.ID3(X,Y,list(X.index),self.max_depth) elif(crit == "gini_index"):...
def Expand(peptides): newPeptides=[] for peptide in peptides: for a in get_amino_acid_mass().keys(): newPeptides.append(peptide+a) return newPeptides def Mass(peptide): aa_masses=get_amino_acid_mass() sumMass=0 for a in peptide: if a in aa_masses.keys(): s...
The code identifies all possible cyclic peptides whose cyclospectrum matches the given input spectrum. It iteratively expands peptide candidates, checks their mass against the spectrum's last value, and validates their full cyclospectrum against the input. Valid peptides are collected, duplicates removed, and results a...
def CyclopeptideSequencing(Spectrum): spectrum=Spectrum.split() for i in range (len(spectrum)): spectrum[i]=int(spectrum[i]) peptides=[''] output=[] while len(peptides)>0: removeList=[] peptides=Expand(peptides) for peptide in peptides: if Mass(peptide)==s...
def Expand(peptides,new_alphabet): newPeptides=[] for peptide in peptides: for a in new_alphabet: if len(peptide) > 0: newPeptides.append(peptide + '-' + a) else: newPeptides.append(peptide + a) return newPeptides def Mass(peptide): sumMa...
This code identifies the cyclopeptide with the highest score matching a given spectrum using a leaderboard approach. It iteratively expands peptide candidates, filters those exceeding the spectrum's mass, trims the leaderboard to top N candidates, and selects the peptide with the highest score matching the spectrum's t...
def LeaderboardCyclopeptideSequencing(Spectrum,N,new_alphabet): spectrum=Spectrum.split() for i in range (len(spectrum)): spectrum[i]=int(spectrum[i]) Leaderboard1=[] Leaderboard=[''] LeaderPeptide='' while len(Leaderboard)>0: removeList=[] Leaderboard=Expand(Leaderboard,...
def load_con(self, json_data): for con in json_data: if con: if con["name"] not in self.save_name: self.save_name[con["name"]] = f"CON{self.n_con}" self.n_con += 1 self.infor_con[con["name"]] = {"fun":[], "base_con":[]} ...
The main task of the code is to format source code by loading data, removing redundancies, replacing names, eliminating extra spaces and line breaks, and restructuring parentheses. It performs these steps sequentially in a try block, logging any exceptions for error handling.
def format_source_code(self): try: self.load_con(self.json_data) self.remove_remainder() self.replace_name() self.remove_redundant_line_breaks() self.format_within_parentheses() self.remove_multiple_spaces() except Exception as e: ...
def fetch_electricUsage(): cursor.execute("SELECT SUM(usage) FROM electric2") a = cursor.fetchall()[0][0] return a/2 def fetch_electricCost(): cursor.execute("SELECT SUM(cost) FROM electric2") a = cursor.fetchall()[0][0] return a/2 def fetch_waterCost(): cursor.execute("SELECT SUM(cost) FROM...
The main task of the code is to handle user interactions for toggling devices (doors, lights, windows) in a smart home system via HTTP POST requests, update the corresponding device states, and render the 'utility.html' template with real-time utility usage data (electricity, water, heater). It also supports GET reques...
def utility (): elecUsage = fetch_electricUsage() elecCost = fetch_electricCost() waterCost = fetch_waterCost() waterUsage = fetch_waterUsage() heaterUsage = fetch_heaterUsage() if request.method == 'POST': ## Kitchen if request.form.get('door2') == 'Back Door Toggle': ...
def get_internal_temp(): cursor.execute("SELECT temp_reading FROM Thermostat") return cursor.fetchone()[0] def get_currentWeather(): now = datetime.now() start = now.strftime("%Y-%m-%d") end = now.strftime("%Y-%m-%d" ) time = now.strftime("%H") timeInt = int(time) tz = "America/Chicago"...
The code handles POST and GET requests to control home devices (lights, temperature) via a web interface. It toggles electric devices in specific rooms (e.g., lights) based on form inputs, retrieves internal/exterior temperatures, and updates the 'home.html' template with device status and temperature data. Non-functio...
def home (): if request.method == 'POST': ## Kitchen if request.form.get('oh7') == 'Overhead Light': interTemp = get_internal_temp() extTemp = get_currentWeather() oh7 = toggle_electric("electric", "ison", "19") return render_template('home.html', oh7...
def to_indexed_contituents(parse, const_parse): if parse.count("(") != parse.count(")"): print(parse) parse = spaceify(parse) sp = parse.split() if len(sp) == 1: return set([(0, 1)]), 0, 1 backpointers = [] indexed_constituents = set() word_index = 0 first_op = -1 fo...
The code calculates and returns statistical metrics comparing two corpora, including F1 scores, first/last two-word phrase accuracy, negative pair ratios, and constituent parsing completeness. It prioritizes corpus_1 for evaluation, handling missing examples by requiring the shorter dataset as corpus_1. Results are for...
def corpus_stats(corpus_1, corpus_2, first_two=False, neg_pair=False, const_parse=False): """ Note: If a few examples in one dataset are missing from the other (i.e., some examples from the source corpus were not included in a model corpus), the shorter dataset must be supplied as corpus_1. corpus_1 ...
def to_indexed_contituents(parse, const_parse): if parse.count("(") != parse.count(")"): print(parse) parse = spaceify(parse) sp = parse.split() if len(sp) == 1: return set([(0, 1)]), 0, 1 backpointers = [] indexed_constituents = set() word_index = 0 first_op = -1 fo...
This function calculates the accuracy of labeled examples by comparing the unlabeled and labeled corpora. It iterates through each dataset, processes the constituents, and accumulates counts of correct and total examples using Counters. The result is a tuple of Counters representing correct and total labeled examples a...
def corpus_stats_labeled(corpus_unlabeled, corpus_labeled): """ Note: If a few examples in one dataset are missing from the other (i.e., some examples from the source corpus were not included in a model corpus), the shorter dataset must be supplied as corpus_1. """ correct = Counter() total =...
def __fit1(self, X, y): ''' Implementing Normal equation w = (X^T X)^-1 X^T y ''' x_mat = np.append(np.ones((X.shape[0], 1)), X, axis=1) y_mat = np.array(y).reshape((len(y),1)) if np.linalg.det(np.dot(x_mat.T, x_mat)) == 0: raise ValueError('Singular matrix, c...
This code fits a model by selecting different strategies based on input data dimensions and mode. It checks if the number of samples (m) exceeds, is less than, or equals the number of features plus one (n+1), then calls corresponding private methods (__fit1, __fit2, __fit3) to handle distinct problem types. The mode de...
def fit(self, X, y, iter_step=1, w_hist=False): m, n = X.shape if m > n + 1: if self.mode == 1: self.__fit1(X, y) else: self.mode = 2 self.__fit2(X, y, iter_step, w_hist) elif m < n + 1: self.mode = 3 ...
def makePlural(name): if name.lower() == 'cane corso': return name[:3] + 'i' + name[4:9] + 'i' if name[-1] == 'y': return name[:-1] + 'ies' elif (name[-1] != 's') and ((len(name) <= 2) or name[-3:] != 'ese'): return name + 's' else: return name def compareGroups(dog_name1...
The code compares two dog breeds based on a specified attribute (e.g., height, weight) and a comparison keyword ('taller', 'shorter', etc.), generating a natural language response. It handles special cases like 'group' comparisons via a helper function, checks for ambiguity, applies qualifiers for slight differences, a...
def compare(dog_name1, proper_name1, dog_name2, proper_name2, attribute, comparison_keyword): proper_name1, proper_name2 = makePlural(proper_name1), makePlural(proper_name2) if (type(attribute) == str) and (attribute == 'group') and (comparison_keyword in 'same', 'different'): # comparing groups require...
def checkForAmbiguity(keyword, attribute, subject_dog): response = '' reference = getDogInfo(subject_dog)[attribute] unspecified_both, unspecified_max, unspecified_min = False, False, False ambiguity_info = tuple() # the ambiguity depends on the desired dog's attribute if type(reference) == str...
The code retrieves and formats information about dog attributes (height, weight, lifespan, group) based on a comparison keyword ('higher', 'same', 'lower'). It checks for ambiguity in the subject attribute, generates a report if ambiguous, otherwise constructs a response using predefined sentence fragments and data fro...
def findDogs(subject, subject_dog, keyword): response = '' # checks if there is ambiguity in the desired attribute of the subject dog # if so, there will be an ambiguity report ambiguity_report = '' if subject != 'group': ambiguity_report = checkForAmbiguity(keyword, subject, subject_dog) ...
def correct(): index = 0 while index < len(words): # for every index (the length of the word list may change) # we check every possible multi-word phrase following that index starting at length 2 p_len = 2 while p_len <= (len(words) - index): checkPhrase(index, p_len) ...
The function `parse` processes a list of words using a dictionary and linguistic rules to generate valid sentence structures. It corrects the input word list, identifies known words, and constructs possible sentence components (including multi-word entries) based on the provided rules. The result is stored in a global ...
def parse(word_list, d, rules): global words, dictionary, trees # save the words, and dictionary as global variables words = word_list dictionary = d # reset the dictionary of trees trees = dict() try: correct() # corrects the given word list to include any multi-word dictionary ...
def parseQuestion(question): global parse_tree words = [word for word in question.split(' ') if (word != '')] if len(words) > 1: # updates the parse tree parse_tree = DogParse.parse(words, Grammar.dictionary, Grammar.syntax_rules) try: # finds the sentence tree if poss...
The code processes user input by splitting it into questions, parsing each question, selecting appropriate responses, and outputting them. It adds a disclaimer from the American Kennel Club on the first response and resets topics after each interaction.
def respond(user_input): global topics, response, first_question questions = [q for q in user_input.lower().replace('.', '?').split('?') if q] for question in questions: parsed = parseQuestion(question) if parsed: pickResponse() if response == '': print('S...
def readDirectory(volume_dir_list, volume_shape, norm_constant): #Check if a .i file was specified or if a full directory was specified if volume_dir_list[0][-1] == 'i': nb_dir = len(volume_dir_list) nb_volumes = 1 else: nb_dir = len(volume_dir_list) nb_volumes = len(glob.g...
This code initializes training data by loading and preprocessing noise and target volumes. It crops, pads, augments (rotates/shifts), and crops again to prepare 3D medical imaging data for training. The goal is to create aligned input-output pairs with spatial transformations for tasks like image registration or segmen...
def __init__(self, noise_dir_list, target_dir_list, volume_shape=(128,128,89), batch_size=8, slices=3, image_size=128, degrees_max=15, distance_max=4, nb_augmentations=1, crop_xy=128, crop_z=89, offset_z=0, padding='zero', noise_norm_constant=1, target_norm_constant=1, nb_to_re...
def readDirectory(volume_dir_list, volume_shape, norm_constant): #Check if a .i file was specified or if a full directory was specified if volume_dir_list[0][-1] == 'i': nb_dir = len(volume_dir_list) nb_volumes = 1 else: nb_dir = len(volume_dir_list) nb_volumes = len(glob.g...
The code initializes validation data by loading and preprocessing noise and target volumes through cropping, padding, augmentation, and random patch extraction. It processes input directories, applies spatial transformations, duplicates targets, augments data, crops to remove bleed-over, and saves 2.5D slices as valida...
def __init__(self, noise_dir_list, target_dir_list, volume_shape=(128,128,89), nb_val=8, slices=3, degrees_max=15, distance_max=4, nb_augmentations=1, crop_xy=128, crop_z=89, offset_z=0, padding='zero', noise_norm_constant=1, target_norm_constant=1, nb_to_remove=0): ...
def plot_dg_rates(self): params = self.parameters() g, b, m, h = self.simulate_DG(**params) fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5, 1, figsize=(4,5)) ax1.plot(params['range_t'], h, color='0.5', label='HIPP') ax1.set_ylabel("HIPP") ax2.plot(params['range_t'], b...
The code initializes a class with parameters for neural network simulations, storing input frequency, synaptic weights, and inhibition scales. It generates a unique identifier (flag) and triggers three plotting functions to visualize dendritic rates, cell firing properties, and granule cell activity rates.
def __init__(self, PP_freq, # frequency of PP inputs fbi, # scale feedback and feedforward inhibition synaptic weights (between GCs and BCs) PP_weight, # scale PP synaptic weight (onto GCs and BCs) ): self.pars = {} s...
def check_box_attached(self): dist_0 = np.sum(np.abs(self.agent_curr_positions[0] - self.box_curr_position)) if dist_0 == 1: self.box_attached = True def can_move_box(self, agent_forces): agent_0_force = agent_forces if all(self.agent_curr_positions[0] + agent_0_force == self...
The main task of the code is to process agent actions, update the environment state by moving agents/box, check boundaries, calculate rewards, and return results. It handles force application, position updates, box attachment checks, world state updates, and observation generation for reinforcement learning training.
def step(self, actions): """ Returns reward, terminated, info """ info = {} int_actions = [int(a) for a in actions] self.episode_actions.append(int_actions) self.check_box_attached() # Phase 1. Change the state # 1. is both the agent attached t...
def _setup(self) -> None: mp = self.mediapipe_results self.p_clock_abs = self._initialize_point(self.i_p_clock, mp) self.p_hand_abs = self._initialize_point(self.i_p_hand, mp) if self.scaling_mode in {1, 2}: n = 2 if self.scaling_mode == 1 else 4 for i in range(n...
This method updates the object's state using parsed Mediapipe results by setting internal data, triggering OSC handler updates, performing translation, calibration, and post-calibration processing (scaling/normalization), updating a tracker, and refreshing drawn gestures if calibrated.
def update(self, mediapipe_results_parsed: MediapipeParsed) -> None: self.mediapipe_results = mediapipe_results_parsed self.osc_handler.update(self) self._setup() self._translation() self._calibration() if self.is_calibrated: self._scaling() self...