dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def getNoteX(self, pitch): if pitch < self.middleNote: return self.getNoteX(pitch + 1) - (self.getNoteWidth(pitch + 1) + self.getNoteWidth(pitch)) / 2 if pitch > self.middleNote: return self.getNoteX(pitch - 1) + (self.getNoteWidth(pitch - 1) + self.getNoteWidth(pitch)) / 2 ...
This code renders a visual representation of musical notes on a surface, including time dividers, note dividers, active notes, a piano keyboard, and particles. It calculates positions for notes and octaves, draws horizontal/vertical lines for divisions, renders pressed notes, and displays the piano with key states. The...
def draw(self, surface: Surface): divider = 2 # Draw time dividers for t in range(int(self.historyHeight) // (self.timeScale // divider) + 1): p = self.historyHeight - (t + ((self.time * divider) % 1)) * (self.timeScale / divider) pygame.draw.line(surface, (50, 50, 50), ...
def get_d1(self): """ Gets the d1 of the option. For more information, visit https://github.com/JulioManuelOsorio/derivatives-package Parameters ---------- Returns ---------- float The d1 of the option """ ...
The function calculates the theta (time decay) of a European option using the Black-Scholes model. It returns a float representing the rate of change in the option's value per unit time, considering parameters like stock price (S), strike price (K), volatility (σ), time to maturity (τ), and risk-free rate (r). The form...
def get_theta(self): """ Gets the theta of the option. For more information, visit https://github.com/JulioManuelOsorio/derivatives-package Parameters ---------- Returns ---------- float The theta of the option """ ...
def get_CRR_dt(self, N): """ Following the notation of the Cox-Ross-Rubinstein model, gets the dt of the option. For more information, visit https://github.com/JulioManuelOsorio/derivatives-package Parameters ---------- N : int Number of binomial time steps ...
The function `get_CRR_p` calculates the risk-neutral probability $ p $ of an upward price movement in the underlying asset per binomial time step under the Cox-Ross-Rubinstein (CRR) model. It uses the risk-free rate $ r $, time step duration $ \Delta t $, and the up/down factors $ u $ and $ d $ to compute $ p $ via the...
def get_CRR_p(self, N): """ Following the notation of the Cox-Ross-Rubinstein model, gets the probability that the price of the underlying asset will go up at each binomial time step (here, we call it "the p of the option"). For more information, visit https://github.com/JulioManuelOsorio/derivatives-pa...
def get_d1(self): """ Gets the d1 of the option. For more information, visit https://github.com/JulioManuelOsorio/derivatives-package Parameters ---------- Returns ---------- float The d1 of the option """ ...
The function `get_price` calculates the price of a financial option using either the Black-Scholes-Merton (BSM) model or the Cox-Ross-Rubinstein (CRR) binomial model, depending on the `solver` parameter. For BSM, it applies the closed-form formula involving log-normal distributions and parameters like asset price, stri...
def get_price(self, solver, N = None): """ Gets the price of the option, based on the solver. For more information, visit https://github.com/JulioManuelOsorio/derivatives-package Parameters ---------- solver : str Method used to estimate the price of the opti...
def parse_regions(melbGrid:json) -> (list, list): latitudes = [] longtitudes = [] for item in melbGrid['features']: latitudes.append(item['properties']['xmin']) latitudes.append(item['properties']['xmax']) longtitudes.append(item['properties']['ymin']) longtitudes.append(item['properties']['ymax']) latit...
The main task of the code is to analyze the sentiment of tweets based on their geographical regions. It loads region data, parses sentiment scores from a lexicon, and aggregates tweet sentiment scores and counts per region using `collections.Counter`, returning both aggregated sentiment scores and total tweet counts pe...
def do_work(tweets: list, coordinates: list) -> (collections.Counter, collections.Counter): with open(PATH_MELBGRID) as f: melbGrid = json.load(f) latitudes, longtitudes = parse_regions(melbGrid) with open(PATH_AFINN) as f: word_score_pair = f.readlines() afinn = {} for line in word_score_pair: word, sc...
def collectresults(): company = getcompanyname() while company: if company == "": break quizkeys = quiz.keys() quizkeys.sort() for question in quizkeys: showquestion(lo_question = question,lo_company = company) company = getcompanyname() if l...
The main task of the code is to run a benchmark tool that prompts the user to either load pre-saved results or collect new ones. If the user chooses to load results, it retrieves and displays stored company data (average, max, min values). Otherwise, it directly collects new results. The tool then exits after processin...
def main(): print print("Welcome to the benchmark tool!") print userinput = input("Do you want to load the saved results?") if userinput == " ": collectresults() elif string.upper(userinput[0]) == "Y": gl_companies,gl_avg,gl_max,gl_min = loadresults() showresults(gl_com...
def is_train_test_file_exists(self) -> bool: try: logging.info(f"Checking if train and test file exists.") is_train_file_exist = False is_test_file_exist = False train_file_path = self.data_ingestion_artifact.train_file_path test_file_path = self.data...
This method performs data validation by checking the existence of train/test files, validating the dataset schema, and detecting data drift. If successful, it generates a DataValidationArtifact with schema/report paths and validation status. It returns the artifact or raises an exception on failure.
def initiate_data_validation(self) -> DataValidationArtifact: try: self.is_train_test_file_exists() self.validate_dataset_schema() self.is_data_drift_found() data_validation_artifact = DataValidationArtifact( schema_file_path=self.data_validation_...
def _calculate_subtotal(self): return sum( [ item['count'] * self.products[item['product_key']]['price'] for item in self.items ] ) def _calculate_sales_tax_total(self, sales_tax_rate): return self._calculate_subtotal() * sales_tax_rate def...
The code calculates subtotal, sales tax total, and total for a list of items using a given tax rate. It initializes items, computes each value via helper methods, and returns a dictionary with these totals, including the applied tax rate.
def calculate_totals(self, items = None, sales_tax_rate = 0): 'Calculate the subtotal, sales tax total, and total based on the items' self.items = items or [] return { 'subtotal': self._calculate_subtotal(), 'sales_tax_rate': sales_tax_rate, 'sales_tax_total...
def find(self, val): if self.root is not None: return self._find(val, self.root) else: return None def treeMinimum(self, x): while x.l is not None: x = x.l return x def findParent(self, rootNode, elem): if rootNode is None: return N...
This function finds the inorder successor of a given value in a binary search tree. It first checks if the target node has a right subtree, returning its minimum value if so. If not, it traverses upward to find the first ancestor where the target node is the left child, returning that ancestor as the successor.
def treeSuccessor(self, value): node = self.find(value) if node is None: return None if node.r is not None: return self.treeMinimum(node.r) y = self.findParent(self.root, node) while y is not None and node == y.r: node = y y = self....
def transplant(self, u, v): uParent = self.findParent(self.root, u) if uParent is None: self.root = v elif u == uParent.l: uParent.l = v else: uParent.r = v if v is not None: vParent = self.findParent(self.root, v) vPar...
This code deletes a node with a specified value from a binary tree. It checks if the node exists, handles empty trees, and manages three cases: nodes with no children, one child, or two children. For two children, it replaces the node with the minimum value in its right subtree, adjusts pointers, and ensures proper tre...
def delete(self, value): node = tree.find(value) if node is None: print("Node not found") return if self.root is None: print("Tree is empty") return if node.l is None: self.transplant(node, node.r) elif node.r is None: ...
def do_bucket_sort(buckarr): greatest = 0 for i in range(len(buckarr)): if buckarr[i] > 1: length = len(str(buckarr[i])) greatest = length if length > greatest else greatest divisor = 10 ** greatest for i in range(len(buckarr)): buckarr[i] = (buckarr[i] / divisor)...
The main task of the code is to test and compare three sorting algorithms (bucket sort, quicksort, and radix sort) by applying each to a copy of the input array and printing the original and sorted results. It creates duplicates of the input array, applies each sorting method, and outputs the sorted arrays for visual c...
def test_sort(A): print("------------------------------------------------------------") print("Original array:", A) buckarr = A[:] do_bucket_sort(buckarr) quickarr = A[:] quicksort(quickarr, 0, len(A) - 1) radarr = A[:] radarr = do_radix_sort(radarr) print("Sorted array using bucke...
def connect_to_lans(self): # print(self.station_info["stations"]) for interface in self.station_info["stations"]: bridge_name = self.station_info[interface]["lan"] #check if there is an active lan with lan_name all_bridges = load_json_file('all_lans.json') ...
The main task of the code is to manage network connections by connecting to LANs, handling input/output via I/O multiplexing (select), processing incoming messages, maintaining connection timers, and gracefully disconnecting inactive or failed connections. It also handles user input for commands, monitors socket activi...
def start(self): try: #try connecting to lans self.connect_to_lans() # print('Enter the message in format: destination_name;message') for conn in self.all_connections: self.add_time(conn) while True: # threading.Thread(...
def read_from_json(self): """Read json file (no,x y, ori)""" #for 'while' reading_json = True num_select = 1 #json open try: f = open(self.path_to_json) data = json.load(f) json_place = [] parking_coordinates = [] for i in data: json_place.append(i) #rospy.loginfo("This is "+ i + "...
The code simulates an autonomous parking station interface, allowing users to park cars (with time-based categorization), retrieve parked cars, or check available spots. It maintains parking data, validates user inputs, and logs interactions using ROS. The loop continues until the user exits, summarizing parked car cou...
def test_ta_(self): self.log_topic_vars() try: self.total_parking_place = int(len(self.read_from_json()[1])) except: rospy.loginfo("Json not found") self.reset_place(self.available_places, self.total_parking_place) rospy.loginfo('******************************') rospy.loginfo('Welcome to Autonomou...
def find_loop(graph): """Attempts to find loops in a graph""" #print_matrix(graph.adj, tag='Full') # trim the graph to remove terminal atoms and terminal groups adj, nodes, edges = trim_graph(graph.adj, graph.nodes, graph.edges, save=True) #print_matrix(adj, tag='TrimmedFull') loops, anchors =...
The main task of the code is to process a graph data file, generate it if missing, identify substructures and loops, create a simplified quotient graph, and output analysis results including substructure reports, dummy nodes, and a node legend. It handles both data loading/generation and structural analysis to produce ...
def main(): """Main execution of script""" os.system('cls') print('=' * 50 + '\nStarting Quotient Graph Code\n') print('Version %s' % VER) print('=' * 50) print("Loading graph data from", infile) print('~' * 50) if not os.path.exists(infile): print('Graph file: %s' % infile, "not...
def parse_sub_file(path): ''' Parses a subtitle file. ''' starts, ends, texts = [], [], [] in_stream = open(path, 'r') # while the end of the file has been reached while in_stream: start_secs, end_secs, text = parse_sub(in_stream) if (start_secs is None)...
This function aggregates subtitle data from multiple folders into a structured pandas DataFrame, including video IDs, timestamps, subtitles, and source comments. It processes the data by adding adjusted end times, filtering entries, and optionally saving the resulting dataset as a TSV file.
def subtitles_dataframe(subs_folders, save_path=None): ''' creates a pd.DataFrame object and saves .csv ''' video_ids_acc = [] starts_acc = [] ends_acc = [] subs_acc = [] comments_acc = [] # repeats the same procedure for each folder with subs (en, translated, other) fo...
def instantiate_model(input_shape, dropout_rate = 0, l2_lambda = 0): ## define model architecture # input input_layer = layers.Input(shape = input_shape) # dense first_dense_layer = layers.Dense( units = 256, activation = "relu", kernel_regularizer = regularizers.l2(l2_lambd...
The code trains and evaluates three game decision models iteratively over multiple generations. It simulates games using baseline models, trains each decision-specific model on generated data, and compares their performance. If the trained models outperform baselines by a 55% to 45% margin, they are returned; otherwise...
def training_iteration(generations, baseline_models, games_per_generation = 100): # instantiate models for each of the game decisions model_turn_around = instantiate_model((245, ), 0.3, 0) model_pick_up = instantiate_model((245, ), 0.3, 0) model_drop_token = instantiate_model((276, ), 0.3, 0) # sim...
def mkdirp(d): pathlib.Path(d).mkdir(parents=True, exist_ok=True) def gen_keys(key_count, keystore): mkdirp(keystore) keys = {} with tempfile.TemporaryDirectory() as tmpstore: super_secret = os.path.join(output_dir, 'super_secret') create_cmd = [ 'geth', '--datad...
The main task of the code is to initialize a network with multiple authorities by generating cryptographic keys, creating a genesis block, and setting up node directories. It creates a super secret file, generates authority keys, constructs a genesis block from these keys, and initializes each node's data with the gene...
def init_net(authority_count): mkdirp(output_dir) nodes = os.path.join(output_dir, 'nodes') keystore = os.path.join(output_dir, 'keys') super_secret = os.path.join(output_dir, 'super_secret') with open(super_secret, 'wt') as f: f.write('woshiyizhidahuamao') print("Generating authority...
def init_net(output_dir, node_cnt): print('initializing bitcoin regtest local net..') mkdirp(output_dir) print('initializing nodes..') basic_port = 19555 basic_rpc_port = 20555 bootnodes = [] for i in range(1, node_cnt + 1): datadir = os.path.join(output_dir, 'nodes', str(i)) ...
The code initializes and starts a local network of 4 nodes in a directory named 'tutorial-net', waits for them to start, then launches a miner using the data directory of node 1.
def main(): output_dir = os.path.join(os.getcwd(), 'tutorial-net') if not os.path.exists(output_dir): init_net(output_dir, 4) start_net(output_dir) time.sleep(5) print('sleep 5 secs, wait for nodes starting..') miner_datadir = os.path.join(output_dir, 'nodes', '1') star...
def crawl_all_urls_for_given_team_in_league_competitions(team_id, competition_name, first_season_year = 2009, last_season_year = 2023): # start of the process now = time.time() dict_of_league_competitions_urls = dict() if last_season_year > 2023: last_season_year = 2023 if last_season_yea...
This function crawls player statistics (e.g., summary, offensive, defensive) for teams in a specified league between given years, saves data as CSV files, and logs performance metrics. It iterates through teams, extracts URLs for each season, fetches relevant stats based on the 'stat' parameter, and stores results in s...
def crawl_chosen_stats_between_years(league, teams_details, start_year, end_year, stat='summary'): # start of the whole process global driver_connection_counter, driver_connection_time_sum, driver_connection_time_average global fetching_data_counter, fetching_data_time_sum, fetching_data_time_average n...
def print_line(line): line_txt = ' '.join(word[0] for word in line) print(line_txt) def separte_by_columns_new(sorted_lines): copy_sorted_lines = sorted_lines col1_lines = [] col2_lines = [] # checking based on starting position of the line upper_starting_x_cord_of_line = np.percentile([lin...
The code processes OCR data from a JSON file by grouping text blocks into lines based on vertical alignment, sorts lines by position, arranges words within lines horizontally, calculates metrics like character height, and separates content into columns for structured output.
def main(): with open('file/rm2.json') as json_file: data = json.load(json_file) blocks = data["textAnnotations"][1:] # print(data) lines = [] words = [] prev_y = None for block in blocks: vertices = block['boundingPoly']['vertices'] # print(f'({vertices[0]["x"]},...
def choose_feature(self, data, label, columns, is_categorical): min_entropy = math.inf best_feature = 0 is_cat = True for i in range(len(columns)): if is_categorical[i]: entropy = self.cond_entropy_categorical(data, label, columns[i]) if entrop...
The code constructs a decision tree recursively by selecting the best feature to split data, handling categorical and continuous features differently. It creates child nodes based on splits, stops when features are exhausted, depth limits are reached, or label purity meets thresholds, and recursively builds subtrees fo...
def construct_tree(self, tree, features, depth, is_categorical): if len(features) == 0: return tree elif depth == self.max_depth: return tree elif (np.sum(tree.label) / len(tree.label)) >= self.threshold or (np.sum(tree.label) / len(tree.label)) <= 1 - self.threshold: ...
def get_locations(self, obj): ''' Return a list of tuple locations (x,y) for given (str) obj ''' locations = [] for i in range(self.rows): for j in range(self.cols): # check that there's more than one of the same obj in a given location ...
The main task of the code is to move all "YOU" objects in a grid according to specified directional rules, handling collisions by pushing or pulling objects when necessary. It checks movement validity, processes each "YOU" object's positions, and applies movement logic based on adjacent objects' presence, ensuring comp...
def move(self, property_rules, direction): ''' Given the property_rules (dict) and direction, move all the YOU objects according to rules in lab 10. ''' # unpack direction components dx, dy = direction_vector[direction] # get all the unique objects with p...
def init_config(): now = datetime.now().strftime("%m.%d.%Y_%H:%M:%S") with open('config.yml', 'r') as yamlfile: cur_yaml = yaml.safe_load(yamlfile) cur_yaml['import'].update({'classDateTime': cur_yaml['import']['class'] + '_' + now}) if cur_yaml: with open('config.yml', 'w') as yaml...
The code generates FHIR import scripts for code systems (CS) and value sets (VS) from a CSV resource file. It initializes configurations, processes the input file, and creates scripts in a dedicated folder. Each row is evaluated: CS/VS resources trigger script generation, while others are ignored with a warning. The to...
def generate_scripts(resource_file): """ Parameter resource_file: path to csv file with resources """ init_config() t = token() process_resource_file(resource_file) load_defined_properties(t) create_import_script_folder() for row in resource_file_rows_to_import: if is_c...
def initialize(self, hidL, hidU): self.weights = {} hidL = range(1,hidL+1) currXsize = self.inSize if len(hidL) != 0 and hidU: for l,n in zip(hidL, hidU): w = np.random.uniform(-1,1,(currXsize,n)) b = np.random.uniform(-1,1, n) ...
The code trains a model using specified hyperparameters (bestHypSet) over given epochs, computes training and validation errors iteratively, logs these errors in formatted tables, visualizes error trends, and evaluates final model performance on training and test datasets, reporting misclassification and proxy error me...
def predict(self, bestHypSet, modellayout, hyperSet, epochs): l, u , lr = bestHypSet self.ValErr, self.TrainErr = [],[] if l == 1 or l == 0: self.initialize(int(l), [int(u)]*int(l)) else: self.initialize(int(l), [int(u[0]),int(u[1])]) for epoch in range(ep...
def initialize(self, hidL, hidU): self.weights = {} hidL = range(1,hidL+1) currXsize = self.inSize if len(hidL) != 0 and hidU: for l,n in zip(hidL, hidU): w = np.random.uniform(-1,1,(currXsize,n)) b = np.random.uniform(-1,1, n) ...
This function performs hyperparameter tuning for a machine learning model using cross-validation. It iterates over learning rates in 'hyperSet', trains the model for given epochs with k-fold cross-validation, evaluates training/test errors, selects the optimal learning rate minimizing validation error, and retrains the...
def model1(self,params, epochs = 5): hidL = params['hidL'] hidU = params['hidU'] hyperSet = params['lr'] errTrain = [] errTest = [] self.TrainErr = [] self.ValErr = [] print('==> Model Selection......') for lr in hyperSet: start = time....
def initialize(self, hidL, hidU): self.weights = {} hidL = range(1,hidL+1) currXsize = self.inSize if len(hidL) != 0 and hidU: for l,n in zip(hidL, hidU): w = np.random.uniform(-1,1,(currXsize,n)) b = np.random.uniform(-1,1, n) ...
The code performs hyperparameter tuning for a neural network by systematically testing combinations of hidden layers (hidL), units (hidU), and learning rates (lr) through cross-validation. It trains models for each combination, evaluates training and validation errors, selects the optimal hyperparameters based on minim...
def model2(self,params, epochs = 5): hidL = params['hidL'] hidU = params['hidU'] learningRate = params['lr'] self.TrainErr = {} self.ValErr = {} print('==> Model Selection......') for l in hidL: for u in hidU: for lr in learningRate: ...
def initialize(self, hidL, hidU): self.weights = {} hidL = range(1,hidL+1) currXsize = self.inSize if len(hidL) != 0 and hidU: for l,n in zip(hidL, hidU): w = np.random.uniform(-1,1,(currXsize,n)) b = np.random.uniform(-1,1, n) ...
This code performs hyperparameter tuning for a neural network model using grid search. It iterates over combinations of hidden layer units (hidU1, hidU2) and learning rates, training the model with cross-validation for each. It records training/validation errors, identifies the optimal hyperparameters minimizing valida...
def model3(self,params, epochs = 5): hidL = params['hidL'] hidU = params['hidU'] learningRate = params['lr'] self.TrainErr = {} self.ValErr = {} print('==> Model Selection......') for u1 in hidU[0]: for u2 in hidU[1]: for lr in learning...
def eat(self, types, endpoint=False) -> Token: if not isinstance(types, list): types = [types] got = "eat error" try: self._next() assert self.cur_token.type in types return self.cur_token except StopIteration: if endpoint: ...
This function parses operations into abstract syntax tree (AST) nodes. It handles NAME (defining operations with inputs), LOOP/WHILE (loop constructs with counters), END (termination), and VAR (assignments). It consumes tokens, validates syntax, and returns corresponding nodes like NameDefNode, LoopNode, WhileNode, or ...
def parse_operation(self): token = self.eat(["LOOP", "WHILE", "NAME", "END", "VAR"], endpoint=True) # Blocks if token.type == "NAME": name = token.value inputs = [] while True: token = self.eat(["PARAM", "BEGIN"]) if token.type ...
def read_magic(path: Union[bytes, str, os.PathLike]) -> magic.FileMagic: """ Detect file type using 'file-magic' library. Work around 'file-magic' bug by returning default FileMagic instance. """ try: return magic.detect_from_filename(path) except UnicodeDecodeError as exc: logg...
The code postprocesses files by converting Apple binary property lists to XML format and dumping SQLite databases to new SQL files if they don't exist. It uses file magic detection to identify file types, performs in-place conversions for plists, and creates separate SQL dumps for SQLite files. The function logs action...
def postprocess(path: Union[bytes, str, os.PathLike]): """ Postprocess file based on its type (as determined by 'magic'). * Convert Apple property lists that are binary to xml format (in-place) * Dump SQLite databases to new SQL file alongside original (if not exists) """ file_magic = read_magic...
def get_vector(img_list): vec = [] for img in img_list: #print(img.shape) dim = (512,512) resized = cv2.resize(img,dim, interpolation = cv2.INTER_AREA) #print(resized.shape) for i in range(0, resized.shape[0], 4): for j in range(0, resized.shape[1], 4): ...
The code performs image quantization using a codebook generated from a set of training images. It resizes the input image, extracts features from training images, builds a codebook, encodes/decodes the target image, saves the result, and calculates PSNR to evaluate quality.
def VQ(img_name_list, cb_size, img_to_quant): #img_name_list: list of images' names in string #cb_size: codebook size #img_to_quant:image to be quantized img = cv2.imread(img_to_quant, cv2.IMREAD_GRAYSCALE) dim = (512,512) img = cv2.resize(img,dim, interpolation = cv2.INTER_AREA) cv2.imwrit...
def choosenAction(): x = input("Enter Your Choice: ") if (x.isalpha() or not x in range(1,6)): return (x) return choosenAction() def createProject(chosenusr): data=NewProject(chosenusr) file=open("AllProjects.txt",'a') file.writelines(data) file.close() def viewproject(): file=op...
The code defines a menu-driven interface for project management, allowing users to create, view, edit, or delete projects, or exit the program. It prompts the user for an action, processes the input, and calls corresponding functions to execute the chosen task, ensuring proper navigation and termination of the program ...
def ProjectMenu(chosenusr): print("""choose your action from list: c) create project v) view all projects e) edit Your projects d) delete your own projects done) done with program""") choice = choosenAction() if (choice == "c"): ...
def find_left_bound(filter_frame: np.ndarray) -> int: """ Find the left bound of the frame in the image. """ return find_normal_bound(filter_frame, 1) def find_right_bound(filter_frame: np.ndarray) -> int: """ Find the right bound of the frame in the image. """ return find_reverse_bound(...
The function `find_frame_boundary_of_npimage_filter` identifies the frame boundary in a given numpy image array. It calculates the extreme coordinates (left, right, top, bottom) that define the non-overlapping edges of the frame. By calling four helper functions, it determines each boundary and returns them as a tuple....
def find_frame_boundary_of_npimage_filter(filter_frame: np.ndarray ) -> Tuple[float, float, float, float]: """ Returns a tuple of the coordinates of the frame boundary in the image. This boundary is defined as the most extreme coordinates in each corner that do ...
def get_indices(self): ''' :param y_pred: predicted target variable :return: indices of the positive and negative predictions ''' y_predictions = self.convert_scores_to_label() normal_idx, anomaly_idx = [], [] for i in range(len(y_predictions)): if y_p...
The function identifies threshold violations in reconstruction errors for each column by comparing anomaly values against a training-derived maximum threshold. It counts how many anomalies exceed this threshold and calculates the percentage of violations, returning a dictionary with counts and percentages for each colu...
def threshold_violations(self): ''' :param column_names: list of column names :param details: dictionary of details (reconstruction error, mean, std) :param normal_val_index: indices of normal values :return: dataframe with the threshold violations ''' normal_inde...
def _log(self, s): t = time.localtime() t_str = time.strftime("%a, %d %b %Y %H:%M:%S", t) with open(f'{self.log_dir_path}/ga.log', 'a+') as f: f.write(f'[{t_str}] {s}\n') print(s) def _init_models(self): self._log('Init models') self.pool = mp.Pool(mp.cpu_cou...
The `optimize` method executes one generation of a genetic algorithm (GA). It checks termination conditions, initializes models if needed, runs an evolutionary iteration (`_evolve_iter`), updates the generation count, saves progress, and logs results. It returns the generation's metrics (median, mean, max scores, etc.)...
def optimize(self): """ Runs a generation of the GA. The result is a tuple (median_score, mean_score, max_score, evaluation_used, scored_parents) :return: False if the optimization is ended, result otherwise """ if self.termination_strategy(): if self.model...
def _get_out_features(self): if self._tiling is not None: return self._tiling ret = 0 for name, param in self.pnn.named_parameters(): if 'weight' in name: layer_shape = param.shape layer_size = reduce((lambda x, y: x * y), layer_shape) ...
This code initializes a neural network module for a reinforcement learning agent, combining a policy network (pnn) with a hidden network (hnn) that processes latent variables. It sets up parameters for tiling, latent dimensions (z_dim), and initializes layers for feature transformation. The code prepares buffers for la...
def __init__(self, obs_space, action_space, pnn, tiling=64, shrink=1): super().__init__() self._tiling = tiling self.z_dim = int(32 * shrink) self.z_v_evolve_prob = 0.5 self.pnn = pnn(obs_space, action_space) self.pnn_modules = list(dict(self.pnn.named_children()).keys...
def set_recursive(self, recursive): if recursive is not None and recursive != self._recursive: self._recursive = recursive self._initiated = False def _init_if_needed(self): if not self._initiated: self._initiated = True self._get_dir_info(self._path) def ...
The code defines a `__repr__` method to generate a string representation of an object, summarizing its attributes: file path, directory/file counts, line statistics (code, comments, whitespace), and total size. It initializes necessary data, then formats these values into a readable string for debugging or display.
def __repr__(self, recursive=None): self.set_recursive(recursive) self._init_if_needed() return "%s (%s dirs, %s files, %s lines: %s code, %s comment, %s empty) %s" % ( self._path, self._dircount, self._filecount, self.get_line_count(), ...
def get_line_count(self): self._init_if_needed() return self._codelines + self._commentlines + self._whitespacelines def get_code_lines(self): self._init_if_needed() return self._codelines def get_comment_lines(self): self._init_if_needed() return self._commentlines def g...
This code defines the __repr__ method to return a formatted string summarizing a file's details: its name, total lines, code lines, comment lines, empty lines, and file size using ByteSize formatting.
def __repr__(self): return "%s (%s lines: %s code, %s comment, %s empty) %s" % ( self._filename, self.get_line_count(), self.get_code_lines(), self.get_comment_lines(), self.get_whitespace_lines(), ByteSize(self.get_filesize()).__repr__() ...
def previous_image_and_labels(self): """Switching to the previous image and label, saving if requested""" if not self.image_index <= 0: if self.save_on_change_checkbox.isChecked(): self.save_labels() self.image_index -= 1 self.image_index_spinbox.setVa...
This code handles keyboard events in a Qt-based application, triggering actions like navigating images (A/D), saving/copying/pasting labels (S/C/V), zooming (Plus/Underscore), and closing the window (Escape). It maps specific keys to corresponding methods for image and label manipulation, enhancing user interaction wit...
def keyPressEvent(self, event): match event.key(): case Qt.Key.Key_A: self.previous_image_and_labels() case Qt.Key.Key_D: self.next_image_and_labels() case Qt.Key.Key_S: self.save_labels() case Qt.Key.Key_C: ...
def detect_collisions(paths): ############################## # Task 3.1: Return a list of first collisions between all robot pairs. # A collision can be represented as dictionary that contains the id of the two robots, the vertex or edge # causing the collision, and the timestep at w...
The main task of the code is to solve a multi-agent pathfinding problem by iteratively finding collision-free paths for all agents from their start to goal locations. It uses A* for initial path generation, detects collisions, and applies constraint-based splitting (standard or disjoint) to resolve conflicts. The algor...
def find_solution(self, disjoint): """ Finds paths for all agents from their start locations to their goal locations disjoint - use disjoint splitting or not """ self.start_time = timer.time() # Generate the root node # constraints - list of constraints # ...
def get_signature(password): timestamp = str(int(time.time())) data = timestamp[:8] + password + timestamp[:8] hashed_data = hashlib.sha256(data.encode()).hexdigest() return hashed_data def client_send(client_socket, data: bytes) -> bool: try: data_length = len(data) header = data_le...
The code connects to a server using input or predefined host, port, and password, authenticates via a password-derived signature, and initiates messaging if authentication succeeds. It handles connection errors and validates server responses, closing the connection on failure.
def connect_to_server(): global in_host global in_port global in_password try: if not in_host: host = input("[?] Host > ") else: host = in_host if not in_port: port = int(input("[?] Port > ")) else: port = int(in_port) ...
def _save_reservation(request, form_values): try: (reservation, resources, reservation_error) = _assemble_reservation( request, form_values) (save_recurrences, remove_recurrences, recurrence_error) = \ _assemble_recurrences( request, form_values, reservation,...
The function handles reservation creation/editing by preparing form data, determining action URLs, and delegating to helper functions. It aggregates resources by tags, sets return URLs, and uses POST data or existing reservation IDs to either save new reservations or populate edit forms with existing data.
def create_or_edit_reservation(request, reservation_id=None): resources = models.Resource.objects.all() tag_resources = {} for resource in resources: for tag in resource.tags.all(): if tag.id not in tag_resources: tag_resources[tag.id] = [] tag_resources[tag.i...
def ends(self, s): length = len(s) if s[length - 1] != self.buffer[self.k]: # tiny speed-up return 0 if length > (self.k - self.k0 + 1): return 0 if self.buffer[self.k-length+1:self.k+1] != s: return 0 self.offset = self.k - length retu...
This code implements Step 1a and 1b of the Porter stemming algorithm. It processes word endings by removing suffixes like 'sses', 'ies', and 's' (Step 1a), then handles 'eed', 'ed', and 'ing' suffixes (Step 1b). It adjusts the word's ending based on vowel presence, consonant doubling, and specific replacement rules to ...
def step1ab(self): if self.buffer[self.k] == 's': if self.ends("sses"): self.k = self.k - 2 elif self.ends("ies"): self.setto("i") elif self.buffer[self.k - 1] != 's': self.k = self.k - 1 if self.ends("eed"): ...
def m(self): n = 0 i = self.k0 while 1: if i > self.offset: return n if not self.cons(i): break i = i + 1 i = i + 1 while 1: while 1: if i > self.offset: return n ...
The code adjusts the offset (self.offset) and modifies the index (self.k) based on specific character conditions. It checks if the character at self.k is 'e', then decrements self.k if 'm()' returns >1 or equals 1 with a non-vowel-consonant-vowel sequence at self.k-1. If the character is 'l', it further decrements self...
def step5(self): self.offset = self.k if self.buffer[self.k] == 'e': a = self.m() if a > 1 or (a == 1 and not self.cvc(self.k-1)): self.k = self.k - 1 if self.buffer[self.k] == 'l' and self.doublec(self.k) and self.m() > 1: self.k = self.k -1
def get_corpus(): global document_filenames, N # Fetch list of document names in corpus documents = glob.glob(CORPUS) # Set size of corpus N = len(documents) # Dictionary having doc id as key and document name as value document_filenames = dict(zip(range(N), documents)) def initialize_ter...
The main task of the code is to build an inverted index for a corpus by initializing terms, postings, document frequencies, and vector lengths. It enables continuous search functionality, retrieving ranked documents via `do_search()` and displaying results in a tabular format using `print_scores(scores)`, allowing iter...
def main(): # Get details about corpus get_corpus() # Initialise terms and postings for the corpus initialize_terms_and_postings() # Set document frequencies for all terms initialize_document_frequencies() # Set document vector lengths initialize_lengths() # Allow for search ...
def step1ab(self): if self.buffer[self.k] == 's': if self.ends("sses"): self.k = self.k - 2 elif self.ends("ies"): self.setto("i") elif self.buffer[self.k - 1] != 's': self.k = self.k - 1 if self.ends("eed"): ...
This function performs stemming on a word by applying a series of transformation steps (step1ab, step1c, step2–step5) to reduce it to its root form. It initializes buffer with input word `p`, sets indices `k0` and `k`, and returns the stemmed substring from `k0` to `k+1` after processing.
def stem(self, p, i, j): self.buffer = p self.k = j self.k0 = i if self.k <= self.k0 + 1: return self.buffer self.step1ab() self.step1c() self.step2() self.step3() self.step4() self.step5() return self.buffer[self.k0:se...
def getSettings(): settings = general.readJSON(SETTINGS_FILE) global currency global save_to_db global refreshtime currency = settings["currency"] save_to_db = settings["database"]["save_to_db"] refreshtime = settings["refreshtime"] def getItems(): global items items = general....
The code initializes settings and items, establishes a database connection if enabled, prepares the database with the items, and then starts a loop process, likely for processing or managing data operations in a continuous cycle.
def start(): getSettings() getItems() db = None if(save_to_db): db = dbHandler.createDBConnector() dbHandler.readyDB(items, db) loop(db)
def draw_info(self, env_info: dict): """ draws info headers at the top of the screen from the `env.get_info()` object """ # display name for dictionary keys name = { 'v_transit_start': 'Start', 'v_transit_end': 'End', 'v_transit_remaining': 'Remaining', 'v_has_package': 'Package', 'p_location_...
The main task of the code is to render the game environment's visual state by drawing the Vienna map, informational elements, locations, packages, and vehicles onto the screen using Pygame. It processes exit events, updates the display with new elements after each dispatch action, and ensures the screen reflects the cu...
def draw(self, env_info: dict): """ main drawing function, called after every dispatch action :param env_info: the info object returned from the environment step function """ for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() # draw image on the bottom of the canvas ...
def get_cost(self): return self.get_cv_metric(self.cv_folds, self.cost_type) def train(self, nfft=False): self.N = self.X.shape[0] X_sparse = self.X.dot(self.spectral_freqs) Phi_const = np.sqrt(self.kernel_scale/self.M) Phi = Phi_const*np.exp(-2j*np.pi*X_sparse) noise = s...
This function computes gradients of the cost function with respect to noise parameters, kernel scale, and frequency components using finite differences. It perturbs the real noise component, calculates cost changes, and combines gradients from three domains (noise, kernel scale, frequencies) into a concatenated array f...
def get_cost_grad(self): self.cur_cost = self.get_cost() self.noise_real -= self.grad_epsilon self.train() self.last_cost = self.get_cost() d_cost_d_noise = self.get_d_cost_d_noise() g11 = self.noise_real*d_cost_d_noise[0] g12 = self.noise_imag*d_cost_d_noise[1] ...
def load_regression(self, reg_meth='GomPlex'): model_path = self.get_regressor_path(reg_meth) if(reg_meth == 'GomPlex'): return GomPlex().load(model_path) def get_input_output_matrix_by_subjects(self, subjects): input_mat, output_mat = None, None for subject in subjects: ...
The code evaluates a regression model's performance in classifying subjects as CI (cognitive impairment) or NCI (non-cognitive impairment) using probabilistic predictions adjusted for age, gender, and education level. It computes metrics like accuracy, precision, recall, specificity, F1-score, and AUC, while comparing ...
def eval_model_for_subjects(self, model=None, n_trains=100, reg_meth='GomPlex'): echo_message = False if(model is None): echo_message = True model = self.load_regression(reg_meth) subjects = self.df_drawing_data.index cfs_mat = np.zeros((2, 2)) cis, pred_c...
def load_regression(self, reg_meth='GomPlex'): model_path = self.get_regressor_path(reg_meth) if(reg_meth == 'GomPlex'): return GomPlex().load(model_path) def get_input_output_matrix_by_subjects(self, subjects): input_mat, output_mat = None, None for subject in subjects: ...
This function evaluates a regression model's performance on subgroups (CI vs. NCI) by training on random samples, predicting class probabilities with adjustments for age, gender, and education, and computing metrics like accuracy, F1, AUC, and confusion matrices to assess classification effectiveness.
def eval_model_for_subgroups(self, model=None, n_trains=100, reg_meth='GomPlex'): echo_message = False if(model is None): echo_message = True model = self.load_regression(reg_meth) subjects = self.df_drawing_data.index cfs_mat = np.zeros((2, 2)) cis, pred_...
def get_train_test_data(self, ratio): subjects_train, subjects_test = self.get_subjects_for_train_test(ratio) X_train, y_train = self.get_input_output_matrix_by_subjects(subjects_train) X_test, y_test = self.get_input_output_matrix_by_subjects(subjects_test) return X_train, y_train, X_te...
This function trains a regression model using either the GomPlex algorithm or a Multi-Layer Perceptron (MLP). For GomPlex, it preprocesses data, trains the model with cross-validation, evaluates performance, and saves the best model if it outperforms existing ones. For MLP, it imports Keras components to build and vali...
def train_regressor(self, reg_meth='GomPlex', iter_tol=30, ratio=0.3, cv_folds=3, score_rerun=20, plot_error=False): if(reg_meth == 'GomPlex'): # Default Regression Method - GomPlex print('# Preprocessing Raw Drawing Data') X_train, y_train, X_test, y_test = self.get_...
def get_event_types(): return get_events().keys() def get_subscription_body(user_id, event_name): event_info = get_events(event_name) return { "type": f"{event_name}", "version": "1", "condition": { f"{event_info['type']}": f"{user_id}" }, "transport": { ...
The function subscribes a user to all available Twitch event types by iterating through each event, generating a subscription request body, and sending a POST request to Twitch's eventsub endpoint for each event.
def subscribe_user(user_id): for event in get_event_types(): body = get_subscription_body(user_id, event) send_twitch_request(endpoint=eventsub_endpoint, method="POST", body=body)
def load_posting_list(postings_file, offset): postings = open(postings_file, 'r') postings.seek(0) posting_list = [] try: postings.seek(offset) posting_string_list = postings.readline().rstrip("\n").split(" ")[1:] # get posting list for term for values in posting_string_list: ...
The function evaluates a boolean query on a document collection using inverted indexes. It tokenizes and stems the query, processes operators (AND, OR, NOT), handles nested subqueries with parentheses, and combines posting lists via intersection/union operations. The result is a tuple of document IDs matching the query...
def evaluate_query(query, doc_ids, dictionary, postings_file): stemmer = PorterStemmer() tokens = word_tokenize(query) tokens = [stemmer.stem(token.lower()) for token in tokens] final_result = [] # Base cases # A if (len(tokens) == 1): if tokens[0] in dictionary: final_...
def load_dict(dict_file): dictionary = {} memory_dict = open(dict_file, 'r') file_content = memory_dict.read() # breaks the content into [content, "\n"] dict_text_list = file_content.split("\n")[:-1] for item in dict_text_list: token, posting_offset = item.split(" ") diction...
The code performs search operations using a dictionary and postings file to process queries from an input file, retrieving relevant document IDs. It loads the dictionary, reads queries, evaluates each using `evaluate_query`, collects results, formats them as strings, and writes them to a results file. The main task is ...
def run_search(dict_file, postings_file, queries_file, results_file): """ using the given dictionary file and postings file, perform searching on the given queries file and output the results to a file """ print('retrieving the dictionary...') dictionary = load_dict(dict_file) doc_ids = load...
def setup_folders(self,dataset_name,exmpls_per_class): # Make training directory train_path = join(TRAIN_DIR,dataset_name) if not os.path.isdir(train_path): makedirs(train_path) out_dir_name = "%d_exmpls_" % exmpls_per_class if self.ae: out_dir_name += "ae...
This function performs semi-supervised training on a model using both labeled (supervised) and unlabeled (unsupervised) data. It initializes training parameters, splits data into supervised/unsupervised subsets, iterates over epochs to train with multiple loss components (e.g., prototype, AE, silhouette), tracks metric...
def train_semi_sup(self, epochs=200,start_at=0,pct_for_query=0.5,exmpls_per_class=15,seed=None,proto=True,ae=True,silh=False,db=False,hubert=False,dataset_name=None,update_eoe=False,filt_width=None): self.proto = proto self.ae = ae self.silh = silh self.db = db self.seed = seed ...
def debug_print(fmt): if DEBUG_MODE: print(fmt) def tunnel(client_conn, http_request): # Handle checking blocked list request_status = REQUEST_NONE with blocked_lock: if http_request.url in blocked_urls: request_status = REQUEST_BLOCKED with requests_lock: debug_...
The main task of the code is to handle incoming network connections by parsing HTTP requests. It checks if the request is HTTPS, then either establishes a tunnel or relays the connection based on the protocol. Debug logs track the process, including connection receipt, packet parsing, and protocol determination.
def handle_connection(data, conn): if data: debug_print(f"-------------------------------------------------------") debug_print(f"[-] Received connection - parsing packet") # Parse HTTP packet http_request = HTTPRequest(data) if not http_request.connectit: return...
def crawl_files(URL, response : requests.Response): responseText = response.text regexp1 = '(?<=src=")(\/[^\/].+?)(?=")' regexp2 = '(?<=href=")(\/[^\/].+?)(?=")' filesURL = re.findall(regexp1, responseText) filesURL += re.findall(regexp2, responseText) selectedFiles = [] #Select two rando...
The code crawls a given URL, collects related URLs, and scans each for potential security issues. It checks for port poisoning and headers poisoning vulnerabilities by making HTTP requests and analyzing responses. The main task is to identify and flag malicious or insecure configurations in web resources during automat...
def crawl_and_scan(url, initialResponse): selectedURLS = crawl_files(url, initialResponse) for url in selectedURLS: potential_verbose_message("CRAWLING", args, url) initResponse = base_request(url) port_poisoning_check(url, initResponse) headers_poisoning_check(url, initResponse)
def base_request(url): randNum = str(random.randrange(9999999999999)) buster = str(random.randrange(9999999999999)) try: response = requests.get(f"{url}?cacheBusterX{randNum}={buster}", allow_redirects=False, timeout=TIMEOUT_DELAY) except: return None return response def port_poison...
The function checks for cache poisoning vulnerabilities by analyzing HTTP responses. It first requests a URL, verifies the status code, then checks for port and header poisoning. If either check is inconclusive ("UNCONFIRMED"), it initiates further scanning via crawling. The core task is identifying potential cache poi...
def cache_poisoning_check(url): initialResponse = base_request(url) if not initialResponse: potential_verbose_message("ERROR", args, url) return if initialResponse.status_code in (200, 304, 302, 301, 401, 402, 403): resultPort = port_poisoning_check(url, initialResponse) res...
def cache_poisoning_check(url): initialResponse = base_request(url) if not initialResponse: potential_verbose_message("ERROR", args, url) return if initialResponse.status_code in (200, 304, 302, 301, 401, 402, 403): resultPort = port_poisoning_check(url, initialResponse) res...
This code performs cache poisoning checks on URLs provided via a single URL argument or a file. If a URL is specified, it checks it directly. If a file is provided, it processes all URLs in the file, using multithreading for parallel checks when specified, splitting URLs into thread-specific lists and managing concurre...
def main(): if args.url: try: cache_poisoning_check(args.url) except: print("\nInvalid URL") elif args.file: if not args.threads or args.threads == 1: sequential_cache_poisoning_check(allURLs) else: workingThreads = [] ...
def folder_path_to_title(folder_path:Path) -> str: return folder_path.name.replace("_", " ").replace("-", " ").capitalize() def run_test_case(test_case_folder_path:Path, evaluation_folder:Path, build_path:Path, is_dummy:bool=False) -> Counter: res = Counter() test_case_name = {"description": f"##### {folde...
This function executes test cases and hidden tests within specified directories, aggregating results in a Counter. It checks for subfolders, runs test cases in non-hidden directories first, then processes hidden tests separately. The 'is_dummy' flag controls context setup, while paths define test locations and build se...
def create_context(context_folder:Path, evaluation_folder:Path, build_path:Path, is_dummy:bool=False) -> Counter: res = Counter() if not is_dummy: context_name = folder_path_to_title(context_folder) ctx_kwargs = { "description":{ "description": f"#### {context_name}"...
def fade_effect(): """ This function adds a fade-out effect when a song gets change """ if pygame.mixer.music.get_busy(): # Stop the currently playing song pygame.mixer.music.fadeout(200) # Fade out the song over 1 second # Wait for the fade-out effect to complete before loadin...
The main task of the code is to play a selected song from a listbox by loading the audio file, handling play/pause toggling, updating UI elements (like song name and button states), and managing song selection highlighting. It also includes error handling for missing files and fallback to random song playback if the se...
def play_song(option): """ Play selected song in listbox """ global data, last_played_song, is_playing, current_position, selected_song file_path = data["folder_path"] try: if file_path != "": if option in existing_songs: full_song_path = os.path.join(file_p...
def fade_effect(): """Return's a fade out effect on songs when they change""" if pygame.mixer.music.get_busy(): # Stop the currently playing song pygame.mixer.music.fadeout(200) # Fade out the song over 1 second # Wait for the fade-out effect to complete before loading and playing the ...
The code plays a selected song using pygame mixer, handling pause/resume functionality, updating UI elements (labels, buttons, listbox), and applying fade effects. It checks if the song exists in the folder, initializes the mixer if needed, and toggles playback state. If the song is new, it updates the position bar, hi...
def play_song(selected_option): """Play the song""" global folder_path, selected_song, last_played_song if folder_path: # Check if selected_option is None or empty if selected_option in existing_songs: # Retrieve the full song path based on the selected option full_s...
def get_file_path(directory): # Returns the file path of all files in the directory file_paths = [] for root, dirs, files in os.walk(directory): for file in files: filepath = os.path.join(root, file) file_paths.append(filepath) return file_paths def open_file(filePath): ...
The main task of the code is to evaluate and compare the performance of three SAT-solving algorithms—DPLL, WalkSAT, and GSAT—on hard CNF formulas. It processes each formula file, runs DPLL once and the other two algorithms 10 times with varying parameters, measures execution time, and prints results including satisfiab...
def main(): # files = get_file_path('./CNF Formulas') files = get_file_path('./HARD CNF Formulas') # with open("SAT_Output.txt", "w") as f: # with open("SAT_Hard_Output.txt", "w") as f: for file in files: clauses = open_file(file) print(file) # f.write(file + '\n') ...
def train_imdb(): (train_dataset, test_dataset, encoder) = get_imdb_data() validation_dataset = test_dataset model = LSTM_Model(encoder) model.model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.Adam(1e-4), metrics=['accuracy']) ...
The main task of the code is to execute different training functions based on the 'type' argument in 'args'. If the type is "imdb", it runs `train_imdb()`; if "twitter", it runs `train_twitter()`; and if "sarcasm", it runs `train_sarcasm()`. The function acts as a dispatcher to select the appropriate training script fo...
def main(args): if args.type == "imdb": train_imdb() elif args.type == "twitter": train_twitter() elif args.type == "sarcasm": train_sarcasm()
def selectUser(): c.execute("SELECT USER FROM LOGGINDATA") def usersList(): selectUser() userinlist = [] for queryresult in c.fetchall(): userinlist.append(queryresult) userinlist = flatit(userinlist) return userinlist def passwordList(): selectPassword() passwordinlist = [] ...
The code validates user registration inputs by checking if the username already exists, ensuring no spaces in fields, and confirming both fields are filled. If valid, it proceeds to register the user with the provided credentials.
def register_attempt(): selectUser() userentryvalue = str(usersv.get()) # userentryvalue = str(userentryvalue) passwordentryvalue = str(passwordsv.get()) # passwordentryvalue = str(passwordentryvalue) print(userentryvalue, passwordentryvalue) userinlist = usersLis...
def general_method(k, denominator, given): letter = None if denominator == 4: letter = 'Q' elif denominator == 10: letter = 'D' else: letter = 'P' print('-'*50) print('GENERAL METHOD') first_answer = (k * len(given)) / denominator print(f'\n{letter}{k} = kn / {...
The code presents a menu to select a statistical method (General, Mendenhall-Sinchich, Linear Interpolation, or All) and executes the chosen method(s) using input parameters `k`, `denominator`, and `given`. It calls corresponding functions based on user input, with option 'd' triggering all three methods. The task invo...
def solve(k, denominator, given): print('\nSelect method:') method_chosen = input('[a] General Method \n[b] Mendenhall and Sinchich Method \n[c] Linear Interpolation Method\n[d] All \n> ').lower() if method_chosen == 'a': general_method(k, denominator, given) elif method_chosen == 'b': ...
def debug(self,msg): if self.show_debug: print(msg) def show_status(self): self.debug(sys._getframe().f_code.co_name) if self.yam: ys = self.yam.get_status() # print(ys) if 'power' in ys: if ys['power'] == 'on': ...
This code initializes a Qt-based GUI application for a Yamaha Receiver interface, setting up the main window with title, version, and copyright info. It configures screen settings, window style, frameless display, central widgets, and toolbars. A timer is started to periodically reset the UI frame, while status and pla...
def __init__(self): self.app = qtw.QApplication(sys.argv) qtw.QMainWindow.__init__(self) self.title = "Yamaha Receiver" self.description = "Yamaha Receiver Interface" self.version_str = "0.7.3" self.copyright_str = "(c) copyright 2024, Matthew Grund" self.setObj...
def add_normal_toolbar_button(self,group_name,item_name,icon_file): # print(f"Adding '{group_name}'::'{item_name}'") i = self.normal_icon(self.icon_path + icon_file) a = qtg.QAction(i, item_name.title(), self) a.triggered.connect(lambda : self.toolbar_callback(group_name,item_name)) ...
The code initializes a right-side toolbar in a GUI application, setting up buttons for audio units (Yamaha amplifiers) based on IP addresses. It configures toolbar appearance, adds unit-specific buttons with network status labels, and initializes device handles. The toolbar displays unit information, enables selection,...
def __init__(self, q_main_window): super().__init__(q_main_window) self.q_main_window = q_main_window self.setStyleSheet(self.q_main_window.styleSheet()) self.setIconSize(qtc.QSize(48,48)) self.setObjectName("Right Toolbar") self.setMinimumWidth(96) self.setMovabl...
def add_toolbar_spacer(self): self.q_main_window.debug(sys._getframe().f_code.co_name) spacer = yamstyle.styled_spacer(self.q_main_window) self.addWidget(spacer) def add_normal_toolbar_button(self,group_name,item_name,icon_file): self.q_main_window.debug(sys._getframe().f_code.co_name) ...
The code initializes a bottom toolbar with media playback and help controls, setting UI properties like size, style, and button layout. It adds buttons for play/pause, media navigation, and help, configuring active/normal states and spacing for a structured interface.
def __init__(self, q_main_window): super().__init__(q_main_window) self.q_main_window = q_main_window self.q_main_window.debug(sys._getframe().f_code.co_name) self.setStyleSheet(self.q_main_window.styleSheet()) self.setIconSize(qtc.QSize(42,42)) self.setMinimumHeight(56) ...
def back(prev_frame, curr_frame, staff_logged_out=False): if staff_logged_out: confirm = messagebox.askyesno(title="Logout Confirmation!", message="Are you sure you want to logout?") if not confirm: return if curr_frame == home_frame: curr_frame.place_forget() else: ...
The code creates a tabbed interface for managing entities like User, Staff, or Machine. It generates a GUI with a header, search bar, Treeview for displaying data, and CRUD buttons. The layout dynamically adjusts based on the entity type, with specific columns, button commands, and logout positioning.
def create_tab(nb, heading, lbl_id, curr_frame): obj_dict = {"User": user, "Staff": staff, "Machine": machine} obj_id = heading.split(' ')[0] obj = obj_dict[obj_id] frame = ttk.Frame(nb) frame.pack(fill=BOTH, expand=1, anchor=CENTER) header_frame = ttk.Frame(frame) header_frame.pack(fill=...
def user_logged_in(curr_frame, vals): email = vals[0].get() passwd = vals[1].get() try: if email == "" or passwd == "": raise EmptyFieldError("Empty Credentials") # check email-id email_regex = re.compile(r'^[a-z0-9]+[._]?[a-z0-9]+[@]\w+[.]\w{2,3}$') match = ema...
The code creates a login interface with a welcome message, email/password fields, toggle password visibility buttons, and action buttons (Login, Clear, Back). It switches to this frame from the current one, handles user input, and prepares for login validation or navigation.
def user_log_in(curr_frame): curr_frame.pack_forget() global log_in_frame log_in_frame = ttk.Frame(root) log_in_frame.pack(fill=BOTH, expand=1) # top frame top_frame = ttk.Frame(log_in_frame) top_frame.pack(padx=10, pady=10) welcome_lbl = ttk.Label(top_frame, text="Log-In!", font="Helv...
def staff_logged_in(curr_frame, vals): email = vals[0].get() passwd = vals[1].get() try: if email == "" or passwd == "": raise EmptyFieldError("Empty Credentials") # check email-id email_regex = re.compile(r'^[a-z0-9]+[._]?[a-z0-9]+[@]\w+[.]\w{2,3}$') match = em...
This code creates a staff login interface with email/password fields, password toggle, login functionality, and navigation controls. It replaces the current frame with a new login frame containing labels, entry fields, buttons, and event bindings for user authentication and interface navigation.
def staff_log_in(curr_frame): curr_frame.pack_forget() global staff_login_frame staff_login_frame = ttk.Frame(root) staff_login_frame.pack(fill=BOTH, expand=1) title_lbl = ttk.Label(staff_login_frame, text="Sign-In!", font="Helvetica 30 bold italic") title_lbl.pack(padx=20, pady=20) temp_f...
def wpaNetworksChange(action: bool = True) -> None: out = _exec_wait(['wpa_cli', '-i', 'wlan0', 'list_network']) if out == False: raise Exception('Unable to get networks list') for line in out.splitlines()[1:]: data = line.split() if len(data) == 4 and ((b'DISABLED' if action else b'...
The function `runCaptivePortal` sets up a captive portal Wi-Fi hotspot using `hostapd` on `wlan0`, configures a DHCP server with `dnsmasq`, and launches a captive portal web server. It monitors these processes, logs errors if they terminate, and triggers a reboot after 30 seconds if all services stop. The task involves...
def runCaptivePortal() -> None: dnsmasq = None hostapd = None captive = None try: wpaNetworksChange(False) if _exec_wait(['sudo', 'ip', 'link', 'set', 'dev', 'wlan0', 'down']) == False: raise Exception('Unable to shutdown the wlan0 interface') if _exec_wait(['sudo'...
def send_index(self, notification, color = "ff6666"): self.send_response(200) self.send_header("Content-Type", "text/html") self.end_headers() self.wfile.write((index % ( html.escape(color, True), html.escape(notification), html.escape("'"+"', '".join(...
This code handles a POST request to configure WiFi settings. It validates the content type and size, parses form data for SSID and password, checks if SSID is non-empty, applies the configuration using wpaCreateConfig, and reboots the system upon successful save.
def do_POST(self): ctype, pdict = parse_header(self.headers.get("Content-Type")) if ctype != "application/x-www-form-urlencoded": self.send_index("ERROR: Incorrect content type") return length = int(self.headers.get("Content-Length")) if length > 10240: ...
def join(self, group: Group, new_user: socket.socket, username: str): actual_username = username clone = 1 while group.users.get(username): actual_username = username + "({0})".format(clone) clone += 1 group.users[new_user] = actual_username for...
This function processes client commands in a group chat application. It parses commands starting with '%', executes actions like joining/leaving groups, posting messages, listing users, and sending messages. It handles both public and private groups, extracts parameters using regex, and invokes corresponding methods wi...
def _process_command(self, client: socket.socket, input: str) -> None: if(input.startswith('%')): commands = input.split(" ", maxsplit=1) match commands[0][1:]: #Removes %, code was ugly otherwise #case 'connect': #self.connect(self, comman...
def forward_check(self, variable: Variable, assignments: Dict[Variable, Domain], domains: Dict[Variable, List[Domain]]): # For every unassigned neighbor to this variable for neighbor in self.get_unassigned_neighbors(assignments, variable): domains_to_delete: List[Domain] = [] #...
The main task of the code is to solve a constraint satisfaction problem (CSP) by performing backtracking search with optional preprocessing via forward checking and AC3. It initializes domains, applies consistency checks, executes backtracking search, verifies constraint satisfaction, and returns the valid assignment o...
def solve(self) -> Optional[Dict[Variable, Domain]]: if self.forward: # Do a preliminary forward for all initial assignments for variable in self.initial_assignments: self.forward_check(variable, self.initial_assignments, self.initial_domains) if self.ac3: ...
def create_cust_tables(): cnx = mysql.connector.connect(user='****', password='*********', host='127.0.0.1', database='onlinefoodorderingdb', auth_plugin='mysql_native_password') cursor = cnx.cursor() cursor.execute("DROP TABLE IF EXISTS CUSTOMER_MASKED_DATA") sql ='...
The main task of the code is to create customer and employee database tables, insert sample data into them, and execute SELECT queries to retrieve and display data from both tables. The function sequentially initializes database structure, populates it with data, and demonstrates querying operations for employee and cu...
def main(): create_cust_tables() create_emp_tables() insert_data() select_emp_query() select_cust_query()
def seperateItems(sku): items = [] p=0 for i in sku: validAlpha = i.isalpha() and (getPrice(i) != 0) if(not validAlpha and not i.isnumeric()): return [] for i,l in enumerate(sku): if(l.isalpha()): items.append(sku[p:(i+1)]) p = i+1 un...
The main task of the code is to calculate the total price of items in a shopping basket, applying specific discount rules. It processes a string of SKUs, separates them into individual items, calculates base prices, and applies discounts for 'E' items (which reduce 'B' item costs). The function returns the total price ...
def checkout(skus): if(skus): lengthOfSku = len(skus) if(lengthOfSku == 0): return -1 price = 0 items = seperateItems(skus) if(len(items) == 0): return -1 for item in items: storeItem = item[-1] itemPrice = getPr...
def __standardizef(fitinfo, offset=None, scale=None): r'''Standardizes f by creating offset, scale and fs. When appropriate, imputes values for `f`.''' # Extracting from input dictionary f = fitinfo['f'] mof = fitinfo['mof'] mofrows = fitinfo['mofrows'] epsilonPC = fitinfo['epsilonPC'] ...
The function `fit` performs a modified PCGP (Principal Component Gaussian Process) method to emulate responses in a dataset, handling missing values through imputation. It standardizes input data, extracts principal components (PCs) based on variance thresholds, and fits Gaussian Process (GP) emulators for each PC. The...
def fit(fitinfo, x, theta, f, epsilonPC=0.001, epsilonImpute=10e-6, lognugmean=-10, lognugLB=-20, varconstant=None, dampalpha=0.3, eta=10, simsd=None, numpcs = -1, standardpcinfo=None, verbose=0, **kwargs): ''' The purpose of fit is to take information and plug all of our fit informa...
def start_conv(update, context, vk_chat_id): uid = update.effective_user.id chat_id = update.effective_chat.id try: if vk_chat_id >= 2000000000: execute(f"insert into chats (chat_id, uid, peer_id) values ({chat_id}, {uid}, {vk_chat_id})") else: execute(f"insert into ...
This code handles Telegram callback queries for a bot, managing user interactions with VK chat streams. It processes three scenarios: binding a VK chat to a Telegram group (via CONV data), navigating to the next/previous page of conversations (via next_page/prev_page data), or handling unknown callbacks. The function e...
def callback(update, context): query = update.callback_query data = query.data if str(CONV) in data: # User binding vk chat stream to telegram group conv = data[len(str(CONV)):] start_conv(update, context, int(conv)) elif 'next_page' in data: data = data.split(",")[1:] ...
def gather_positions(tree): """Makes a list of positions and position commands from the tree""" pos = { "data-x": "r0", "data-y": "r0", "data-z": "r0", "data-rotate-x": "r0", "data-rotate-y": "r0", "data-rotate-z": "r0", "data-scale": "r0", "is_pat...
The main task of the code is to position slides within a tree structure by gathering initial positions, calculating adjusted positions through a processing step, and then updating the tree's layout with the computed positions to organize or arrange the slides effectively.
def position_slides(tree): """Position the slides in the tree""" positions = gather_positions(tree) positions = calculate_positions(positions) update_positions(tree, positions)
def get_keybind_data(self): # As the method suggests, it gets the necessary keybinds based from the toggled preset self.keybinds_class = mapping.Keybinds() self.presets_class = mapping.Presets() presets_dict = self.presets_class.get() self.controls_data = self.keybinds_class.ret...
The function updates keybinding configurations by retrieving new data, populating a mapping list with keybinds and presets, binding these to controls, and enabling controls if activated.
def update_keybind_data(self): # Gets new keybind data and binds it to controls data = self.get_keybind_data() self.populate_mapping_list(keybinds=data[0], preset=data[1]) self.bind_keybinds_to_controls() if self.enable: self.enable_controls()
def transitive_closure(ml, cl, n): ml_graph = dict() cl_graph = dict() for i in range(n): ml_graph[i] = set() cl_graph[i] = set() def add_both(d, i, j): d[i].add(j) d[j].add(i) for (i, j) in ml: add_both(ml_graph, i, j) def dfs(i, graph, visited, compon...
This function performs K-means clustering with constraint handling. It initializes centroids, iteratively assigns data points to clusters while respecting constraints (ml, cl), computes new centroids, and stops when centroid shifts fall below tolerance. Returns cluster assignments and centroids if convergence is achiev...
def cop_kmeans(dataset, k,B, ml=[], cl=[], initialization='kmpp', max_iter=300, tol=1e-4): ml, cl = transitive_closure(ml, cl, len(dataset)) ml_info = get_ml_info(ml, dataset,B) tol = tolerance(tol, dataset) centers = initialize_centers(dataset, k, initialization,B) ...
def diff_data_process(data): n, p = data.shape diff_data = [data[0,:] - data[1,:]] for i in np.arange(1,int(n/2),1): diff_data = np.r_[diff_data, [data[2*i,:] - data[2*i + 1,:]]] return diff_data def metric_learning(diff_data, diag = True): n, p = diff_data.shape if diag == True: ...
The function `cop_kmeans_metric_learning` performs metric learning on a dataset to enhance clustering. If `learn=True`, it computes a metric matrix `B` using differences in the data and a diagonal constraint. It then applies constraint-based cop-kmeans clustering (with `k=2`), incorporating `B` and derived constraints ...
def cop_kmeans_metric_learning(dataset, learn = True, diag = True): n, p = dataset.shape if learn == False: B = np.identity(p) else: diff_data = diff_data_process(dataset) B = metric_learning(diff_data, diag = diag) cannot_link = link_constraint(dataset) clusters, center...
def enhanceView(self): if not self.enhancedView: # squaring to maxize face contrast print("Enhancing View Image") self.getROI() img = self.cam.view.copy() C= 25 f = (131 * (C + 127)) / (127 * (131 - C)) g = 127 * (1 - f) ...
The main task of the code is to detect and refine vertices from faces in an image. It enhances the view, identifies faces, applies dilation and clustering to locate vertices, filters invalid faces, reduces redundant points globally, and saves the result with vertices marked. The process ensures accurate vertex detectio...
def findFeatures(self): # ret, thresh = cv2.threshold(self.cam.view, 127, 255, 0) # self.cam.view = cv2.Canny(self.cam.view, 50, 255) # self.cam.view = cv2.dilate(self.cam.view, kernel=np.ones((3,3), np.float32)) # self.cam.view = cv2.medianBlur(self.cam.view, 7) # contours, hier...
def processCameraView(self, debug=False): path = "views/robot" + str(self.objNo) + "_" + str(self.pairNo) + "_view" + str(self.viewCount) + ".png" viewExists = os.path.exists(path) print("View Exists: " + str(viewExists)) if (not debug) or (not viewExists): print("Acquiring...
The code calculates 3D positions of detected vertices from two camera views by aligning corresponding points via optical flow and camera movement. It adjusts face counts, correlates vertices with faces, and triangulates 3D coordinates using camera parameters and displacement. The result includes 3D points, vertex pairs...
def calcViewFeatures(self, dbgTkn=0, debug=False): # we want to move the camera some horizontal offset. The math here is that for small theta, sin(theta)=theta # The distance moved will be R*theta then, and if the movement is small enough we can approximate this as # purely horizontal pr...
def processCameraView(self, debug=False): path = "views/robot" + str(self.objNo) + "_" + str(self.pairNo) + "_view" + str(self.viewCount) + ".png" viewExists = os.path.exists(path) print("View Exists: " + str(viewExists)) if (not debug) or (not viewExists): print("Acquiring...
The main task of the code is to estimate and compute 3D geometric features (vertices, faces) from a camera view, using an optimal radius. It processes camera data, calculates view features, and adds computed geometry (faces) to a polygon structure for visualization or further analysis. Debugging is optional.
def estimateTrueViewFeatures(self, debug=False): pts = [] self.processCameraView(debug=debug) self.set_radius(self.getOptimalRadius()) ps, vertPairs, FACES, FCP = self.calcViewFeatures('2.6', debug=debug) pts.extend(ps) color = np.array([1,1,1]) self.poly.addF...
def print_board(board): print(board[0:3]) print(board[3:6]) print(board[6:9]) print() def evaluate(board): winner = None # declare a string for determining whether there is a winner # loops for player in ['X', 'O']: if any(all(board[i] == player for i in row) for row in [ ...
The code implements a tic-tac-toe game where a human player competes against a computer. The human inputs moves (0-8) to place 'X' on the board, while the computer automatically places 'O' using a predefined strategy. The game checks after each move for a win or draw, printing the board state and declaring "Game over!"...
def play_game(): print("game board") board = ['-' for i in range(9)] print_board(board) while True: human_move = int(input("Enter your move (0-8): ")) if board[human_move] == '-': board[human_move] = 'X' print_board(board) if evaluate(board) is not Non...
def tree_copy(src, dst): src_path = generic_parse_path(src) dst_path = generic_parse_path(dst) e = Engine() e.generic_copy_tree(src_path, dst_path, sync=False) def _is_s3(path): return path.startswith('s3://') def tree_rm(src): src_path = generic_parse_path(src) e = Engine() e.generic_...
The function `tree_move` copies the directory tree from `src` to `dst`, then deletes the original `src` directory. If `src` is an S3 bucket, it uses `tree_rm` for removal; otherwise, it uses `shutil.rmtree` to delete the local directory. The main task is to move a directory tree by copying it and safely removing the so...
def tree_move(src, dst): tree_copy(src, dst) if _is_s3(src): tree_rm(src) else: shutil.rmtree(src)
def reset (self): self.calculations_submitted = 0 self.results_collected = 0 self.results = [] self.futures = [] def setup_signals (self, **kwa): signal.signal (signal.SIGINT, self.handler_sigint) if kwa.get ('timeout'): signal.sign...
The main task of the code is to initialize a logging system and configure a Dask distributed computing cluster. It sets up a logger with configurable log levels, creates a local cluster with specified worker and thread parameters, connects to it via a client, and prepares the system for parallel processing. The code al...
def __init__ (self, **kwa): cfg = kwa.get ('cfg') loglevel = dict ( debug = logging.DEBUG, info = logging.INFO, warn = logging.WARN, error = logging.ERROR, ).get ( cfg.get ('loglevel'), logging.INFO, ) se...
def check_te_cache(self): """ Query (for te) the file (before upload) in order to find whether file results already exist in TE cache. :return the query response """ self.set_file_sha1() request = copy.deepcopy(self.request_template) request['request'][0]['feature...
The code handles file analysis by checking a TE cache for existing results. If found, it uses cached data; otherwise, it uploads the file, queries it, and processes the response. Based on the verdict (Malicious/Benign), it moves the file to quarantine or benign directories, downloads reports if malicious, and generates...
def handle_file(self): """ (Function description is within above class description) """ query_cache_response = self.check_te_cache() cache_status_label = query_cache_response['response'][0]['status']['label'] if cache_status_label == "FOUND": self.print("Resul...
def feed_forward(self): self.layer1 = sigmoid(np.dot(self.input, self.weights1)+self.biases1) self.layer2 = sigmoid(np.dot(self.layer1, self.weights2) + self.biases2) self.output = sigmoid(np.dot(self.layer2, self.weights3)+self.biases3) def get_cost(self, label): self.expected = np.zero...
The main task of the code is to process input data through a neural network by normalizing the input, performing a feed-forward pass, calculating cost (if not in test mode), and executing backpropagation. It returns the predicted class label based on the maximum output value. Additionally, it conditionally saves result...
def get_output(self, input1, label, test=False, saveScores=False): input1 = input1.flatten() self.input = input1/255 self.feed_forward() if not test: self.sumCost += self.get_cost(label) self.full_back_prop() if saveScores: self.save() ...
def generateSettingsFrame(self, dic): ret = pmc.frameLayout(**self.settingsFrames) with ret: self.executeToggles.append(pmc.checkBox(label = dic.capitalize(), cc = lambda x: self.toggleActive(), v = self.bs.input[dic]['execute'])) self.temp = frameLayout(label=dic + "Frame") ...
This code creates a UI window for a rigging tool, deleting any existing instance. It sets up layouts with buttons to generate guides, mirror them, create rigs, and auto-rig, organizing controls into frames for user interaction. The interface enables users to configure rig parameters and execute rigging workflows throug...
def create( self ): if pmc.window( self.windowName, exists=True ): pmc.deleteUI( self.windowName, uiTemplate=True, window=True ) template = uiTemplate(self.windowName, force=True) template.define(frameLayout, borderVisible=False, labelVisible=False) template.define(colum...
def view_details_button_clicked(self, ) -> None: status, filename, _ = self.is_csv_data_provided() if not status: return row_count = 0 with pd.read_csv(filename, chunksize=200) as reader: for chunk in reader: row_count += len(chunk.index) ...
This code defines a main loop for a GUI application, continuously reading user events from a window. It processes events like button clicks (e.g., viewing details, applying changes, deleting columns, splitting CSV) by calling corresponding methods. The loop exits when the window is closed, then closes the window. The p...
def main_loop(self, ) -> None: while True: event, self.values = self.window.read() if event == sg.WIN_CLOSED: break elif event == KEY_VIEW_DETAILS: self.view_details_button_clicked() elif event == KEY_APPLY_CHANGES: ...
def fetch_uploaded_tracks(gpm, cursor, logger): uploaded_tracks = gpm.get_all_songs() current_album_id = None last_album_id = None last_artist_ids = None i_track = 0 for pltrack in uploaded_tracks: i_track += 1 if ((i_track - 1) % 50 == 0) or (i_track == len(uploaded_tracks)): ...
The main task of the code is to synchronize Google Play Music (GPM) playlist data with a MySQL database. It parses command-line arguments, configures logging, connects to a database, updates records to mark them as unprocessed, fetches uploaded tracks and playlist entries via GPM's API, and marks unprocessed entries as...
def main(): parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="Increase output verbosity", action="store_true") parser.add_argument("-l", "--listId", help="Playlist ID", nargs=1) args = parser.parse_args() logger = logging.getLogger("app") logger.setLevel(logging.DE...
def init_log(logpath: str, args): logger = logging.getLogger("app") logger.setLevel(logging.DEBUG) log_formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") log_hnd_screen = logging.StreamHandler(stream=sys.stdout) log_hnd_screen.setLevel(logging.ERROR) if args.verbose: ...
The main task of the code is to reset processing flags in a database, fetch YouTube Music playlist data (either all playlists or a specific one based on input), update entries, and clean up unprocessed records. It uses command-line arguments for verbosity and playlist ID, initializes logging and a database connection, ...
def main(): parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="Increase output verbosity", action="store_true") parser.add_argument("-l", "--listId", help="Playlist ID", nargs=1) args = parser.parse_args() locale.setlocale(locale.LC_ALL, 'en_GB') logger = init_log(...
def MIS(self, x_0, steps=2, batch_ids=None): total_poposal_num, accept_num = 0, 0 if self.use_cache: raise ValueError else: # x_0: (B,L) x_t, t_batch = None, None for _ in range(steps): x_proposals, log_q, t_batch = self.proposal(x_...
This function calculates the loss during training by generating noisy samples (x_t) from input data, computing log probabilities, and backpropagating the loss. In evaluation mode, it estimates the log probability difference between data and proposals, averaging over multiple samples to assess model performance.
def cal_loss(self, input_data, mode='train', train_sample_steps=2, batch_ids=None, eval_sample_num=1): MIS_steps = 1 if self.use_cache else train_sample_steps x_0 = input_data.to(self.device) if mode=='train': x_t, _, _, accept_rate, t_batch = self.MIS(x_0, steps=MIS_steps, batch_ids...
def add_features(df): df = df.assign( time_diff = lambda x:x['deadline']-x['launched_at'] ) return df def encode_categoricals(X_train, X_lnom, X_test, add_lnoms_func, params): # add outcome lnoms X_train_lnom = add_lnoms_func(X_train, X_lnom, "outcome") X_test_lnom = add_lnoms_func(X_tes...
The function preprocesses data for modeling by adding features, splitting data (with/without cross-validation), encoding categorical variables, selecting relevant features, handling missing values, and adjusting USD goal features. It returns cleaned training/test datasets and outcomes for model training/evaluation.
def data_clean_for_model(df, outcome, params, cv=True): df = add_features(df) if cv: X_train, X_test, y_train, y_test = train_test_split(df, df[outcome], test_size=params['test_frac'], random_state=params['rseed']) X_train_lnom, X_test_lnom = encode_categoricals(X_train, X_train, X_test, add_cv...
def zeros(name, folder="D:\\Reserved Space", size=1024**3): n = createName(name) f = open(os.path.join(folder,n+".res"),"wb+") f.write( bytearray(size) ) f.close() def ones(name, folder="D:\\Reserved Space", size=1024**3): n = createName(name) f = open(os.path.join(folder,n+".res"),"wb+") f....
The code generates multiple files with different data types (zero-filled, one-filled, random) in the specified directory. Each file is created with the given size (default 1 GB), using functions like zeros(), ones(), and random() to populate the data.
def fullFile(name, folder, size=1024**3): zeros(name,folder,size) ones(name,folder,size) random(name,folder,size) zeros(name,folder,size) random(name,folder,size)
def load_info(self): label_score = tk.Label(self.info_frame, text=f'SCORE {self.score}') label_score.grid(row=0, column=0, sticky='w', pady=(5, 30), padx=5) label_score.config(bg='gray4', fg=self.fg_color, font=('Comic Sans MS', 14)) label_next = tk.Label(self.info_frame, text='NEXT BL...
This code initializes a Tetris-like game interface by setting up the main window, binding keyboard controls for movement/rotation, creating UI frames for the play area and info panel, preparing block types, and initiating game components like score tracking and block spawning.
def __init__(self, main_window, menu_frame): self.main_window = main_window self.menu_frame = menu_frame try: background_label = self.main_window.place_slaves()[0] background_label.destroy() except IndexError: pass self.bg_color = 'black' ...