dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def compute_test_score_per_user(data): """Calculate the ratio of the number of questions a student answered correctly to the number of questions they attempted """ M = len(set(data["user_id"])) user_num_questions_correct = np.zeros((M, 1)) user_num_questions_attempt = np.zeros((M, 1)) for ...
The code implements an Item Response Theory (IRT) model for educational data, tuning hyperparameters (learning rate, iterations), training the model on labeled data, and evaluating validation/test accuracy. It computes question discrimination indices, visualizes training dynamics (accuracy, log-likelihood), and plots s...
def main(): train_data = load_train_csv("../data") # You may optionally use the sparse matrix. train_sparse_matrix = load_train_sparse("../data") val_data = load_valid_csv("../data") test_data = load_public_test_csv("../data") ####################################################################...
def getTrajectoriesDistances(self, verbose = False): if (verbose): print("-- Distances between all trajectories --") distances = [] nb_trajectories = len(self.trajectories) for i in range(nb_trajectories - 1): i_distances = [] for j in range(i + 1, nb_...
The main task of the code is to visualize and analyze trajectory data by calculating pairwise distances, printing trajectory details, displaying combined trajectories, and separately visualizing clustered trajectories if provided. The function orchestrates data processing, output, and visualization steps for trajectory...
def completeDisplay(self, clusters = None): self.getTrajectoriesDistances(verbose = True) self.printTrajectories() self.showTrajectories() self.showTrajectoriesSeparately(clusters = clusters, verbose = True)
def get_time(parsing): time = parsing.split(' ')[0] try: secs = conv_time(time) return (secs, getnext(parsing, time + " ")) except Exception: return (None, None) def get_caller(parsing): caller = parsing.split(":")[0] return (caller, getnext(parsing, caller + ": ")) def get_l...
The code processes a line of input to extract structured data (time, caller, location, subjects) using helper functions, returning a dictionary if successful or None if time parsing fails.
def process_line(line): clip = {} clip['time'], next = get_time(line) if (clip['time']) is None: return None clip['caller'], next = get_caller(next) clip['location'], next = get_location(next) clip['subjects'] = get_subjects(next) return clip
def getEmailFromUser(): print(f"Chatbot: Fill in your email") email = input(f"You: ") return email def checkUserInDatabase(name, surname, email): mycursor.execute( "SELECT client_email FROM Clients WHERE client_email = %s", (email, ) ) if len(mycursor.fetchall()) == 0: if addUser...
The code's main task is to facilitate a tennis court reservation system via a chatbot. It collects user personal data, checks database existence, selects a date and time, handles OTP verification, assigns a court, and confirms the reservation via email if successful.
def startChat(): print(f"Chatbot: Welcome to the Tennis Court Reservation System") print(f"Chatbot: Please enter your personal data first") print(f"Chatbot: Fill in your name") name = input(f"You: ") print(f"Chatbot: Fill in your surname") surname = input(f"You: ") ...
def set_screenshot_dir(self,os_name,os_version,browser,browser_version): "Set the screenshot directory" try: self.screenshot_dir = self.get_screenshot_dir(os_name,os_version,browser,browser_version,overwrite_flag=True) if not os.path.exists(self.screenshot_dir): o...
This method registers a web driver with specified OS, browser, and remote settings. It creates screenshot directories, sets up logging, initializes the driver with implicit wait and maximized window, then triggers the start process for test execution.
def register_driver(self,remote_flag,os_name,os_version,browser,browser_version,remote_project_name,remote_build_name): "Register the driver with Page." self.set_screenshot_dir(os_name,os_version,browser,browser_version) # Create screenshot directory self.set_log_file() self.driver = sel...
def get_element(self, locator, verbose_flag=True): """Returns element by locator if exists, otherwise returns None""" dom_element = None try: locator = self.split_locator(locator) dom_element = self.driver.find_element(*locator) except Exception as e: ...
This function attempts to click a web element identified by a given locator. It retrieves the element, performs the click, waits for a specified time, and returns a success flag. If an exception occurs, it logs the error, records the failure in a list, and returns False. The method ensures robust interaction with UI el...
def click_element(self, locator, wait_time=3): """Click the button""" result_flag = False try: clickable_element = self.get_element(locator) if clickable_element is not None: clickable_element.click() result_flag = True self...
def load_existing_job_info(filepath=defval.default_job_csv_path, filename=defval.default_job_csv_name): # Construct the complete path complete_path = os.path.join(filepath, filename) # Check if the complete file path exists if not os.path.exists(complete_path): r...
The function `get_slurm_job_df_info` retrieves and processes SLURM job data, combining existing CSV records with newly fetched data if needed. It ensures the dataset spans the specified date range, deduplicates entries, sorts them by submission time, and saves the updated data back to a CSV for future use. The task inv...
def get_slurm_job_df_info(username:str=defval.username, end_date=None, start_date=None, verbose:bool = False): job_csv_info_path = os.path.join(defval.default_job_csv_path, defval.default_job_csv_name) if os.path.exists(job_csv_info_path): if verbose: pr...
def seed_all(seed = 42): """ Fix seed for reproducibility """ # python RNG import random random.seed(seed) # pytorch RNGs import torch torch.manual_seed(seed) torch.backends.cudnn.deterministic = True if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) import...
The function prepares data by splitting into training and validation sets (10% validation), trains a model using the training data, and evaluates it on the validation set through inference.
def run_model(df ): seed_all(config.SEED) df['mlabel'] = (df.ner_tags) val_size = int(df.shape[0]*.1) df_train = df df_val = df.iloc[:-val_size] print('Training examples ', len(df_train)) print('Validation examples ', len(df_val)) print("\ntraining started....") run(df_train,...
def gen_server_msg(msg:str): return { var.sender : var.server_name, var.group_name : var.server_name, var.data : msg } def send_to_group(group_name,msg): db.groups[group_name].add_msg(msg) for rid in db.groups[group_name].members_id: send(rid,msg) def resp...
This function handles a user joining a group by checking if the database operation succeeds. If successful, it broadcasts a join message to the group and sends a success response; otherwise, it sends an error response and a group name error message.
def join_group(sid, data): group_name = data[var.group_name] if db.join_group(sid, group_name): msg = gen_server_msg(f"{db.users[sid].name} joined chat {group_name}") msg[var.group_name] = group_name send_to_group(group_name, msg) response_msg = msg.copy() response_msg[va...
def gen_server_msg(msg:str): return { var.sender : var.server_name, var.group_name : var.server_name, var.data : msg } def send_to_group(group_name,msg): db.groups[group_name].add_msg(msg) for rid in db.groups[group_name].members_id: send(rid,msg) def resp...
This function handles a user leaving a chat group by updating the database, generating a server message to notify the group, and sending a response to the client indicating success or error based on the database operation result.
def leave_group(sid, data): group_name = data[var.group_name] if db.leave_group(sid, group_name): msg = gen_server_msg(f"{db.users[sid].name} leaved chat {group_name}") msg[var.group_name] = group_name send_to_group(group_name, msg) response_msg = msg.copy() response_msg[...
def gen_server_msg(msg:str): return { var.sender : var.server_name, var.group_name : var.server_name, var.data : msg } def send_to_all(msg): for user in db.users.values(): rid = user.id send(rid,msg) def send_group_name_error(sid): send_error(sid, ...
The main task of the code is to create a group using provided data, notify all users if successful with a message indicating the group was created by the user, or send an error message if group creation fails. It retrieves the group name from input data, checks database creation, fetches the creator's name, generates a...
def create_group(sid, data): group_name = data[var.group_name] if db.create_groups(group_name): u_name = db.users[sid].name msg = gen_server_msg(f'group {group_name} has been created by {u_name}') send_to_all(msg) else: send_group_name_error(sid)
def get_mask(img, mask_1, mask_2): lower_threshold = np.array([mask_1] * 3) upper_threshold = np.array([mask_2] * 3) mask = cv2.inRange(img, lower_threshold, upper_threshold) mask = cv2.bitwise_not(mask) contours, _ = cv2.findContours( mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) mi...
The main task of the code is to rotate an image by detecting its optimal rotation angle using edge detection, applying the rotation with a white border, converting color space, and cropping the result to remove excess borders.
def rotate_image(img, angle=None): mask = get_mask(img, CORNER_THRESHOLD, 255) if angle is None: angle = optimal_rotation(mask) M = cv2.getRotationMatrix2D( (img.shape[1] / 2, img.shape[0] / 2), angle, 1) img = cv2.warpAffine( img, M, (img.shape[1], img.shape[0]), borderValue=(25...
def import_data(arm=0): # Open the file. global filepath filepath = '../ActionNet_data/2022-06-14_16-38-43_streamLog_actionNet-wearables_S04.hdf5' h5_file = h5py.File(filepath, 'r') #################################################### # Example of reading sensor data: read Myo EMG data. ###...
The main task of the code is to preprocess EMG data by transforming it into stiffness features, create a labeled dataset, split it into training and testing sets, and prepare PyTorch DataLoader objects for model training and evaluation. The code handles data loading, transformation, dataset creation, and batch generati...
def main(): num_classes=20 #do not consider base class 0 device = torch.device("mps" if torch.has_mps else "cpu")#conv3D is still not working on mps, leave cpu batch_size=16 #learning_rate=0.001 #0.0001 #epochs=20 #momentum=0.9 #weight_decay=0.000001 #0.000001 emg_L, time_s_L,time_str_L=...
def import_data(arm=0): # Open the file. global filepath filepath = '../ActionNet_data/2022-06-14_16-38-43_streamLog_actionNet-wearables_S04.hdf5' h5_file = h5py.File(filepath, 'r') #################################################### # Example of reading sensor data: read Myo EMG data. ###...
The code trains an LSTM-based EMG signal classifier to recognize 20 classes from transformed stiffness data. It loads and preprocesses EMG data, splits into training/test sets, initializes a custom neural network, and trains it over 10 epochs with Adam optimizer. The model's state is saved post-training for future use.
def main(): sequence_len=26 #params for output images of spectrogram input_len=17 num_layers=2 num_classes=20 #do not consider base class 0 device = torch.device("mps" if torch.has_mps else "cpu")#conv3D is still not working on mps, leave cpu batch_size=1 learning_rate=0.001 epochs=10 ...
def new_contest(url, working_dir, dest_dir): # get contest id from url match = re.search(r"contest/(\d+)", url) contest_id = "" print(match) if match: contest_id = match.group(1) else: print("invalid url: cannot find contest ID in the link given") return # get contes...
This function determines whether a given URL points to a contest or problem and checks if the destination directory matches this type. If there's a mismatch, it warns the user and seeks confirmation before proceeding. Depending on the confirmed type, it calls either `new_contest` or `new_problem` to create the correspo...
def new(url, working_dir, dest_dir): # check if the url is a contest or problem url_is_contest = not re.search("problem", url) # check if directory is contest dir dest_dir_name = re.search(r'[^/]*$', dest_dir) dir_is_contest = bool(re.search("contest", dest_dir_name.group(0).lower())) # warn u...
def drawzsample(N=1000): # draw sample in the red-shift. The size of the sample is not exactly N, but some number close to it. X=np.logspace(-1,2,50) Y=[dVperdz(x) for x in X] # the un-normalized population upper=max(Y) # the peak value of the population distribution zwhole=np.random.uniform(0,zhigh,N) ...
The code generates samples in a multi-dimensional parameter space for gravitational wave events, including chirp mass, angles, and redshift. It returns these parameters or a subsample meeting a detection condition (flag≠0), filtering based on distance, mass, and orientation using a function `f`.
def drawsample(N=1000,flag=0): # draw sample in the multi-dimensional parameters space. #The size equals that of zsample, which is not exactly N, but someting close to this value. zsampled=drawzsample(N) Num=len(zsampled) Msampled=np.random.normal(loc=1.5,scale=0.3,size=Num) # Chirp mass before redshifted...
def drawzsample(N=1000): # draw sample in the red-shift. The size of the sample is not exactly N, but some number close to it. X=np.logspace(-1,2,50) Y=[dVperdz(x) for x in X] # the un-normalized population upper=max(Y) # the peak value of the population distribution zwhole=np.random.uniform(0,zhigh,N) ...
The code generates samples in a multi-dimensional parameter space, including redshift, chirp mass, and celestial angles, with optional subsampling based on a detection criterion. It returns either the full sample or a filtered subsample meeting specific conditions, likely for astrophysical simulations or gravitational ...
def drawsample(N=1000,flag=0): # draw sample in the multi-dimensional parameters space. The size equals that of zsample, which is not exactly N, but someting close to this value. zsampled=drawzsample(N) Num=len(zsampled) Msampled=np.random.normal(loc=1.5,scale=0.3,size=Num) # Chirp mass before redshifted!! ...
def drawsample(N=1000,flag=0): # draw sample in the multi-dimensional parameters space. #The size equals that of zsample, which is not exactly N, but someting close to this value. zsampled=drawzsample(N) Num=len(zsampled) Msampled=np.random.normal(loc=1.5,scale=0.3,size=Num) # Chirp mass before redshifted...
The code computes the average value of a function `f(rho)` and its uncertainty by performing 10 Monte Carlo simulations, each generating `N` samples. It calculates the mean of the results and the standard deviation of the distribution, returning both as the final output.
def Percent(cri,N=1000): # return the value of <f(rho)>, together with its uncertainty. fraction=[] for i in range(0,10): Msampled,cthsampled,phisampled,cosisampled,psisampled,zsampled=drawsample(N) NM=len(Msampled) summ=0. for j in range(0,NM): D=Dl(zsampled[j]) ...
def drawsample(N=1000,flag=0): # draw sample in the multi-dimensional parameters space. The size equals that of zsample, which is not exactly N, but someting close to this value. zsampled=drawzsample(N) Num=len(zsampled) Msampled=np.random.normal(loc=1.5,scale=0.3,size=Num) # Chirp mass before redshifted!! ...
The code computes the average value of a function `f(rho)` and its uncertainty using Monte Carlo sampling. It draws 10 samples of size N=1000, calculates `f(rho)` for each, averages them, and returns the mean and standard deviation of these averages. The function incorporates redshift effects via the chirp mass term.
def Percent(cri,N=1000): # return the value of <f(rho)>, together with its uncertainty. fraction=[] for i in range(0,10): Msampled,cthsampled,phisampled,cosisampled,psisampled,zsampled=drawsample(N) NM=len(Msampled) summ=0. for j in range(0,NM): D=Dl(zsampled[j]) ...
def graph1(df,lookup): col1_name="junction_detail" col2_name="number_of_vehicles" df=replace_dataframe_from_lookup(df,lookup,col1_name) df=replace_dataframe_from_lookup(df,lookup,col2_name) return ScatterAverage(df,col1_name, col2_name) def graph2(df,lookup): col1_name="road_type" col2_name=...
The code creates a Dash web application displaying a dashboard with multiple graphs visualizing the UK Accidents 2016 dataset. It initializes the app layout with headings, spacing, and five graphs generated by graph1–graph5 functions using the input DataFrame and lookup dictionary. The app runs on a server to render th...
def create_dash(df,lookup): app = dash.Dash() app.layout = html.Div([ html.H1("Web Application Dashboards with Dash", style={'text-align': 'center'}), html.Br(), html.H1("UK Accidents 2016 dataset", style={'text-align': 'center'}), html.Br(), html.Div(), dcc.Grap...
def randapplegen(): randAppleX = round(random.randrange(0, display_w - applesize) / 10.0) * 10.0 randAppleY = round(random.randrange(0, display_h - applesize) / 10.0) * 10.0 return randAppleX,randAppleY def pause(): paused = True screenmessage("PAUSED!!!", orange, y_displace=-150, szfont='big') ...
The code implements a snake game loop where the player controls a snake to eat apples, increasing its length and score. It handles keyboard input for movement, checks collisions with walls and self, generates new apples upon consumption, and displays a game-over screen with restart options.
def gameloop(): # coordinates lead_x = display_w / 2 lead_y = display_h / 2 lead_x_change = 10 lead_y_change = 0 randAppleX, randAppleY = randapplegen() #variables declaration global headdirect headdirect = 'right' gameExit = False gameOver = False snakelist = [] sn...
def _check_task_paused(self): while self.paused: print('Sleeping') self.sleep(1) def destinction(ownerName, original_Name): print("OwnerName-----------> : ", ownerName) print("Original_Name-------> : ", original_Name) owner_array = ownerName.split(" ") or...
The main task of the code is to scrape data from a website by navigating through pages, handling reCAPTCHA verification using a solver, and parsing owner information. It uses multiple drivers to process different URLs based on detected conditions, extracting details and breaking tasks when specific criteria are met.
def turepeopleSearch(self, driver1, driver2, driver3, data): url = self.default_url.format(data["name"], data["address"]) driver1.get(url) self._check_task_paused() try: self.logcallback.emit("### Recaptcha Detecting >>>................", 24) recaptcha = driver1....
def _intialize(self): self.logcallback.emit("### Now making csv file...........................", 2) open(self.dirName + "/" + "{}.csv".format(self.searchName), "wb").close() header = ["Name", "Address", "Phone1", "phone2", "phone3", "phone4", "phone5", "phone6", "phone7", "phone8", ...
This code scrapes data from a website by navigating through pages, solving reCAPTCHA challenges, and using multiple browsers to extract owner information. It checks for task pauses, processes paginated results, and directs different drivers to parse specific details based on owner name matches. The primary goal is to c...
def parse_page(self): self._intialize() # Checking task is paused or not self._check_task_paused() time.sleep(5) self.logcallback.emit("### First Page Scraping Start.................", 10) driver = self.driver driver1 = self.driver1 driver2 = self.driver...
def _intialize(self): self.logcallback.emit("#Now making csv file...........................", 2) # Qtcore open(self.dirName + "/" + "{}.csv".format(self.keyword), "wb").close() header = ["Company Name", "Name", "Role", "Address", "Age", "Filling Type", "Status", "State", "Foreign State...
The main task of the code is to scrape company data from a website by searching for a keyword, extracting company names and URLs from search results, then navigating to each company's page to collect detailed information such as name, role, address, filing type, status, and other attributes. The data is stored in a dic...
def parse_page(self): item_urls = [] companyNames = [] self._intialize() self._check_task_paused() time.sleep(5) self.logcallback.emit("### First Page Scraping Start.................", 10) driver = self.driver driver1 = self.driver1 driver2 = se...
def print_selected_hyperparams(param_values): search_space = get_search_space() search_space_keys, search_space_vals = zip(*search_space.items()) search_space_keys = {param_name: idx for idx, param_name in enumerate(search_space_keys)} for param_name in search_space_keys: ...
The code defines an `objective_function` to train and evaluate a neural network model for a classification task. It processes input data by encoding categorical features (one-hot/embedding) and numeric features, constructs a Keras model with embedded layers, dense layers, and dropout, trains it on a dataset, evaluates ...
def objective_function(params): print_selected_hyperparams(params) test_size = hyperparam_value("test_size", params) batch_size = hyperparam_value("batch_size", params) epochs = hyperparam_value("epochs", params) learning_rate = hyperparam_value("learning_rate", params) hidden_layer_1 = hyperpa...
def card_list_to_dict(card_list): """ Convert a list of Card objects to a list of dictionaries. Args: card_list (list): A list of Card objects. Returns: list: A list of dictionaries representing each Card object. """ card_dicts = [] for card in card_list: card_dict ...
The function identifies the best cards for a user based on their location by evaluating card specials, categories, and base rates. It returns a list of tuples containing the location name, card ID, and image URL for the top card at each of the six nearest locations.
def get_best_cards(user_id, latitude, longitude): try: latitude = float(latitude) longitude = float(longitude) except ValueError: return None user_cards = card_list_to_dict(get_user_cards(user_id)) # invalid user_id if (user_cards is None): return None # get neare...
def add_business(self): print('Welcome to Quantify...') while True: try: name = input('Business name: ') num_of_months = int(input('Number of months to evaluate: ')) total_revenue = float(input('Total revenue: $')) cogs = float(...
The function adds a new decimal column to an SQLite financials table, populates it with specific financial data values from self.b_data for categories like gross profit and net profit, increments a counter, and handles exceptions by updating the database again if errors occur.
def add_new_data_db(self): self.add_business() self._health_compilation() try: con = sqlite3.connect(self.b_data[0][1] + '.db') cur = con.cursor() cur.execute('ALTER TABLE ' + self.b_data[0][1] + '_financials\n' + 'ADD col' + str(self....
def load_dataset(db_conn): """ Loads the dataset """ #load each crop return [load_crop(db_conn, c) for c in CROPS] def prune_data(data, n): """ Prune off the last n years of training """ return [(f[:-n], p[:-n]) for f, p in data] def select_model(hidden, **kwargs): """ Returns a model based on the given args...
The main task of the code is to train a character-level auto-encoder using data from a database. It loads and prunes datasets, initializes a model and optimizer, trains the model with mean squared error loss, and evaluates performance on training, validation, and test sets by printing MSE and MAE loss metrics.
def main(args): """ Trains a character level auto-encoder """ seed(args.s) t.manual_seed(args.s) arg_dict = vars(args) #connect to the database db_conn = sql3.connect(args.db) #load the data print("Loading Data") data = load_dataset(db_conn) training_data = prune_data(data, args.dev + args.test) dev_d...
def __is_open_brace(self, char): return self.__BRACES.get(char, False) def __append_close_brace_to_stack(self, char): self.__stack.append(self.__BRACES[char]) def __is_unbalanced(self, char): return self.__is_closed_brace(char) and (self.__is_stack_empty() or not char == self.__pop_from_stack())...
This code checks if a string of braces is balanced by iterating through each character, using a stack to track open braces, and raising an error if unbalanced characters are found. It returns a confirmation message if the stack is empty, indicating balanced braces.
def check_if_balanced(self): for i, char in enumerate(self.__text): if self.__is_open_brace(char): self.__append_close_brace_to_stack(char) elif self.__is_unbalanced(char): raise _UnbalancedBracesError(self.__unbalanced_text_till_index(i, char)) r...
def __validate(self, first_names, last_names): self.__validate_names(first_names) self.__validate_names(last_names) def __insert_first_names_into_full_names(self, first_names): self.__insert_names_into_full_names(first_names, 1) def __update_full_names_with_last_names(self, last_names): ...
The code joins first and last names into full names by validating inputs, then inserts the longer list (either first or last names) into full names first, followed by updating with the shorter list to combine them properly.
def __join_names(self, first_names, last_names): self.__validate(first_names, last_names) if len(first_names) >= len(last_names): self.__insert_first_names_into_full_names(first_names) self.__update_full_names_with_last_names(last_names) else: self.__insert_la...
def get_feed_df(rss_feed_urls): with st.spinner('Retrieving articles from feeds...'): return rss_feeds.get_feed_df(rss_feed_urls) def setup_searcher(feed_df, use_gpu, model_name="deepset/sentence_bert"): with st.spinner('No precomputed topics found, running zero-shot learning...'): searcher = ha...
This code creates a Streamlit app for interactive news article retrieval using NewsBERT. It loads topics/RSS feeds, allows user selection of topics/search terms, filters articles by confidence threshold, and displays results in wall/dataframe formats with GPU acceleration options.
def main(): st.title('NewsBERT') # setting up data file_url_template = "https://raw.githubusercontent.com/lambdaofgod/pytorch_hackathon/master/data/{}.txt" topic_strings_file_url = file_url_template.format('topics') rss_feeds_file_url = file_url_template.format('topics') topic_strings = list(pd...
def init_data_tab(self): """ Method that initialize the tab :return: """ self.clear() self.tab_info = QWidget() self.tab_exif = QWidget() self.addTab(self.tab_info, "Info") self.addTab(self.tab_exif, "EXIF") def __update_info(self, info): ...
The main task of the code is to update the data tab with the currently selected image's information and EXIF data. It initializes the data tab, retrieves the image data and EXIF metadata from the controller, then updates the UI components displaying these details using private methods.
def update_tab_value(self): """ Method that update the data tab with the selected image data :return: """ self.init_data_tab() info, exif = self.controller.get_current_data() self.__update_info(info) self.__update_exif(exif)
def extract_items(target_files, target_files_temp_dir, extract_item_list): """Extracts items from target files to temporary directory. This function extracts from the specified target files zip archive into the specified temporary directory, the items specified in the extract item list. Args: target_files...
The function `create_merged_package` merges two partial target files packages (framework and vendor) into a unified target files structure. It extracts specified items directly from both input packages into a temporary directory, then processes `META/*` files separately. Special handling merges metadata, partitions, an...
def create_merged_package(temp_dir, framework_target_files, framework_item_list, vendor_target_files, vendor_item_list, framework_misc_info_keys, rebuild_recovery, framework_dexpreopt_tools, framework_dexpreopt_config, ...
def create_merged_package(temp_dir, framework_target_files, framework_item_list, vendor_target_files, vendor_item_list, framework_misc_info_keys, rebuild_recovery, framework_dexpreopt_tools, framework_dexpreopt_config, ...
The function merges framework and vendor target files into a unified output package by extracting and processing files, validating compatibility (e.g., VINTF, sharedUserId), compiling policies, and generating merged zip, OTA, and IMG files while handling dexpreopt configurations and partition-specific checks.
def merge_target_files(temp_dir, framework_target_files, framework_item_list, framework_misc_info_keys, vendor_target_files, vendor_item_list, output_target_files, output_dir, output_item_list, output_ota, output_img, output_sup...
def produce_sequence(keyNum, X_dict, n_return = 1, printout = False): ''' Input: - keyNum: the ID number of the problem - X_dict: the dictionary that contains the problem - n_return: number of best sequences to return Output: - a dictionary with key = the ranking of the output. Specific inf...
The function `moveGeneratorForAllProblem` processes climbing problem data from MoonBoard, converting each problem's move sequence into a 22-dimensional vector format suitable for RNN input. It iterates through processed data, generates move features (e.g., hold positions, scores, movement metrics), and compiles them in...
def moveGeneratorForAllProblem(processed_data, save_path, print_result = False): """ Apply moveGenerator on all problems, and transform the output into X vector move sequence for RNN Input: - processed_data: the processed data that is scraped from MoonBoard - i.e. '/preprocessing/processed_data_xy_m...
def produce_sequence(keyNum, X_dict, n_return = 1, printout = False): ''' Input: - keyNum: the ID number of the problem - X_dict: the dictionary that contains the problem - n_return: number of best sequences to return Output: - a dictionary with key = the ranking of the output. Specific inf...
This function generates hand move sequences from processed climbing problem data for RNN training. It processes each problem's coordinates and operators into string formats, saves valid sequences in a dictionary, and handles errors. Output: dictionary mapping problem keys to hand move lists, e.g., ["J5-LH", "G6-RH"], f...
def handStringSeqGeneratorForAllProblem(processed_data, save_path, print_result = False): """ Apply moveGenerator on all problems, and transform the output into X vector move sequence for RNN Input: - processed_data: the processed data that is scraped from MoonBoard - i.e. '/preprocessing/processed_...
def orderToSeqOrder(self, order): """ Transform from order (in the all avalible holds sequence) to hand order (in the hand sequence)""" return self.handSequence.index(order) def getleftHandOrder(self): """ Return a num of the last left hand hold's oreder (in processed data from bottom to top)"""...
The function calculates the combined success rate of the last move by multiplying the success rates of the left and right hands, each determined by their respective holds and operators. It retrieves the appropriate operators using order-to-sequence mappings, then computes individual success rates and combines them mult...
def lastMoveSuccessRateByHold(self): operatorLeft = self.handOperator[self.orderToSeqOrder(self.getleftHandOrder())] operatorRight = self.handOperator[self.orderToSeqOrder(self.getrightHandOrder())] return self.successRateByHold(self.getleftHandHold(), operatorLeft) * self.successRateByHold(self...
def click_login_area(browser): """ Clicks on login area to pull up username and password field """ login_elem = None a_elems = browser.find_elements('tag name', 'a') for a in a_elems: if a.text == 'LOGIN/REGISTER': login_elem = a break if login_elem is None: ...
The main task of the code is to automate logging into the MoonBoard website by navigating to the specified URL, locating the login area, inputting provided credentials, and clicking the login button. It returns the login button element if successful or None if any critical element is missing during the process.
def loginMoonBoard(browser, url='', username='', password=''): """ Logs in to MoonBoard site """ browser.get(url) # Get login element login_elem = click_login_area(browser) if login_elem is None: return None # Fill in credentials and login username_elem, password_elem = inp...
def load_pickle(file_name): """ Loads data from pickle format """ with open(file_name, 'rb') as f: return pickle.load(f) def get_current_page(browser): """ Gets the index of the current page of routes (bottom bar) """ pager_elem = None page_elem = None # Pull elements wi...
The function processes all pages by repeatedly extracting problems from a browser session, handling errors with retries, and saving results to a dictionary. It navigates through pages, persists intermediate data if a save path is provided, and stops when all pages are processed or a specified limit is reached.
def process_all_pages(browser, save_path='', num_tries=20, sleep_val=1, num_pages=-1): """ Processes all pages and saves results into a dictionary """ # Load problems dict, if it exists problems_dict = {} if os.path.exists(save_path): problems_dict = load_pickle(save_path) page_cnt ...
def getEndHoldOrder(self): """return endHold list with 2 element of np array""" endHoldOrderList = [] for i in range(self.totalNumOfHold): if self.allHolds[i][9] == 1: endHoldOrderList.append(i) if len(endHoldOrderList) == 1: endHoldOrderList.appen...
The main task of the code is to update the hand sequence and operator when adding a new hold (nextHold) with a specified hand (op). It appends the hold to the sequence, updates the operator list, adjusts end hold tracking, and calculates the distance between the original and new hand positions. Conditional logic manage...
def addNextHand(self, nextHold, op): """ Operation to make add the next hold. Append handsequence and hand operation. nextHold is a hold. op is "LH" or "RH" """ if self.touchEndHold == 3: self.handSequence.append(self.totalNumOfHold - 1) if self.handSequence[-1] == "LH": ...
def getXYFromOrder(self, holdOrder): """return a coordinate tuple giving holdOrder (a num in processed data)""" return ((self.allHolds[holdOrder][6]), (self.allHolds[holdOrder][7])) def getrightHandOrder(self): """ Return a num of the last right hand hold's oreder (in processed data from bottom ...
The function calculates the success rate of moving a hold (tryOrder) using either the left or right hand (op), considering the other hand's current position and distance. It adjusts the success rate by penalizing large crosses between hands, multiplying individual hand success rates, and normalizing by the distance bet...
def tryMove(self, tryOrder, op): """Try how addition hold. Return successRate, tryOrder is a number in holdsNotUsed list. op is either "LH" or "RH" """ tryHold = self.allHolds[tryOrder] finalXY = self.getXYFromOrder(tryOrder) if op == "LH": originalXY = self.g...
def list_json(directory): '''list files with json extension''' filePaths = [] for root, directories, files in os.walk(directory): for filename in files: if filename.endswith(".json"): filepath = os.path.join(root, filename) filePaths.append(filepath) r...
(The main task of the code is to deploy applications to Marathon using configurations from JSON files. It sends HTTP PUT requests to Marathon's API to create/update apps, handles 'macvlan' network settings, and supports both synchronous (with instance tracking) and asynchronous deployment modes. The function processes ...
def deploy_apps(env, sync=False): '''Deploy to Marathon''' deployFiles = sorted(list_json('./_json/{}'.format(env))) deployConfig = load_json(deployFiles) for config in deployConfig: finalJson = json.dumps(config) r = marathon_request(env, 'put', '/v2/apps{}?force=true'.format(config['id...
def marathon_request(env, method, uri, data=None): '''Build request to Marathon''' config = load_json(['./_env/{}/marathon.conf'.format(env)]) password = base64.b64decode(json.dumps(config[0].get('password'))).decode().rstrip('\n') auth = ('admin', password) headers = {'Content-type': 'application/j...
This function scales multiple Marathon applications by sending PUT requests to update their instance count in a specified environment. It iterates over provided app IDs, adjusts instances via Marathon's API, and prints status updates. If 'sync' is True, it retrieves deployment IDs and synchronizes deployment progress.
def scale_apps(env, appIds, instances, sync=False): for app in appIds: r = marathon_request(env, 'put', '/v2/apps/{}?force=true'.format(app), '{"instances":%s}' % ''.join(instances)) print('Scaling {} in {} to {}'.format(app, env, ''.join(instances))) if sync: deployId = get_depl...
def transform_parameters(apikey, parameters): for k in ['fly_from', 'fly_to']: if k in parameters: parameters[k] = to_iata_code(apikey, parameters[k]) for k in ['date_from', 'date_to', 'return_from', 'return_to']: if k in parameters: if isinstance(parameters[k], dt.datet...
The code's main task is to search for flight options using an API, transform input parameters, fetch data from "kiwicom-prod.apigee.net", process the JSON response to extract flight options, and return the top 'n' options based on the specified flight type. If no data is retrieved, it returns None after printing an err...
def search(flight_type, apikey, parameters, n): parameters = transform_parameters(apikey, parameters) # print(parameters) response_json = download_data(apikey, api="https://kiwicom-prod.apigee.net/v2/search?", parameters=parameters, cache_expire_after=3600) if response_...
def drawText(frame, text, x, y=None, line=None, fontScale=0.4, thickness=0, lineType=cv.LINE_AA, color=white, colorbg=black): font = cv.FONT_HERSHEY_SIMPLEX bottomLeftCornerOfText = (x, y if y else getLineY(line)) if colorbg is not None: cv.putText(frame, text, bottomLeftCornerOfText, font, fontScale, colorbg...
This function generates and visualizes latency statistics on a frame. It calculates min, avg, and max latency values from a list, displays them as text, and overlays horizontal bars representing these metrics. It also creates a histogram by counting occurrences of each latency value, drawing vertical bars to visualize ...
def drawSummaryText(frame, latencies, line): secs = [i.secs() for i in latencies] secsLen = len(secs) if secsLen: secsMin = min(secs) secsMax = max(secs) secsAvg = sum(secs) / secsLen h = 16 x = 5 drawText(frame, "min:{}ms, avg:{}ms, max:{}ms".format(int(secsMin*1000), int(secsAvg*1000), i...
def permissionInPermissionDic(dic: dict, permission: str) -> bool: gotPermission = False permissionList = permission.split(".") currentPermissionPosition = dic for v in permissionList: if v in currentPermissionPosition: if type(currentPermissionPosition[v]).__name__ == "dict": ...
This function removes a specified permission from a member's permissions. If the permission exists in the default permissions for the member's guild, it marks the permission as removed from defaults; otherwise, it directly removes the permission from the member's existing permissions.
def removePermissionFromMember(member, permission): permissions = dataStorage.getPlayerData(member, "permissions", default={}) splitPermission = permission.split(".") if permissionInPermissionDic(getDefaultPermissions(guild=member.guild), permission): dataStorage.setPlayerData(member, "permissions"...
def permissionInPermissionDic(dic: dict, permission: str) -> bool: gotPermission = False permissionList = permission.split(".") currentPermissionPosition = dic for v in permissionList: if v in currentPermissionPosition: if type(currentPermissionPosition[v]).__name__ == "dict": ...
This function removes a specified permission from a role's permissions. It checks if the permission is a default guild permission; if so, it adds it to the role's "removedFromDefaultPermissions" list. Otherwise, it directly removes the permission from the role's "permissions" dictionary. The updated role data is then s...
def removePermissionFromRole(role, permission): roles = dataStorage.getGuildData(role.guild, "roles", default={}) splitPermission = permission.split(".") if f"{role.id}" not in roles: roles[f"{role.id}"] = {} if "permissions" not in roles[f"{role.id}"]: roles[f"{role.id}"]["permissions"]...
def getAllPermissionsInPermissionDic(dic: dict, **kwargs) -> list: if "currentlyAt" not in kwargs: currentlyAt = "" else: currentlyAt = kwargs["currentlyAt"] l = [] for k in dic: if isinstance(dic[k], dict): currentlyAt = f"{k}." l.extend(getAllPermissions...
The function `getMemberPermissions` compiles a member's effective permissions by first retrieving their stored permissions, then adding all default guild permissions, and finally removing any permissions marked as removed. It uses helper functions to add or remove permissions from the dictionary, ensuring the final res...
def getMemberPermissions(member) -> dict: d = dataStorage.getPlayerData(member, "permissions", default={}) for v in getAllPermissionsInPermissionDic(getDefaultPermissions(guild=member.guild)): d = addPermissionToDic(d, v.split(".")) for v in getAllPermissionsInPermissionDic( dataStorage....
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The code defines a function `north_button_click` that handles the action when a "North" button is clicked. It prints the direction "N" to a description, executes a command associated with "N", and updates the current state. The main task is to process user input for navigating north in a game or application, updating r...
def north_button_click(): print_to_description("N", True) perform_command("N", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The code defines a function `south_button_click` that handles a button press event. It updates a description with "S", executes a command associated with "S", and updates the current state of the application, likely for navigation or interaction in a system like a game or interface.
def south_button_click(): print_to_description("S", True) perform_command("S", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The code defines a function `east_button_click` that handles a button action by printing the letter "E" to a description, executing a command associated with "E", and updating the current state. Its main task is to process an east-direction interaction in a system, likely a game or interface, by triggering related acti...
def east_button_click(): print_to_description("E", True) perform_command("E", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The code defines a function `west_button_click` that handles a button press event, printing "W" to a description, executing a "W" command (likely for movement), and updating the current state, typically used in interactive applications or games to process westward navigation actions.
def west_button_click(): print_to_description("W", True) perform_command("W", "") set_current_state()
def print_to_description(output, user_input=False): description_widget.config(state = 'normal') description_widget.insert(END, output) if (user_input): description_widget.tag_add("blue_text", CURRENT + " linestart", END + "-1c") description_widget.tag_configure("blue_text", foreground = 'blu...
The main task of the code is to handle the Enter key event in a command input widget. It retrieves the input text, logs it, clears the widget, splits the command into verb/noun components, executes the command in uppercase, and updates the application state.
def return_key_enter(event): if( event.widget == command_widget): command_string = command_widget.get() print_to_description(command_string, True) command_widget.delete(0, END) words = command_string.split(' ', 1) verb = words[0] noun = (words[1] if (len(words) > 1) ...
def serial_port_scan(self): self.session = Session() try: # Scan all serial ports serial_ports_obj_list = serial.tools.list_ports.comports() # Populate to_show and to_hide lists for serial_port_obj in serial_ports_obj_list: # Read port de...
This code initializes a GUI for serial port scanning, creating frames, buttons, and widgets to manage port details (short/full view), include hidden ports, and scan ports. It sets up a textbox with scrollbars to display found ports, binds keyboard events, and configures layout and interactions for user input and output...
def __init__(self, root_frame): self.root = root_frame self.session = Session() self.user_entry = UserEntry() self.serial_port_scan() ###################################################################### # GUI Frames # self.frame = LabelFrame(self.root, width=...
def get_cache_key(self, **parameters): return self.key_policy.cache_key( sampler_parameters=self.sampler_parameters, sampler_properties=self.sampler_properties, input_parameters={ k: v for k, v in parameters.items() if k not in ...
This function samples solutions from a QUBO problem using a cache for replay, combining cached results with new samples if needed. It checks cache availability, retrieves stored samples when possible, and delegates to a sampler for fresh results. The output is a concatenated SampleSet of replayed and newly generated sa...
def sample_qubo(self, Q: QUBO, **parameters) -> SampleSet: # QUBO as provided is not json-compatible -- store as list of items cache_key = self.get_cache_key(qubo_safe=list(Q.items()), **parameters) entry = self.get_or_insert(cache_key) num_reads = parameters.get("num_reads") re...
def writeBlock(self, lines): for line in lines: self.spatial_str += self.format(line) self.addNewline() def incIndentation(self): self.indent += 1 def setupInOutFile(self): lines = [] lines.append("val infile = buildPath(IR.config.genDir," + "\"tu...
The code defines a method `setupMain` that constructs a Scala `main` function's structure. It writes the function signature, increases indentation, configures input/output files and streams, and initiates an "Accel" block for further code generation, likely for a hardware accelerator or specialized execution environmen...
def setupMain(self): self.writeBlock(["def main(args: Array[String]): Unit = {"]) self.incIndentation() self.setupInOutFile() self.setupStreams() self.writeBlock(["Accel {"]) self.incIndentation()
def reduce(self, type, num_iters, par, idx, out, inner_lines, reduce_lines, write=True): lines = [] lines.append("val " + out + " = Reduce(Reg[" + type + "])(" + str(num_iters) + " par " + str(par) + "){ " + idx + " =>") lines.e...
The code constructs a dense neural network (DNN) layer by performing a weighted sum of inputs using a reduction operation, applying a ReLU activation with bias, and parallelizing computations across neurons. It combines weight look-up tables (LUTs), argument memory, and bias LUTs to compute neuron outputs, leveraging p...
def buildDNNLayer(self, dict): inner_line = dict["weight_lut"] + "(i,j) * " + dict["arg_mem"] + "(j)" red = self.reduce(dict["type"], dict["neuron_size"], dict["inner_par"], "j", "w", [inner_line], "_ + _", False) red.extend(self.buildReLU(d...
def run_get_primers(self): primers_file = os.path.join(self.KEY_DATABASE_PATH, self.KEY_PRIMERS_FILE) primer_fwd = '' primer_rev = '' for index, record in enumerate(SeqIO.parse(primers_file, 'fasta')): if index == 0: # forward-primer primer_fw...
The code processes metagenomic data through a pipeline: it checks read quality, merges paired-end sequences, trims primers, filters sequences, dereplicates reads, generates ASVs (amplicon sequence variants), assigns taxonomy, and compiles abundance tables with taxonomy. It handles multiple samples, verifies primer posi...
def run_pipeline_asv(self): primer_fwd, primer_rev_rc = self.run_get_primers() for subdir, dirs, files in os.walk(self.KEY_SAMPLES_PATH): for file in files: if re.search('[_][Rr][1][_]?(\w|[-])*\.([Ff][Aa][Ss][Tt][Qq]|[Ff][Qq])$', file): fastq_r1_file = o...
def tournament(p_trees, k): # using the tournament preceture for selecting a couple tree # in this method we choose 3 tree randomly 2 times (2 times becuase we want a couple), and select the best-mae tree couple_parent = [] for j in range(2): best_mae = float('inf') best_tree = None...
The function generates offspring by selecting parent pairs via tournament selection, applying crossover with probability 'pc', and mutating the resulting children with probability 'pm', returning the new generation of children.
def making_children(parent_trees, k, pc, pm): # we want to make children on base of a list of trees (parent_trees) lenght = len(parent_trees) children = [] for i in range(int(lenght/2)): #returning a couple of parents parent1, parent2 = tournament(parent_trees, k) ...
def getBestSplit(self, dataset, numSamples, numFeatures): bestSplit = {} maxInfoGain = -float("inf") for featureIndex in range(numFeatures): featureValues = dataset[:, featureIndex] possibleThresholds = np.unique(featureValues) for threshold in possibleThresho...
This function recursively builds a decision tree by splitting the dataset based on information gain. It checks if the current node can split further (based on sample count and depth limits), finds the best feature/threshold for splitting, and recursively constructs left and right subtrees. If no valid split is found, i...
def buildTree(self, dataset, currDepth=0): X, Y = dataset[:,:-1], dataset[:,-1] numSamples, numFeatures = np.shape(X) if numSamples>=self.minSamplesSplit and currDepth<=self.maxDepth: bestSplit = self.getBestSplit(dataset, numSamples, numFeatures) if bestSplit["infoGain"]...
def floors_arr(xyzfile, down_thr, up_thr): first_floors_arr = [] second_floors_arr = [] df = pd.read_table(xyzfile, skiprows=0, delim_whitespace=True, names=['x','y','z']) pcd_arr = df.to_numpy() for v in pcd_arr: if down_thr <= v[1] <= up_thr: first_floors_arr.append(v) else: second_floor...
The code converts 3D point cloud data into 2D pixel coordinates on a specific image. It rescales annotations, plots points within defined thresholds, transforms coordinates to screen pixels, and adjusts scaling ratios (3400/640, 2200/480) to map points to the target image dimensions, returning the transformed pixel coo...
def pixel_arr(txt, ply, xyzfile, bin, down_thr, up_thr, area_thr, wh_ratio_thr): first_arr, _ = floors_arr(xyzfile, down_thr, up_thr) xaxmin, xaxmax, yaxmin, yaxmax = get_xy_lim(first_arr, bin) rescale_arr = rescale_anno(txt, ply, down_thr, up_thr, area_thr, wh_ratio_thr) arr = [] x = [] y = [] for rec in...
def elastic_energy(u,p): return 0.5*(1-p)**2*inner(sigma(u), epsilon(u))*dx def dissipated_energy(p): return Gc/2*(p/l+ 0.5*l*dot(grad(p), grad(p)))*dx def external_work(u): return dot(body_force, u)*dx
The code calculates the total energy by summing the elastic energy (dependent on displacement `u` and parameters `p`) and dissipated energy (dependent on `p`), then subtracting the external work done on the system (dependent on `u`). This likely models energy balance in a mechanical or physical system, where total ener...
def total_energy(u,p): return elastic_energy(u,p) + dissipated_energy(p) - external_work(u)
def _generate_index_name(self): """ Generates an index name from the PDF file name. Returns: str: The index name. """ # Extract the base name without extension and use first 7 characters base_name = os.path.basename(self.pdf_path) valid_name = re.sub(...
The main task of the code is to upsert documents into a Pinecone index. It checks if the index exists, creates it if necessary, loads documents, and returns a PineconeVectorStore object. The function ensures the index is properly set up, handles existing indexes efficiently, and uses embeddings to store documents, wait...
def upsert_documents(self): """ Upserts the documents into the Pinecone index. Returns: Pinecone: The Pinecone object. """ if self.index_name is None: self.index_name = self._generate_index_name() print("Checking if index exists...", self._check_...
def all_players_ready_round(self) -> bool: #Return true if all but 1 folded or all in count = 0 for p in self.active_players: if not self.player_done_betting_round(p): count += 1 return (count <= 1) def __flip(self): #show cards #...
This method advances to the next betting round (street) in a game. It checks if the round should end, increments the street counter, resets betting states, and determines the next player to act. It returns True to indicate progression to the next street or round completion.
def __next_street(self) -> bool: if self.street == 3 or self.all_players_ready_round(): #End the round self.__flip() return True else: #Next street self.street += 1 #Reset turn to first to bet self.player_turn = (self.bi...
def all_players_ready_street(self) -> bool: ready = True for p in self.active_players: if not self.player_done_betting_street(p): ready = False return ready def __next_street(self) -> bool: if self.street == 3 or self.all_players_ready_round(): #En...
The main task of the code is to manage turn progression in a poker game. It checks if all players except one have folded, awards the pot to the remaining player, and ends the round. If all players are ready, it advances to the next betting round. Otherwise, it identifies the next active player who hasn't finished betti...
def __next_turn(self) -> bool: num_folded = 0 for p in self.active_players: if p.folded: num_folded += 1 #Check if everyone has folded if (num_folded + 1) == self.num_active_players: for p in self.active_players: if not p.folded: ...
def __build_sidepot(self, player_id): sidepot_index = self.__pot_placement(player_id) ############################### print(str(sidepot_index)) ############################## p = self.all_players[player_id] call = self.amount_to_call #bu...
This function handles a player's raise action by updating their bet, adjusting their chip count, managing side pots for players with zero chips, updating the main pot amount, setting the required call amount, and progressing to the next turn in a poker game.
def __raise(self, player_id, new_bet): for p in self.active_players: if p.chips == 0: self.__build_sidepot(p.player_id) p = self.all_players[player_id] self.__call_most_sidepots(p.current_bet, len(self.pot) - 1) p.current_bet += new_bet p.chip...
def __fold(self, player_id): p = self.all_players[player_id] p.folded = True self.__next_turn() def __pot_placement(self, player_id) -> int: p = self.all_players[player_id] call = self.amount_to_call i = 0 while i < len(call) and p.chips >= (call[i] - p.current_be...
This function processes a player's action in a game, validating if the player can fold, call, raise, or go all-in based on their chips and current game state. It checks if the action is valid (e.g., sufficient chips, correct turn) and updates the game state accordingly, returning 0 for success, 1 for invalid actions, o...
def take_action(self, player_id, action, new_bet=0) -> int: if self.running and (player_id == self.active_players[self.player_turn].player_id): self.running = False p = self.active_players[self.player_turn] call = self.amount_to_call if action == 0: ...
def setup_distributed(port=29500): if not dist.is_available() or not torch.cuda.is_available() or torch.cuda.device_count() <= 1: return 0, 1 if 'MPIR_CVAR_CH3_INTERFACE_HOSTNAME' in os.environ: from mpi4py import MPI mpi_rank = MPI.COMM_WORLD.Get_rank() mpi_size = MPI.COMM_WORL...
The code trains a sequence classification model (e.g., RoBERTa, BERT) using distributed training, handling multiple validation sets. It loads datasets, initializes models, trains with AdamW optimizer, evaluates metrics (accuracy, F1), saves best checkpoints, and logs results via TensorBoard. The function supports distr...
def run(max_epochs=None, device=None, batch_size=24, max_sequence_length=128, random_sequence_length=False, epoch_size=None, seed=None, data_dir='data', real_dataset='webtext', fake_dataset='xl-1542M-nucleus', token_dropout=None, la...
def _get_dir(self, state: FSState): return os.path.join(self.directory, self.name, state.value) def _move(self, name: str, old_state: FSState, new_state: FSState): os.rename(self._get_path(old_state, name), self._get_path(new_state, name)) def _get_path(self, state: FSState, name: str): return o...
The code retrieves the next priority item from a queue by accessing a READY directory, iterating through files, locking them (moving to LOCKED state), reading their contents, and deserializing the data. It returns the item ID and deserialized object, handling errors like file not found or deserialization failures.
def get(self) -> (str, object): """ Get the next priority item from the queue, returning the item ID and the object """ directory = self._get_dir(FSState.READY) print("Getting directory", directory) paths = list(Path(directory).iterdir()) print("Top paths", paths...
def find_smallest_dist(shortest_distance_dict, visted_nodes): ## cycle through shortest_distance_dictionary to find the node with the current shortest distance and unvisted largest_distance = math.inf largest_node = "" shortest_distance_dict_copy = shortest_distance_dict.copy() ## remove all vist...
The code implements Dijkstra's algorithm to compute the shortest path from node "A" to all other nodes in a graph. It initializes distances to infinity except for the starting node "A", iteratively selects the unvisited node with the smallest known distance, updates distances to its neighbors if a shorter path is found...
def Djirksta_Alg(dict_of_nodes): shortest_distance_from_A = {"A": 0, "B": math.inf, "C": math.inf, "D": math.inf, "E": math.inf} previous_vertex = {} unvisted = ["A", "B", "C", "D", "E"] visited = [] # print(find_smallest_dist(shortest_distance_from_A, visited)) while unvisted: # ...
def w_action(teams,team_round,playr): """This function allow worrior to choose one of his actions """ print("3:buy armor - buy armorfor a member of the team") print("4:share intelligence- share intelligence with the Explorer") print("5:improve strength- improve strength of warrior") chosen_action=...
The code runs a turn-based game where two teams alternate selecting characters to perform actions. Each team chooses a character (0-2) to attack or cast spells, triggering specific functions (w_action, m_action, e_action) based on the selected character. The game loops until the user inputs -1, switching teams after ea...
def run_game(teams): team_round=0 #first round start with team1. chosen_char=1 while(chosen_char !=-1): print(f"Team {team_round+1} Wich character do you wish to choose for this round?") for i in range(0,3): print(f"{i}:{teams[team_round][i].name}") #display character...
def loadDeviceTree(device): dataTree = sg.TreeData() if device == []: return dataTree dataTree = convert_dict_to_tree_data(device.toDict(), dataTree) return dataTree def loadingWindow(): loadedDevices = globals()['loadedDevices'] loadingLayout = [ [ sg.Text("UPnP options"), ], [ sg.Button("Load Dev...
This code creates a UPnP console GUI using PySimpleGUI, allowing users to select devices, view service/action trees, and send selected actions. It handles menu interactions, device data loading, service/action selection, and event-driven updates to display device info and execute actions. The interface includes dynamic...
def main(): sg.theme('DarkBlue2') selectedDevice = globals()['selectedDevice'] deviceTreeData = sg.TreeData() # define the menu menu = [ ['Window', ['New', 'Refresh']], ['Device', ['Info','Select', 'Load']], ] # set the main layout mainWindowlayout = [ [ sg.Menu(menu), sg.Text("UPnP console", font...
def getFullServiceInformation(): service = getService(options['service']) if service['serviceId'] in options['storedServices'].keys(): return options['storedServices'][service['serviceId']] else: print("Using web") url = options['baseURL']+service['SCPDURL'] r = requests.get(...
The main task of the code is to send a SOAP request to a UPnP service based on provided service information, handle the response by parsing and pretty-printing the XML, log success/failure status, and save the formatted XML response to a file. It constructs a SOAP envelope, sets appropriate headers, executes the POST r...
def send_soap_request(service): fullServiceInformation = getFullServiceInformation() # SOAP request payload based on the service's SCPD soap_request = f'''<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> {formAc...
def send_soap_request(service): fullServiceInformation = getFullServiceInformation() # SOAP request payload based on the service's SCPD soap_request = f'''<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> {formAc...
The code processes user commands to interact with services, handling 'send', 'get', 'set', 'unset', and 'show' actions. It validates arguments, modifies global options, sends SOAP requests, retrieves service info, and displays available services/actions. Error handling ensures proper feedback for invalid inputs or miss...
def commands(command): if command[0] == 'exit': exit() elif command[0] == 'send': if len(command) < 2: print('Missing arguments! Usage "send (actions of the service)" use "show services" to get all services available\nUse "show service actions" to list all service actions') ...
def initialize_optimization_variables(self): self.d_var = make_decision_variable_label(self.nofvar) self.object_coeff = [0]* self.order + [1, 0] self.ub_bound = make_demand_bound(self.nofvar, self.params["ub_bound"]) self.lb_bound = make_demand_bound(self.nofvar, self.params["lb...
The main task of the code is to perform an optimization process by initializing variables, solving the optimization problem, and visualizing the resulting solution. The method systematically sets up the problem, computes the optimal solution, and generates a visual representation of the outcome for analysis or presenta...
def optimize(self): self.initialize_optimization_variables() self.solve() self.visualize_solution()
def eval_image_boxes(box_results: List[BoxResult], box_labels: List[BoxLabel]): category_predictions = list() category_gts = list() category_confidences = list() material_predictions = list() material_gts = list() material_confidences = list() for box_result in box_results: cat_pred,...
The code evaluates predicted labels against ground truth labels for images, generating confusion matrices for category and material classifications. It processes each image's predictions, converts labels to standardized IDs, computes confusion matrices using scikit-learn, and visualizes results. The main task is to ass...
def eval_all_images(pred_dict, gt_labels: AllLabels): category_predictions = list() category_gts = list() category_confidences = list() material_predictions = list() material_gts = list() material_confidences = list() results = (category_predictions, category_gts, category_confidences, mater...
def printIntro(): print("This is to simulate the racquetball game...") def getInput(): probA = float(input("What is the prob. Player A wins a serve: ")) probB = float(input("What is the prob. Player B wins a serve: ")) n = int(input("How many games to sim?: ")) return probA, probB, n def simNGame(n,...
The main task of the code is to simulate a series of games between two players (A and B) using given probabilities of winning each game, then output the results. The `main()` function orchestrates this by first printing an introduction, retrieving user inputs for probabilities and number of games, simulating the games,...
def main(): printIntro() probA, probB, n = getInput() winsA, winsB = simNGame(n, probA, probB) printSummary(winsA, winsB)
def _error(self, msg): self.stderr.write(self.style.ERROR(msg)) def update_structure(self, json_obj): """ Takes as input a json object of the article or summary - combine token information in one element and assign an id to each token - collect entities in one object """ ...
This code imports articles from a JSON file into a database. It reads lines from the specified file, parses each line as JSON, processes the article structure, updates relations in sentences, and uses Django's update_or_create to store articles. It tracks newly created articles and handles errors by logging them and ex...
def import_articles(self, path_to_articles, dataset_id): try: with open(path_to_articles, "r") as f: articles = f.readlines() except Exception as e: self._error(f"Articles File couldn't be opened.\n{e}") exit(1) created_articles = 0 fo...
def log(self, msg): self.stdout.write(msg) def update_structure(self, json_obj): """ Takes as input a json object of the article or summary - combine token information in one element and assign an id to each token - collect entities in one object """ i = 1 for s i...
The main task of the code is to import and process summary data from JSON files into a database. It reads summaries, parses their content, computes metrics (e.g., ROUGE scores, factuality), updates data structures, and saves the results to the database using Django ORM. The function also logs successes/failures, handle...
def import_summaries(self, paths_to_summaries, dataset_id): for model_name, path in paths_to_summaries.items(): self.log(f"Importing model ({model_name}) summaries:") with open(path, "r") as f: sum_list = f.readlines() # remove empty lines sum_lis...
def _success(self, msg): self.stdout.write(self.style.SUCCESS(msg)) def _error(self, msg): self.stderr.write(self.style.ERROR(msg)) def import_articles(self, path_to_articles, dataset_id): try: with open(path_to_articles, "r") as f: articles = f.readlines() ex...
This code creates a dataset record and imports associated articles, models, and summaries from specified files using a configuration JSON. It first saves the dataset, then processes each data type sequentially, exiting on errors.
def handle(self, *args, **options): try: configs = json.load(options['config']) # 1 - Create a new dataset record ds = Dataset(name=configs["dataset"]["name"], description=configs["dataset"]["description"]) try: ds.save() self._succ...
def load_spike_units(path): sessions = helpers.get_sessions_with_drc_recordings(path) data = [] date_first_session = None index = 0 for s in sorted(sessions): session = sessions[s] print(s) print(" ", session['absolute_path']) print(" ", session['recordings']) ...
The code's main task is to match spike units between experimental and null datasets using a GMM-based EM algorithm. It computes null and experimental distributions of waveform distances, identifies units in the 99% confidence interval of the experimental distribution but outside the null's interval, and saves matched u...
def cli_wf_matching(db_path=None, output=None, nb_q_turn_null=4, confidence=0.99, overwrite=False, create_pdf=False): '''This function calculates the null distribution from the null d1_d2 data using a Expectation-Ma...
def _get_mysql_data(self): jdbc_options = self._inst_jdbc_params() jdbc_options['dbtable'] = 'sales_data' df = self.sqlcontext.read.format('jdbc').options(**jdbc_options).load() self._is_dataframe('MySQL', df) self._is_populated('MySQL', df) return df def _get_csv_dat...
The main task of the code is to retrieve and harmonize data from three sources—MySQL, CSV, and XML—into a unified DataFrame. It processes each dataset by standardizing column names, calculating commission amounts, and repartitioning data. The transformed DataFrames are combined using union operations, and the final con...
def get(self): """ Retrieve all the data from the three data sources. 1.) MySQL localhost database where `sales_data` is the table name 2.) CSV reseller data 3.) XML reseller data Return: - Final dataframe for writing to disk. """ ...
def getMatrix(): totalResults =[] trainInputFeatures =[] trainResults =[] testInputFeatures =[] testResults=[] inputFeatures = [] trainMax =409 features = ['p1_pts','p1_reb','p1_ast', 'p2_pts','p2_reb','p2_ast', 'p3_pts','p3_reb','p3_ast', ...
The main task of the code is to perform linear regression using gradient descent on a training dataset. It prepares training and test data by adding bias terms, initializes a theta vector, computes the cost function, and updates theta via gradient descent with a specified learning rate. The goal is to learn optimal par...
def mainAlgorithm(): #calls getMatrix to get the train data/results and test data/results ms = getMatrix() #this X holds all training exmaples in 410x36 matrix Theta = np.zeros(37,) #create thetas for all features tX = ms[0].transpose() #add x0 =1 for all rows x0 = np.ones(409,) X ...
def matrices(): trainX =[] with open('normalizedTrainData.csv','r') as trainFile: csv_reader = csv.reader(trainFile) for line in csv_reader: trainX.append(line) ''' indices = [16,24,32,40,48,56,64,72,80,88,96,104] for x in trainX: for index in indices[::...
The main task of the code is to train a 4-layer neural network using gradient descent on a dataset (X, Y) over 10,000 epochs. It initializes weights and biases, performs forward propagation, computes gradients, updates parameters iteratively, and evaluates the cost function. The trained model is finally tested using th...
def main(): matrixs = matrices() X = matrixs[0] Y = matrixs[1] m = 6000 numLayers = 4 alpha = .01 W0 = np.random.rand(30,100) W0 = W0/10 b0 = np.zeros((30,1)) W1= np.random.rand(15,30) W1 = W1/10 b1= np.zeros((15,1)) W2 = np.random.rand(12,15)...
def extract_mfccs(audio, sample_rate): result = lb.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40) if result.shape[1] != 275: result = pad_along_axis(result, 275, axis = 1) result = scale(result, axis = 1) return result def extract_melspec(audio, sample_rate): result = lb.feature.melspectro...
The main task of the code is to load and preprocess audio files containing specified target emotions, actors, and vocal channels. It filters files based on these criteria, extracts audio features (MFCCs, mel-spectrograms, chroma), and compiles them into a structured pandas DataFrame with metadata. The function returns ...
def load_targets(target_emotions, target_actors, target_channels = ['song', 'speech']): #load files that contain target emotion sounds = [] for file in glob.glob('./data/samples/*.wav'): file_name = os.path.basename(file) #filter out non-target channels- set to all by default ...
def conv2d_test(): x = (0.5+np.arange(14, dtype=np.float32))/13.5 x = np.stack([x + i for i in range(28)]) x = np.random.randn(1, 2, 8, 8) K = 3 w = np.random.randn(4, 2, K, K) weight = torch.tensor(w, requires_grad=True) x = torch.tensor(x, requires_grad=True) out = F.conv2d(x, weigh...
The main task of the code is to execute multiple tests for neural network operations (conv2d, avgpool2d, matmul, unfold) and demonstrate a PyTorch convolution with gradient computation. It initializes tensors, applies a 2D convolution, computes a loss, performs backpropagation, and prints output values and weight gradi...
def main(): np.random.seed(0x43534) conv2d_test() avgpool2d_test() matmul_test() unfold_test() return x = (0.5+np.arange(28, dtype=np.float32))/27.5 x = np.stack([x + i for i in range(28)]) # w = (-1+np.arange(3, dtype=np.float32)) # w = np.stack([w + i for i in range(3)]) w...
def reset_seed(seed): """ ref: https://forums.fast.ai/t/accumulating-gradients/33219/28 """ random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True def parse(): ...
The code performs medical image segmentation using a U-Net model with an EfficientNet encoder. It loads configuration parameters from a YAML file, initializes the model with pre-trained weights from specified folds, and conducts inference on whole slide images (WSIs), saving segmented results to a designated output pat...
def segmentation_test(): reset_seed(1) args = parse() yam_file = open('./arguments.yaml') parsed_yaml = yaml.load(yam_file, Loader=yaml.FullLoader) num_classes = parsed_yaml['segment']['num_classes'] input_path = parsed_yaml['segment']['image'] output_path = parsed_yaml['segment']['results']...
def calc_L_hat_supply( theta, alpha, pi_init, L_init, R_bar_init, w_hat, q_hat, kappa_hat, B_hat, R_bar_hat ): """ Calculate change in labor supply Arguments: theta: preference shock dispersion parameter alpha: final good consumption share pi_init: unconditional commuting probabi...
The function `summarize_counterfactual` compiles counterfactual simulation results by calculating derived variables (L_hat, R_hat, U_hat) from input parameters like wage, rent, and population changes. It merges these results with geospatial neighborhood data into a structured DataFrame, enabling spatial analysis of eco...
def summarize_counterfactual( num_nbhd, neighborhoods_shp, w_hat, q_hat, theta, alpha, pi_init, L_init, R_init, R_bar_init, kappa_hat, B_hat, R_bar_hat, ): """ Summarize exact hat results of counterfactual simulation Arguments: num_nbhd: number of ...
def make_content_update(last_version, date): update = [] current_version = add_to_version(last_version, Types.CONTENT) content_update_date = datetime(year=date.year, month=date.month, day=date.day, hour=randint(0, 23), minute=randint(0, 59)) update.append((current_version, Types.CONTENT, content_update_...
The function processes monthly updates from a start date up to a specified checkpoint date. It iteratively generates content updates, increments the date by one month each cycle, accumulates changes in a list, and saves the final result to a file. The loop stops when the current date reaches or exceeds the checkpoint, ...
def run_checkpoint(updates, version, current_date, checkpoint, file_number): while current_date < checkpoint: update, version = make_content_update(version, current_date) updates += update current_date = add_month(current_date) save_to_file(updates, file_number) return updates, versi...
def arm_routine(self): # Do this five times: self.raise_lower_both_arms() self.dance_front_then_back() def raise_both_arms(self): if self.swarm: # We want them to execute at the same time so we save it and then execute it after queue = [] for each_rove...
The code handles different interaction modes by executing specific actions based on the received integer value. It logs status, triggers arm routines (calibration, raising/stopping arms), and enables swarm mode with flag settings and timed movements.
def on_interaction(self, int32msg): mode = int32msg.data if mode == 0: self.get_logger().info('Interaction mode is off') return elif mode == 1: # Calibration Dance self.arm_routine() elif mode == 2: # Raise front arm and back ar...
def spAND(*inputsp): #handles AND gates s = 1 for inp in inputsp: s = s * inp return s def spOR(*inputsp): #handles OR gates s = 1 temp = 1 for inp in inputsp: temp = temp * (1 - inp) s = 1 - temp return s def sp2XOR(input1sp,input2sp): #for creating the ...
This function processes logic gates by applying corresponding operations (AND, OR, XOR, etc.) to inputs based on the element's type and gate count, updating the signalTable with computed outputs. It handles 2-input, 3-input, and multi-input XOR gates, with error checks for unsupported types or invalid configurations.
def process(element,signalTable): if(element.gate == 2): if(element.ElementTypes=='AND'): signalTable[element.output]=spAND(signalTable[element.inputs[0]],signalTable[element.inputs[1]]) elif(element.ElementTypes=='OR'): signalTable[element.output]=spOR(signalTable[element.in...
def table(inputs): #create truth table #print(inputs) for i in range(0,len(inputs)): SignalsTable[i] = inputs[i] return SignalsTable def crElement(ElementTypes,TotalInputs,TotalOutputs,InputNumElements): ElementTable = [] tempInputNumElements = [] tempInputNumElemen...
This code simulates a digital circuit's behavior by generating truth tables for multiple input combinations, constructing signal tables, processing logic elements, and calculating switching activity metrics for specific test cases. It iterates through all possible input patterns, evaluates circuit outputs, and computes...
def testbench(ElementTypes,inputs): b = [0,1] N = len(TopInputs) TruthTableInputs = list(it.product(b,repeat = inputs))#for truth table TruthTableInputs.append((0.5,)*N) #for esw TruthTableInputs.append((0.4035,)*N) # for personal esw for i in InputNumElements: #create the signal tabl...
def createWorkload(inp, L): #create random workload wl = [] lenInp = len(inp) for y in range(0,L): ls = [] for i in range(0,lenInp): w = np.random.choice([0,1]) ls.append(w) wl.append(ls) #print(wl) return wl def table(inputs)...
The code implements a genetic algorithm to optimize workload configurations by iteratively generating, evaluating, and evolving workloads through selection, crossover, and mutation. It processes elements based on input/output rules, calculates scores, tracks high-performing workloads, and visualizes results to identify...
def testbench2(ElementTypes,inputs): for times in range(3): # times of testbench run workloads=[] totalSw = [] best = open("BestScoreGeneration.txt","w") # file workload with best score totalGenerationHighScores = [] create_signal_len...
def get_id(data): ''' Returns a mapping between the protein id and a numeric id ''' ids = set() p2id = dict() for i, node in enumerate(data['nodes']): pid = node['id'] l1 = len(ids) ids.add(pid) l2 = len(ids) if l1 == l2: continue else: p2id[pid] = i return p2id def get_locations(): file_l = (...
The code prepares data for GraphSAGE by: removing 'multigraph', assigning node IDs and locations, splitting nodes into train/val/test sets (10% each), adding labels, converting IDs, generating random features, and marking links with removal status based on node indices. It structures nodes and links with required attri...
def process_data(data): ''' Prepares the data (dict) in the required format for GraphSAGE ''' del data['multigraph'] p2id = get_id(data) p2loc = get_locations() n = len(data['nodes']) val_split = int(0.1*n) test_split = int(0.1*n) for i,_ in enumerate(data['nodes']): if i < val_split: data['nodes'][i][...
def _open_tasks_input_with_editor(self): tmp_filename = "tmp_tasks" self.tmp_filepath = f"{self.folder_path}{tmp_filename}" command = f"$EDITOR {self.tmp_filepath}" self.input_format_strategy.create_file(self.folder_path, tmp_filename) subprocess.call(command, shell=True) def _pa...
The code's main task is to execute a timer-based process by opening an editor for task input, parsing tasks from a temporary file, generating timer entries, and running the timer with these entries. It orchestrates task parsing and timer execution in a structured workflow.
def run(self): self._open_tasks_input_with_editor() tasks = self._parse_tasks(self.tmp_filepath) entries = self.get_timer_entries(tasks) self.run_timer(entries)
def to_bgr(self): """Converts initial image to BGR mode Returns: np.array: BGR Initial Image """ if self.mode == "rgb": return cv2.cvtColor(self.image.copy(), cv2.COLOR_BGR2RGB) elif self.mode == "bgr": return image def _check_matches(...
This function validates Aruco detection success by using SIFT to match enclosed/unenclosed markers against training images, generating masks, and checking IoU/inclusion ratio thresholds. It returns True if SIFT matches and geometric metrics meet criteria, otherwise False.
def _sift_confirmation(self, aruco_corners_ordered): """Checks out every condition to meet to consider Aruco Detection successful Args: aruco_corners_ordered (list): list of ordered Aruco corners coordinates Returns: bool: Whether or not Aruco detection ...
def to_gray(self): """Converts initial image to GRAYSCALE mode Returns: np.array: GRAYSCALE Initial Image """ if self.mode == "rgb": return cv2.cvtColor(self.image.copy(), cv2.COLOR_RGB2GRAY) elif self.mode == "bgr": return cv2.cvtColo...
This function detects Aruco markers in an image, validates their corners, and computes horizontal and vertical vanishing points using marker geometry. It returns the vanishing points as numpy arrays if markers are valid; otherwise, returns False.
def _warp_with_marker(self): """Algorithm to find vanishing points in a scene with an Aruco marker Returns: np.array: Horizontal vanishing point np.array: Vertical vanishing point """ # Compute Corner detection & order points corners, ids = detect...
def reparametrize_xi(xi, r): df = pd.read_csv("xi_scaling_polynomial.txt") width_params = df['coefficient'][np.where(df['type']=="width")[0]] width_degrees = df['degree'][np.where(df['type']=="width")[0]] mid_params = df['coefficient'][np.where(df['type']=="middle")[0]] mid_degrees = df['degree'][np...
The code trains a neural network to predict parameters (alpha) from input data (xi_prime) using a variational autoencoder framework. It loads data from an HDF5 file, splits it into training/test sets, initializes a custom model (AuxLatentNN), trains it with Adam optimizer, tracks training/test losses, and visualizes re...
def main(args): if not os.path.exists(args.savepath): os.makedirs(args.savepath) with open(args.savepath+"/run_call.txt", 'w') as textfile: call_string =" ".join(sys.argv) textfile.write(f"{call_string}") data = h5py.File("vae-fit-test0.h5", 'r') alpha = data['alpha'][...] ...
def find_peakidxs_multi_thres(arr: ndarray, thresholds: List[float]): peak_idxs: ndarray = np.hstack([find_peakidxs_thres(arr, thres) for thres in thresholds]) peak_idxs = np.unique(peak_idxs.astype(int)) return peak_idxs def define_crossing_thresholds(arr: ndarray, peak_...
The code identifies notes in an audio signal by detecting peak indices using multiple thresholds, refining crossing thresholds, and determining note boundaries through crossings. It iteratively refines peak indices and thresholds to accurately locate note start and end indices in the input signal, returning them as an ...
def find_notes(dec: ndarray, peak_thresholds: List[float]): """Find notes. Args: dec (ndarray): signal to find notes, typically sound intensity. peak_thresholds (List[float]): List of thresholds to find notes. Returns: notes: n_notes x 2. start and end indices for each note """...
def find_peakidxs_from_notes(self): """ Find local maximum indice from notes. """ self.peak_idxs = np.array([np.argmax(self.dec[n[0]:n[1]]) + n[0] for n in self.notes]) return self def find_notes_from_peakidxs(self): """Find notes from pe...
This function removes specified notes by their indices from the `notes` array, then recalculates peak indices, notes from peaks, and note lengths to update the internal state. It ensures the note data is adjusted and reprocessed after removal.
def remove_notes_by_index(self, idxs: List[int]): """ Remove notes by indices. Refind the ones left. Args: idxs (List[int]): indices of notes to remove """ self.notes = np.delete(self.notes, idxs, axis=0) self.find_peakidxs_from_notes() self.find_note...