dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def Initialization(): G.Signal_Values= [0 for i in range(G.No_Signals)] # To store the dictionary values from Signal data dictionary G.Signal_Values[i][0]--> gives the Signal data to plot for the first signal G.Signals_Segments= [0 for i in range(G.No_Signals)] #intializing Signal Seg...
The main task of the code is to generate and visualize data plots based on input parameters. It processes input data using functions like cumulative sum calculations, data concatenation, reshaping, and waveform generation, while configuring plot settings such as color indexing, subplot dimensions, and signal handling. ...
def Plot_Data(ATPName,TestCaseNum,InputData): global ATP_name global TestCase_No received_data= Datamanipulation.Generate_Data(InputData) G.Plot_Init() ATP_name= ATPName TestCase_No=TestCaseNum ...
def Initialization(): G.Signal_Values= [0 for i in range(G.No_Signals)] # To store the dictionary values from Signal data dictionary G.Signal_Values[i][0]--> gives the Signal data to plot for the first signal G.Signals_Segments= [0 for i in range(G.No_Signals)] #intializing Signal Segme...
The code processes input data for plotting by initializing a waveform generation environment, configuring global variables for test case identification, and executing a sequence of data manipulation and visualization functions to generate and display waveforms with specific signal processing steps.
def Plot_Data(ATPName,TestCaseNum,InputData): global ATPname global TestCaseNo received_data= Datamanipulation.Generate_Data(InputData) G.Plot_Init() ATPname= ATPName TestCaseNo=TestCaseNum ...
def __generate_variables(self): """Generate the variables from the yaml to set into linpeas bash script""" variables_bash = "" for var in YAML_VARIABLES: variables_bash += f"{var['name']}=\"{var['value']}\"\n" return variables_bash def __replace_mark(self, mark: str,...
The code's main task is to construct and populate a script (`linpeas_sh`) by generating variables, find commands, storage sections, regex searches, and GTFOBins lists, then replacing predefined placeholders (marks) with these generated content. It ensures all expected components are created, checks for duplicates, vali...
def build(self): print("[+] Building variables...") variables = self.__generate_variables() self.__replace_mark(PEAS_VARIABLES_MARKUP, variables, "") print("[+] Building finds...") find_calls = self.__generate_finds() self.__replace_mark(PEAS_FINDS_MARKUP, find_calls, " ...
def make_df2_pickle(): df, df2, df3 = read_data_and_preprocessing() return df2 def make_df3_pickle(): df, df2, df3 = read_data_and_preprocessing() return df3 def make_model_pickle(): df, df2, df3 = read_data_and_preprocessing() xgb_model = building_model(df3) return xgb_model def validate...
The main task of the code is to perform predictive modeling using a pre-trained XGBoost model. It ensures required data structures (df2, df3) and the model are available by loading from pickle files or regenerating them if missing. The function validates input data against these structures, then uses the model to predi...
def pred(new_data): try: df2 = pickle.load(open("df2.pkl", "rb")) except(OSError, IOError) as e: pickle.dump(make_df2_pickle(), open("df2.pkl", "wb")) df2 = pickle.load(open("df2.pkl", "rb")) try: df3 = pickle.load(open("df3.pkl", "rb")) except(OSError, IOError) as e: ...
def psi_removeChunk(N, psi_arr, xi, yi, zi, size): # if ((xi + size > N) or (yi + size > N) or (zi + size > N)): # raise Exception("Chunk to remove excceeds bounds") for _z in np.arange(zi, zi + size): for _y in np.arange(yi, yi + size): for _x in np.arange(xi, xi + size): ...
The code simulates 3D structures with random voxel chunks and holes using subtractive/generative methods, performs finite element analysis (FEM) to compute displacement under gravity, and evaluates structural deformation and optical length changes. It generates meshes, applies boundary conditions, solves for displaceme...
def sim_randomChunks_hole(N, offset, nb_chunks, maxSize_chunks, design, hole_state, mesh_res, file_name): nb_voxels = N*N*N nb_empty = 0 _ref = np.floor((N-1)/2) # ================================================ # subtractive design. Removes chunks then hole with mirrors. # remove smaller ch...
def psi_removeChunk(N, psi_arr, xi, yi, zi, size): if ((xi + size > N) or (yi + size > N) or (zi + size > N)): raise Exception("Chunk to remove excceeds bounds") for _z in np.arange(zi, zi + size): for _y in np.arange(yi, yi + size): for _x in np.arange(xi, xi + size): ...
The code simulates the removal of random 3D chunks and holes from a voxel grid, generates a mesh, and performs finite element analysis (FEM) to compute structural deformation under gravity. It calculates displacement fields, analyzes optical length changes between mirrored regions, and visualizes results. The task invo...
def sim_randomChunks_hole(N, offset, nb_chunks, maxSize_chunks, hole_state, mesh_res, file_name): nb_voxels = N*N*N nb_empty = 0 if (N%2 == 0): # bottom left coord _ref = N/2 -1 else: _ref = (N-1)/2 psi = np.array([0] * nb_empty + [1] * (nb_voxels - nb_empty)) ...
def sim_randomChunks_hole(N, offset, nb_chunks, maxSize_chunks, design, hole_state, mesh_res, file_name): nb_voxels = N*N*N nb_empty = 0 _ref = np.floor((N-1)/2) # ================================================ # subtractive design. Removes chunks then hole with mirrors. # remove smaller ch...
The code implements a genetic algorithm to optimize structural designs by evolving parent solutions through crossover, mutation, and selection. It initializes a population of random configurations, evaluates their performance (maximum displacement and deformation), and iteratively breeds new generations. Poor-performin...
def main(): # size of initial population nb_pop = 20; psi_array = []; u_max_array = []; delta_L_array =[]; nb_breed = 100; N = 12 offset = 6 # not really used anymore. nb_chunks = 30 # i use 5 for subtractive and 8 for generative maxSize_chunks = 3 # not so constrained anymore. Ensure less...
def sim_randomChunks_hole(N, offset, nb_chunks, maxSize_chunks, hole_state, mesh_res, file_name): nb_voxels = N*N*N nb_empty = 0 if (N%2 == 0): # bottom left coord _ref = N/2 -1 else: _ref = (N-1)/2 psi = np.array([0] * nb_empty + [1] * (nb_voxels - nb_empty)) ...
The main task of the code is to implement a genetic algorithm for optimizing parameters (psi, u_max, delta_L) through iterative breeding of parent solutions. It initializes a population via simulations, selects parents, performs crossover to generate children, and replaces the worst-performing parent if the child exhib...
def main(): # size of initial population nb_pop = 3; psi_array = []; u_max_array = []; delta_L_array =[]; nb_breed = 5; N = 5 offset = 3 nb_chunks = 0 maxSize_chunks = 2 mesh_res = 10 # N = 15, mesh res = 20 just now. offset = 4. # nb pop = 10, nb pop = 5; start_time ...
def testPacketFromInput(): print ('PACKET FROM INPUT TEST') tests = [ '[4, 5, 1]', '[]', '[[]]', '[[3], [1, [12, [4, 5]]]]', '[1,[2,[3,[4,[5,6,7]]]],8,9]', '[[],[[[9],[1,5],5],[[9,0,8,2],4,10,2],2,[[3,1,5,2,8],10]],[],[[10,[2,5],[],[2,10,5,4]],10,3],[[[8,5,4,8,7],...
The main task of the code is to solve Advent of Code Day 13 challenges by testing packet parsing, ordering validation, and computing solutions for Part 1 (outputting 4894) and Part 2. It executes test functions and problem-specific logic to process input data and verify results.
def main(): print('Aoc day 13') testPacketFromInput() testOrderCorrect() part1() # 4894 is right part2()
def loadGrid(lines): start = None end = None for y, row in enumerate(lines): if start != None and end != None: break if 'S' in row: start = (row.find('S'), y) if 'E' in row: end = (row.find('E'), y) # replace start and end letters with elevat...
The code solves Advent of Code Day 12's pathfinding problem. It calculates the shortest path from a start to end point in a grid (Part 1) and then finds the minimal path starting from all 'a' elevation points (Part 2). It uses recursion for pathfinding, measures execution time, and optimizes Part 2 by grouping 'a' poin...
def main(): print('AOC day 12') sys.setrecursionlimit(10000) print('Recursion limit {}'.format(sys.getrecursionlimit())) testgrid = loadGrid(loadLines('input2.txt')) grid = loadGrid(loadLines('input.txt')) shortest = shortestPath(testgrid[0], testgrid[1], testgrid[2]) startTime = time.time()...
def get_db_client(): """Return an authenticated connection to DocumentDB""" # Use a global variable so Lambda can reuse the persisted client on future invocations global db_client if db_client is None: logger.info('Creating new DocumentDB client.') try: cluster_uri = os.env...
The main task of the code is to monitor DocumentDB for data changes via change streams, process insert/update/delete events, and forward them to SQS and S3 while maintaining state tracking. It retrieves events, enriches metadata, handles operation types, and ensures state synchronization to avoid reprocessing, with err...
def lambda_handler(event, context): """Read any new events from DocumentDB and apply them to an streaming/datastore endpoint.""" events_processed = 0 canary_record = None watcher = None try: # DocumentDB watched collection set up db_client = get_db_client() watched_db = os....
def checkSummon(self): if time.time() - self.preSummonTime <= self.getSummonCD(): return False self.preSummonTime = time.time() self.preSummon() return True def checkImageIndex(self): if time.time() - self.preIndexTime <= self.getImageIndexCD(): return ...
The main task of the code is to perform three checks: verifying summon validity, updating image index for animations, and validating the object's position. These methods collectively ensure the object's state remains consistent by handling summon logic, visual updates, and positional accuracy during runtime.
def update(self): self.checkSummon() self.checkImageIndex() self.checkPosition()
def find_commands(equation): ''' Function to identify '\' LaTeX commands within math text Parameters: equation (str) : Equation within math text Returns: commands (list) : List of identified commands within 'equation' ''' commands = [] for match in re.finditer(r'\\', equati...
This function converts LaTeX math commands in an equation to alt text by mapping symbols to their descriptive equivalents, handling special cases like trigonometric functions with exponents, and replacing symbols using provided dictionaries. It processes each command, skips irrelevant ones, and constructs an alt text r...
def alt_commands(arg, track_commands, symbols, converted_symbols, special_symbols): ''' Function to convert the commands to alt text Parameters: arg (str) : Math text within brackets commands (list) : List of identified commands within the equation symbols (list) : ...
def flatten(eqn_list): ''' Function to 'flatten' a list of strings and lists into one list of strings Parameters: eqn_list (list) : List of strings and strings within lists Returns: flattened (list) : List of items in 'eqn_list' as single list entries ''' flattened = [] for...
This function processes a mathematical equation to convert nested bracket structures into alternative text. It parses LaTeX expressions, adjusts formatting for elements like exponents, square roots, and fractions, replaces commands like \\left/\\right, and generates alt text using symbol mappings and replacements. The ...
def nested_brackets(equation, track_commands, symbols, converted_symbols, special_symbols): ''' Function to find the elements within nested brackets Parameters: equation (str) : Equation within math text symbols (list) : List of LaTeX symbols in csv file converte...
def convert_symbols(equation, index, value, track_commands, special_symbols): ''' Function to convert symbols to alt text Parameters: equation (str) : Equation within math text index (int) : Index of 'value' in 'equation' value (str) : Symbol found in math text track_command...
The function `eqn_tokenise` converts a LaTeX equation into an alt text representation by tokenizing the input equation. It processes symbols, commands, brackets, and special notations (e.g., fractions, subscripts) using regex and predefined mappings. The output is a plain-text description of the equation’s structure, s...
def eqn_tokenise(equation, symbols, converted_symbols, special_symbols): ''' Function to tokenise an equation within the LaTeX document Parameters: equation (str) : Equation within math text symbols (list) : List of LaTeX symbols in csv file converted_symbols (list) : List of alt te...
def cuda_info(self, device): if device.type == 'cuda': dev_idx = int(self.cuda.split(':')[-1]) print(torch.cuda.get_device_name(dev_idx)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(dev_idx)/1024**3,1), 'GB') print('Cac...
The code trains a deep learning model (LDNet) for regression tasks, using Mean Squared Error (MSE) loss and Adam optimizer. It preprocesses data by calculating mean/std, transforms datasets, loads checkpoints if specified, trains over multiple epochs, tracks loss, and saves models when loss improves. The training loop ...
def train_model(self): # setting device on GPU if available, else CPU device = self.device print('Using device:', device) print() loss_list = [] iter_list = [] loss = 0 epoch_s = 0 best_loss = float('inf') step_loss = float('inf') ...
def allowed_file(filename): return '.' in filename and filename.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS def save_rxn(rxninfo): global session filename = secure_filename(rxninfo.filename) try: uniquename = file_path(session['uniqueid'], filename) except: init_session() ...
The function processes reaction data inputs (file, SMILES, or database ID), validates them, generates visualizations using Selenzy, and returns SVG data or file paths along with status/success indicators for web display.
def display_reaction(marvin=app.config['MARVIN']): """ Validates the query and displays the reaction """ if request.method == 'POST': size = (600,400) if 'file' in request.files and len(request.files['file'].filename) > 0: fileinfo = request.files['file'] if fileinfo.f...
def ResNet50(input_shape, num_classes=10): input_object = Input(shape=input_shape) layers = [3, 4, 6, 3] channel_depths = [256, 512, 1024, 2048] output = Conv2D(64, kernel_size=7, strides=2, padding="same", kernel_initializer="he_normal")(input_object) output = BatchNormalization()(output) outp...
The main task of the code is to perform image classification using a pre-trained ResNet50 model. It loads a model with specified input dimensions and class count, preprocesses an input image by resizing, normalizing, and expanding dimensions, then predicts the top 5 classes with their confidence percentages using a JSO...
def run_inference(): model = ResNet50(input_shape=(224, 224, 3), num_classes=10) model.load_weights(MODEL_PATH) picture = os.path.join(execution_path, "Haitian-fireman.jpg") image_to_predict = image.load_img(picture, target_size=( 224, 224)) image_to_predict = image.img_to_array(image_to_p...
def Part1(inputs: list) -> int: return GetGammaRate(inputs) * GetElipsonRate(inputs) def Parse(filePath: str) -> list[str]: inputs = Path(filePath).read_text().strip() return inputs.split("\n") def Part2(inputs: list) -> int: return GetOxyRating(inputs) * GetCo2Rating(inputs)
The code defines a function `Solve` that processes a file path to compute and print solutions for two parts of a problem. It uses `Parse` to read/interpret the input data, then applies `Part1` and `Part2` functions to derive results, which are printed as "Day 3 - Part 1 Solution" and "Day 3 - Part 2 Solution" respectiv...
def Solve(path: str): print(f"Day 3 - Part 1 Solution: {Part1(Parse(path))}") print(f"Day 3 - Part 2 Solution: {Part2(Parse(path))}")
def perspective_mouse_bvh_cast(context, event, bvh): origin = view_origin(context) direction = view3d_utils.region_2d_to_vector_3d(context.region, context.space_data.region_3d, (event.mouse_region_x, event.mouse_region_y)) return bvh.ray_cast(origin, direction) def orthographic_mouse_bvh_cast(context, event, bvh): ...
This code handles a modal operator in Blender for interactive 3D surface creation. It captures mouse events to set surface origin/normal, cycles projection modes (floor/mesh/view), updates corner points dynamically, adjusts geometry via mouse movement, and cancels on right-click. It uses raycasting for surface detectio...
def modal(self, context, event): try: context.area.tag_redraw() if event.type == "RIGHTMOUSE" and event.value == "PRESS": bpy.types.SpaceView3D.draw_handler_remove(self.draw_handle__internal, "WINDOW") print("CANCELLED") return {"CANCELLED"} if event.type == "TAB" and event.value == "PRESS": ...
def creat_database(): print("Creating Database...") conn = database_connection() cursor = conn.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS tags_table( idx integer, title text, plot_synopsis text, tags text, split text, synopsis_source text, ...
The main task of the code is to check if a CSV file ("data_with_all_tags.csv") exists. If not, it downloads the IMDb reviews dataset from Kaggle, creates a database, and cleans the downloaded data. The code ensures data availability by either reusing existing files or fetching and processing them if they are missing.
def main(): if os.path.exists("data_with_all_tags.csv"): print("Data already exists") else: print("Downloading dataset from Kaggle") creat_database() data = download_imdb_reviews_kaggle() # mpst_database() # data_load() data_cleaning(data)
def __get_aligned_coors(self, other_coors, other_v1_idx, other_v2_idx, my_v1_idx, my_v2_idx): ang = self.__get_angle(other_coors[other_v1_idx], other_coors[other_v2_idx]) x1, y1 = other_coors[other_v1_idx] ret...
This function aligns coordinates between two structures by attempting two alignment configurations (swapping vertex pairs) to avoid triangle intersections. It selects the non-intersecting alignment, identifies the third vertex index, and returns reordered coordinates with specified vertex indices. The process ensures g...
def align_to_helper(self, other_coors, other_v1_idx, other_v2_idx, my_v1_idx, my_v2_idx, debug_txt): try1_coors = self.__get_aligned_coors(other_coors, other_v1_idx, other_v2_idx, my_v1_idx, my_v2...
def apply_elitism_func(population, N_e): assert N_e <= len(population) if N_e == 0: return np.asarray([]) return sorted(population, key=lambda x: x.get_dist_from_target())[:N_e] def apply_selection(population, selection_type, N_e, s=0): if selection_type == ROULETTE_WHEEL: return roulett...
This function simulates an evolutionary algorithm for optimizing bridge design parameters. It initializes populations, tracks metrics like minimum/mean distance from a target and variant diversity across generations, applies selection, elitism, and mutation operations, and saves plots and statistics. The goal is to evo...
def single_model_runner(generation_num, population_size, selection_type , mutation_p, N_e, output_path, s=0): BB_population = BuildingBlockPopulation(population_size) bridges = BridgesPopulation(population_size, BB_population).population pie_path = path.join(output_path, "distribut...
def get_legal_pairing(self, idx_of_1st_triangle): is_legal = False pair = tuple() while not is_legal: edge_idx1 = randint(0, 2) edge_idx2 = randint(0, 2) pair = (edge_idx1, edge_idx2) is_legal = self.is_legal_pairing(pair, idx_of_1st_triangle) ...
This function inserts a new building block into a specific position within a sequence and updates associated edge pairings to maintain structural connectivity. It handles two scenarios: if the insertion exceeds existing edge pairs, it generates a new pairing; otherwise, it splits an existing pair, creates two new pairs...
def add_new_building_block(self, building_block: BuildingBlockHolder, position: int): # update building block self.blocks.insert(position, building_block) # update pair information if position - 1 >= len(self.edges_pairs): pair = self.get_lega...
def remove_pair(self, idx): edge_of_1st, edge_of_2nd = self.edges_pairs[idx] self.blocks[idx].is_edge_taken[edge_of_1st] = \ False self.blocks[idx + 1].is_edge_taken[edge_of_2nd] = \ False def is_legal_pairing(self, pair, idx_of_1st_triangle): ret_val, _ = self....
The function replaces an existing pair at a specified index by first removing it, then validating the new pair. If invalid, it identifies conflicts and resolves mismatches. Finally, it updates the pair at the given index with the new configuration.
def set_new_pair(self, pair, pair_idx, which_one_changed): self.remove_pair(pair_idx) if not self.is_legal_pairing(pair, pair_idx): _, which_one_conflicted = self.get_conflicted_edge(pair, pair_idx) self.handle_pairs_mismatch(pair, pair_idx, which_one_changed, ...
def generate_path(generation_num, population_size, selection_type, mutation_rate, N_e, var_range=None, var_name=None): generation_val = f"num_gens_{generation_num}" population_val = f"pop_size_{population_size}" mutation_rate_val = f"mutation_rate_{str(mutation_rate).rep...
The main task of the code is to manage and visualize results from multiple evolutionary algorithm simulations by varying parameters like generation number, population size, selection type, and mutation rate. It generates output paths, runs simulations with adjusted parameters via `single_model_runner`, aggregates resul...
def plot_results_manager(generation_num, population_size, selection_type, mutation_rate, N_e, s, var_range=None, var_name=None): overall_data = [] txt = "" global PARENT_PLOT_PATH PARENT_PLOT_PATH = generate_path(generation_num, population_size, ...
def order_by_permutation(self): self.blocks = [None] * self.size for idx, building_blk_idx in enumerate(self.order): self.blocks[idx] = self.building_blocks[ building_blk_idx] def order_edges_in_pairs(self): self.edges_pairs = [None] * (self.size - 1) for i...
This code initializes an object representing a population of geometric building blocks (likely triangles) by randomly selecting instances from a provided population. It sets up parameters like size, orders blocks via permutation, pairs edges, and generates coordinates. The fitness function is initialized but not yet co...
def __init__(self, building_block_population): # random init self.population = building_block_population self.size = randint(10, MAX_NUM_OF_TRIANGLES_INIT) self.building_blocks = [] self.blocks = [] self.edges_pairs = List[tuple] self.order = list(np.random.permutation(...
def handle_expansion(self, new_size): num_to_add = new_size - self.size indices_to_add = sorted(sample(range(new_size), num_to_add)) for position in indices_to_add: bb = self.population.get_random_building_block() self.add_new_building_block(bb, position) self....
The main task of the code is to adjust the size of a bridge structure by expanding or shrinking it based on the `new_size` parameter. It calculates the growth factor, triggers expansion/shrinkage handling, validates that the number of edge pairs matches the expected count (`new_size - 1`), and exits with an error if in...
def change_bridge_size(self, new_size): str_to_dbg = 'expansion' growth_factor = abs(new_size - self.size) if new_size == self.size: # nothing changed return elif self.size < new_size: idx = self.handle_expansion(new_size) elif self.size > new_size: ...
def sim_1(): population_sizes = [30, 100, 300] plot_results_manager(generation_num=100, population_size=0, # Would be filled using # var_range param selection_type=ROULETTE_WHEEL, mutation_ra...
The main task of the code is to sequentially execute seven predefined simulation functions (sim_1() to sim_7()) as part of a larger project. The run_manager() function acts as an orchestrator, triggering each subset simulation in order to replicate or analyze scenarios from the project's broader simulations.
def run_manager(): # The written simulations in functions sim_1(),...,sim_7() are subsets of # simulation we have conducted during our projects sim_1() sim_2() sim_3() sim_4() sim_5() sim_6() sim_7()
def mode(self, mode): # the mode value is invalid if mode not in [CONFIG, ACCGYRO, AMG, NDOF]: raise ValueError self._mode = mode self._write_register(OPR_MODE, mode) # delay for more than 20 milliseconds time.sleep(0.03) def _read_register(self, reg): ...
The code initializes a BNO055 sensor by configuring I2C communication, verifying the chip ID, resetting the device, setting power mode, unit selection, axis calibration, accelerometer, gyroscope parameters, and switching to NDOF mode for operation.
def __init__(self, bus, address=I2C_ADDR_1, units = 0): # create an I2C bus object and set the address self.bus = bus self.address = address self.mode(CONFIG) # check the chip ID if BNO055_ID != self._read_register(CHIP_ID): raise RuntimeError("BNO055 failed ...
def log( s ): ''' print a message on the screen with identifier ''' print( "[read_csv] ", str(s) ) def read_csv_file( path ): '''open and read the CSV file the function reads and splits the fields of the CSV file. Arguments: path (string) : the complete path of the file. ...
The main task of the code is to read a CSV file, transform its string data, infer column data types, generate SQL schema and insert statements, and write them to an SQL file for database creation and data insertion.
def main( ): ''' the main of the test ''' log( "reading file" ) lsplit = read_csv_file( '../test_codes/input_sample_1.csv' ) log( "the file is:" ) print("---") for ln in lsplit: print(ln) print( "\n---" ) log( 'table transformation' ) for i in range( len( lsplit ) ): ...
def have_bomb(self): return self.bomb def near_bombs(self): b = 0 for x in self.get_around(): if x.have_bomb(): b += 1 return b def get_around(self): ret = [] if self._test_p(self.px - 1, self.py - 1): ret.append(self.area_p[self.px...
This method renders a tile's visual state in a game, displaying 'b' if it contains a bomb (ending the game), the count of nearby bombs, or '-' for empty tiles. If flagged, it shows 'f'; otherwise, it's blank. It also triggers automatic reveals of adjacent tiles when a zero-bomb tile is opened.
def paint(self): if self.open: if self.have_bomb(): self.textSprite.setText('b') self.parent.end_game(1) else: number = self.near_bombs() self.textSprite.setText('%d' % (number,)) if number == 0: ...
def add_data_point(self, node, data_point): #add data points and update the the MBRS node.data_points.append(data_point) if data_point['x'] < node.MBR['x1']: node.MBR['x1'] = data_point['x'] if data_point['x'] > node.MBR['x2']: node.MBR['x2'] = data_point['x'] if ...
This code inserts a data point into a tree structure. If the target node is a leaf, it adds the point, updates the minimum bounding rectangle (MBR), and handles overflow. If the node is not a leaf, it recursively selects the optimal subtree for insertion, continues the process, and updates the MBR of the subtree. The g...
def insert(self, u, p): # insert p(data point) to u (MBR) if u.is_leaf(): self.add_data_point(u, p) #add the data point and update the corresponding MBR if u.is_overflow(): self.handle_overflow(u) #handel overflow for leaf nodes else: v = self.choose_...
def initialisation_with_init_centers(self,X): """Standard initialization cannot handle known centroids. This function goes manually through all necessary computations to go on as usual""" # one cannot use the routine initialize centroids, then find quantile risk and update # because it can only ...
The code implements the K-bMOM algorithm to fit a model by iteratively sampling data blocks, computing quantile risks, updating cluster centers, and checking convergence via the Aitkens criterion. It initializes clusters with provided centers or randomly, tracks risks and centroids through iterations, and returns outpu...
def fit(self,X): """Main loop of the K-bMOM algorithm:""" # if the model has already been fitted, return computed output if self.has_model_already_been_fitted: return self.fit_output # else continue # instantiate useful variables self.q_quantile_block...
def access_token_from_file(): file = open("access_token.txt","r") access_token = file.read() file.close() return access_token def handle_and_return_possible_error_message_in_api_response(response): if response.ok: return response_data = response.json() if "error" in response_dat...
This function sends HTTP requests to Spotify's API endpoints with authentication, handling token refresh on 401 errors. It constructs URLs with parameters, uses Bearer token authorization, and retries requests with a new token if the initial access token expires.
def spotify_request(endpoint, http_method="PUT", data=None, force_device=False, token=None, url_params={}): app.logger.info("Request to endpoint '/" + endpoint + "' attempted") if token is None: token = access_token_from_file() if force_device: url_params["device_id"] = "98bb0735e28656bac09...
def say(something): run(["espeak", something], stdout=subprocess.DEVNULL) def play(spotify_uri=None, song_number=0, retries_attempted=0): # XXX: naming problem between this and spotiplay global currently_playing data = '' if spotify_uri != None: #data = '{"context_uri":"' + spotify_uri + '"...
The code handles form submissions in a web application, performing actions like sending text, playing/pausing media, or requesting Spotify authorization based on form inputs. It validates the form, executes corresponding functions, captures responses, and renders a template with the form and result messages.
def index(): # you must tell the variable 'form' what you named the class, above # 'form' is the variable name used in this template: index.html form = NameForm() message = "" response = None if form.validate_on_submit(): if form.say.data: say(form.text.data) if f...
def validate_range_value(value): global first_number global last_number global range_count if value > last_number: value_greater_last_number(value) else: first_number = value def write_range(first_number, last_number, readings): global ranges data = { 'range': str(fir...
The code processes an array by counting its elements, validating each element's range, and then writing the range details. It increments a global counter, calls validation, and sends aggregated results.
def check_ranges_on_array(array): global range_count for x in array: range_count += 1 validate_range_value(x) write_range(first_number, last_number, range_count) return send_result(ranges)
def run_query(query): request = requests.post('https://api.github.com/graphql', json={'query': query}, headers=headers) if request.status_code == 200: return request.json() else: raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query)) def run_v3_...
The main task of the code is to gather various GitHub-related statistics (profile views, lines of code, repository info, etc.) via API calls and format them into a markdown string containing progress badges and visualizations, conditional on specified flags. It compiles these elements into a cohesive markdown output fo...
def get_stats(github): '''Gets API data and returns markdown progress''' stats = '' repositoryList = run_query(repositoryListQuery.substitute(username=username, id=id)) if show_profile_view.lower() in truthy: data = run_v3_api(get_profile_view.substitute(owner=username, repo=username)) ...
def anomaly_detection_pipeline_iso_fst(df, n_comp, window,sensor_cols,inf): '''Anomaly Detection pipeline using Isolation Forest''' df_c = df.copy() X = df_c[list(sensor_cols)] st.session_state.df_viz = df_c eng_fe = pd.DataFrame() use_label, label = check_label() precision, recall, f1_score...
This code detects anomalies in sensor data using selected algorithms (Isolation Forest, LOF, SOS, DBSCAN) via a Streamlit interface. It processes uploaded CSV data, applies chosen anomaly detection methods, computes performance metrics, visualizes results, and exports anomaly-labeled dataframes. The core task is anomal...
def detect_anomalies(): st.title('Detect Anomalies') if 'df' not in st.session_state or 'sensors' not in st.session_state: st.write('Please upload CSV file for anomaly detection and select the sensors you would like to consider for anomaly detection.') else: df = st.session_state.df ...
def display_pdf(file): with open(file,"rb") as file_obj: base64_pdf=base64.b64encode(file_obj.read()).decode("utf-8") pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="500" type="application/pdf"></iframe>' st.markdown(pdf_display,unsafe_allow_html=True) d...
The main task of the code is to create a Streamlit app that allows users to upload PDF/DOCX files, display their content preview, generate vector embeddings for the document, and enable a QA chatbot interface to answer user queries based on the uploaded file's content. It handles file storage, UI layout, embedding proc...
def main(): file_upload=st.sidebar.file_uploader("Upload file...",type=["pdf","docx"]) if file_upload: st.sidebar.success("File Uploaded successfully",icon="✅") file_name=file_upload.name # file name file_size=len(file_upload.read()) # get file size in bytes st.sidebar.markdown...
def get_points_around(self, point: Point) -> list: """ Easy way of returning all surrounding points of a given point :param point: initial point :return: all 4 points around the initial point """ return [self.get_point_up(point), self.get_point_down(point), ...
The function recursively adds points of a specified type around a given point, using get_points_around to identify neighboring locations. It applies this process iteratively, with the 'dept' parameter controlling recursion depth to generate layered surrounding points. Each recursive call reduces dept by 1 until it reac...
def add_points_around(self, point: Point, point_type, dept=0) -> None: """ Will add a type of point around a given point :param point: The point to surround with heat :param point_type: The point type to surround with :param dept: Recursively add the heat to points """ ...
def filter_dangers(self, points: List[Point], exception: Point = None) -> List[Point]: """ Filter out the dangerous points from a list of Points :param points: List of points to filter :param exception: A point that should be exempt from the rule :return: Return a list of points that wi...
The code determines the safest move for a snake in a game by evaluating surrounding points, calculating scores based on heat, avoiding food, distance to the tail, and pathfinding. It filters dangerous areas, prioritizes moves that minimize risk, and selects the highest-scoring move to ensure survival while navigating t...
def spin_and_survive(self): print("SPIN TO SURVIVE") safe_points_around = self.filter_dangers(self.get_points_around(self.you.head)) moves = [] for point in safe_points_around: move = Move(move=self.you.head.resolve_direction(point), point=point) ...
def filter_dangers(self, points: List[Point], exception: Point = None) -> List[Point]: """ Filter out the dangerous points from a list of Points :param points: List of points to filter :param exception: A point that should be exempt from the rule :return: Return a list of points that wi...
The `best_move` function determines the optimal movement for a snake in a game by evaluating safe points around its head, prioritizing moves based on heat (risk). It selects food-targeted moves if not the largest snake or prioritizes attacking smaller snakes if dominant. If neither applies, it defaults to the safest pa...
def best_move(self): """ Spaghetti Top 42! :return: """ safe_points_around = self.filter_dangers(self.get_points_around(self.you.head)) # sorted moves in order of heat sorted_points = sorted(safe_points_around, key=lambda m: point.heat) print("POSSI...
def filter_dangers(self, points: List[Point], exception: Point = None) -> List[Point]: """ Filter out the dangerous points from a list of Points :param points: List of points to filter :param exception: A point that should be exempt from the rule :return: Return a list of points that wi...
The code evaluates potential moves for a snake in a game by calculating scores based on factors like food proximity, danger avoidance, path efficiency to the tail, and opportunities to eliminate smaller enemies. It filters safe points around the snake's head, applies multipliers for strategic advantages, and selects th...
def best_move_score(self): print("BEST MOVE SCORE") safe_points_around = self.filter_dangers(self.get_points_around(self.you.head)) # settings biggest_enemy_snake = self.find_biggest_enemy_snake() food_multiplier = 1 if self.you.size > 10 else 1.5 kill_multiplier = 1.2 ...
def add_hazard(self, hazard: HazardPoint): self.add_point(HazardPoint(x=hazard.x, y=hazard.y)) self.food.append(hazard) def add_food(self, food: FoodPoint): self.add_point(FoodPoint(x=food.x, y=food.y)) self.food.append(food) def add_snake(self, snake: Snake) -> None: """ Add a f...
The code initializes a game board by setting up a grid based on the provided game state, adding hazards, food, and snakes. It organizes snakes and food by proximity to the player's head, preparing the environment for strategic decision-making in the game.
def __init__(self, game_state: GameState): print(game_state.dict()) # todo remove self.game_state = game_state self.turn = game_state.turn self.height = game_state.board.height # y self.width = game_state.board.width # x self.you = game_state.you self.middle =...
def turn_around(): for i in range(2): turn_left() def turn_right(): for i in range(3): turn_left() def go_next_street(): """ Pre-condition: (Corresponding to Exceptions 1-3 of the triangles() function) 1. Karel meets the right wall, facing east. 2. Karel is not on beeper, facing ...
The code navigates Karel to form a triangle by moving from the left vertex, handling exceptions when encountering walls or missing beepers. It picks up the left beeper, attempts to reach the top, and places a beeper at the right vertex, adjusting paths via turns and street transitions if blocked.
def triangles(): """ A triangle has three vertices, left, top and right vertices. Pre-condition: Karel is on a beeper (left vertex). Post-condition: The left beeper is picked up and the top beeper is put. Karel's on the beeper where a right vertex is supposed to be. Exceptions when Karel has to ...
def turn_around(): for i in range(2): turn_left() def put_checkerboard_and_back(): """ Pre-condition: Karel's at (1, 1), facing east. There's no beeper on 1st Street. Post-condition: Karel's at (1, 1), facing east. 1st Street's filled in checkerboard pattern. """ put_beeper() while f...
The main task is to place a single beeper at the midpoint of 1st Street by detecting the square's size (1x1, 2x2, or larger) and using a checkerboard pattern with triangles to form a pyramid. The algorithm adjusts for board types (even/odd corners) to ensure the beeper is placed correctly, handling all cases through co...
def main(): """ Pre-condition: There's no beeper. Post-condition: One beeper is on the midpoint of 1st Street. """ """ There are two types of boards in this problem: - Type 1: A board with even number of corners. - Type 2: A board with odd number of corners. If starting from (1, 1), ...
def tick(self,element): self.tick_list.append(element) def duplicate(elements, times): ret = [] for _ in range(0, times): for e in elements: ret.append(e) return ret def get_repeat(element) -> int: information = information_parsing.divide_information(element) return infor...
This function recursively expands elements based on their type, generating a list by duplicating atomic elements, expanding nested sections iteratively, or cycling through alternations. It handles atomic elements by duplicating them, sections by recursively expanding children until all are processed, and alternations b...
def expand(self, element, repeat) -> list: #print("EXPANDING: ", element.decompile(), " ", element.type, len(element.elements)) if element.type == ElementType.ATOMIC: self.tick(element) return duplicate([element], repeat) if element.type == ElementType.SECTION: ...
def image_loader(self, image_bytes): """ Method Name : image_loader Description : This method load byte image and save it to local. Output : Returns path the of the saved image """ logging.info("Entered the image_loader method of PredictionPipeline class") ...
The main task of the code is to process input data by loading an image, retrieving a pre-trained model from Google Cloud, performing prediction on the image using the model, and returning the detected output. The method logs entry/exit points and handles exceptions by raising a custom exception with the error details.
def run_pipeline(self, data): logging.info("Entered the run_pipeline method of PredictionPipeline class") try: image = self.image_loader(data) print(image, type(image)) best_model_path: str = self.get_model_from_gcloud() detected_image = self.prediction(be...
def remove_waste_words_find_xp_levels(self, tree, decl_clause, level, found_xp): max_levels = level for index, node in enumerate(tree): if type(node) == Tree: if index == 0 and node.label() == decl_clause: found_xp = True levels = self.remove_waste_words_find_xp_levels(node, decl_clause, level+1, f...
The main task of the code is to prune a syntactic tree by iteratively removing redundant constituents (e.g., outer XP structures like S, NP, VP and trailing phrases like PP, SBAR) until the resulting sentence length falls below a specified maximum length (`max_len`). This ensures the tree represents a more concise sent...
def remove_waste_words(self, tree, max_len): XPs = ['S', 'NP', 'VP'] for clause in XPs: current_sentence_len = len(tree_to_sentence(tree)) if (current_sentence_len < max_len): break levels = self.remove_waste_words_find_xp_levels(tree, clause, 0, False) while levels > 1: current_sentence_len = l...
def kraken_long_currency_mappings(currency): mappings = {"btc": "xxbt", "BTC": "XXBT", "doge": "xxdg", "DOGE": "XXDG", "EUR": "ZEUR", "eur": "zeur", "xlm": "xxlm", "XLM": ...
The main task of the code is to withdraw a specified cryptocurrency from Kraken to the user's wallet address if the balance exceeds 0.0001. It retrieves the wallet address from a JSON file, maps the currency code, checks the balance, and executes a withdrawal via Kraken's API if sufficient funds exist. If the balance i...
def withdraw_to_wallet(self, currency_to_withdraw): with open(f"bin/meta_login_{self.name}.json") as login: data = json.load(login) address = data["my_addresses"][str(currency_to_withdraw).lower()] login.close() currency_to_withdraw = self.kraken_long_currency_mappi...
def get_balance(self, currency=False): self.load_key(self.name, "bitstamp") r = self.bitstamp_api_query("balance") if currency: try: amount = r[f"{currency}_available"] except: amount = 0 return float(amount) else: ...
The code facilitates cryptocurrency withdrawal by loading a user's wallet address from a JSON file, calculating the available balance after deducting withdrawal fees, and initiating a withdrawal via the Bitstamp API if the remaining amount exceeds 0.0001. It returns the API response or a message indicating insufficient...
def withdraw_to_wallet(self, currency_to_withdraw): with open(f"bin/meta_login_{self.name}.json") as login: data = json.load(login) address = data["my_addresses"][str(currency_to_withdraw).lower()] login.close() amount = self.get_balance(currency_to_withdraw) ...
def authenticatespreadsheet(doc_name, sheet_name): # obtain JSON file from https://console.cloud.google.com/ - video: https://www.youtube.com/watch?v=V51zRxLAVWU&t=646s scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets', "https://www.google...
This code adds new Bitstamp transactions to an audit spreadsheet, filtering only those with IDs greater than the last recorded Bitstamp transaction. It authenticates the spreadsheet, retrieves relevant transactions, appends them with delays, and returns the count of added rows.
def fill_sheet_file(self, pair, sheetfile): crypto = str(pair[:3]) audit_file = authenticatespreadsheet(sheetfile, f"{self.__class__.__name__}({crypto.upper()})") transactions = self.show_transactions(pair) last_bitstamp_transaction = (list(filter(lambda x: x['Provider'] == self.__class_...
def public_key_to_Header(public_key): return { "typ": "dpop+jwt", "alg": "ES256", # we're hardcoding because we're not changing algo ever "jwk": public_key_to_JWK(public_key) } def strToBase64URL(s): sBytes = bytes(s, 'utf-8') return bytesToBase64URL(sBytes) def intToBytes(n): return...
The main task of the code is to generate a DPOP (Delegated Proof-of-Possession) token by creating a signed JWT. It uses an ECDSA key pair to construct a payload with claims like `iat`, `jti`, `htu`, and `htm`, encodes it in base64, signs it with the private key, and formats the signature for API authentication. The res...
def generate_DPOP(*, uuid, method, url): private_key = ec.generate_private_key( ec.SECP256R1() ) # DPOP lets you specify payload = { "iat": int(time()), # 1633388418, "jti": uuid, # "eca01827-1724-4eea-8eb6-4532616aed9f", "htu": url, # "https://api.mercari.jp/search_index/sea...
def initOpenCL(): global context, queue, program platforms = cl.get_platforms() devices = platforms[0].get_devices(cl.device_type.GPU) device = devices[0] global_mem = device.get_info(cl.device_info.GLOBAL_MEM_SIZE) local_mem = device.get_info(cl.device_info.LOCAL_MEM_SIZE) max_CU = device.g...
This function parses command-line arguments to determine execution mode (graph/check/print) and parameters (M, N) for the lab2 OpenCL kernel. It sets global variables, initializes OpenCL, and invokes the lab2 function with flags for result checking and printing, handling 3-6 argument cases with conditional logic.
def lab2_parse_argv(argv): global KERNELS_FILE check_results = False print_results = False if len(argv) == 1: print("Enter more arguments") return elif len(argv) == 3: if argv[2] == 'graph': KERNELS_FILE = argv[1] initOpenCL() graphics() ...
def decorrelate_and_normalize(data): """ Function to decorrelate and normalize data Args: data(ndarray): an N x M 2D array of observation vectors with each row being an M-dimensional observation vector, totally N observations Returns: tuple: (data, T, smean), where ...
The function performs the EM algorithm to estimate the optimal order (number of clusters) and parameters of a Gaussian Mixture Model (GMM) for given observations. It starts with an initial number of clusters, reduces it iteratively using MDL criteria, and returns the best-fitting GMM with parameters like cluster means,...
def estimate_gm_params(data, init_K=20, final_K=0, verbose=True, est_kind='full', decorrelate_coordinates=False, alpha=0.1): """Function to perform the EM algorithm to estimate the order, and parameters of a Gaussian mixture model for a given set of observations. Args: data(ndarray): an N x M 2D ar...
def write_line(self, line, no_indent=False): if no_indent: prefix = '' else: prefix = ' ' * 4 * self.indentation # self.lines.append(prefix + line) # + r'\n') self.lines.append(prefix + line + '\n') def write_quote(self, text): html_line = r'<q>{}</q>'.for...
This code formats a reference entry by writing author, title, and type-specific details (journal/conference), adding DOI/PDF links, and BibTeX dropdowns for academic citations.
def write_reference(self, key, ref): # Author and title self.write_line(get_author_string(ref)) self.write_quote(ref.fields['title'] + ',') # Journal papers: if ref.type == 'article': if 'journal' in ref.fields: self.write_italics(ref.fields['journal'...
def write_heading(self, heading_title): html_line = '<h3 id="h.p_wWsYqgOg8L8R" class="zfr3Q JYVBee">{}</h3>'.format(heading_title) self.write_line(html_line) def enumerated_list(self): self.write_line(r'<ul style="line-height:200%">') self.indentation += 1 yield self.inde...
This function generates a formatted list of academic references (conference or journal papers) by filtering entries from a dictionary based on their type. It counts matching entries, writes a heading, and lists each reference with a decrementing index and type-specific label. The output is structured using enumerated l...
def write_lines_by_type(self, bib_data_dict, keys, type_): if type_ is 'conference': heading = 'Conference papers' label = '[C{}]' elif type_ is 'journal': heading = 'Journal papers' label = '[J{}]' # Count number of journal/conference papers ...
def write_heading(self, heading_title): html_line = '<h3 id="h.p_wWsYqgOg8L8R" class="zfr3Q JYVBee">{}</h3>'.format(heading_title) self.write_line(html_line) def enumerated_list(self): self.write_line(r'<ul style="line-height:200%">') self.indentation += 1 yield self.inde...
The code organizes references by year, extracting unique years from a dictionary, sorting them in descending order, and writing each year as a heading with corresponding references in bullet points. It iterates through the sorted years, groups references by their year, and formats them using enumerated lists and bullet...
def write_lines_by_year(self, bib_data_dict, keys): years = [] for ref_label, ref in iteritems(bib_data_dict): if ref_label in keys: year = ref.fields['year'] if year not in years: years.append(year) old_years = [int(year) for year...
def verify_good_turn_color(self, pos_tuple): # we verify the color used row, col = pos_tuple if self.board[row][col] == "--": return False # we first clicked a wrong pos if self.board[row][col][0] == "b" and self.turn == 0: return False # you are white, pick white! ...
The function validates the first move by checking if the selected position has the correct player's color and if it's a possible move. It updates possible moves and bad moves, checks for checkmate, and returns whether the initial click is valid, invalidating it if checkmate is detected.
def valid_first_selection(self, pos_tuple): # we verify the color + if there are possible locations to move zero_check (f_row, f_col) = pos_tuple valid_click = self.verify_good_turn_color(pos_tuple) and self.verify_possible_move(pos_tuple) print("Primul click este valid : ", valid_click) ...
def get_all_possible_pieces_that_can_move(self): # for the current table returns all the pieces that can be moved pieces_available = [] for row in range(0,8): for col in range(0,8): able_to_be_moved = len(self.check_good_positions((row,col))[0])!=0 if self.board[...
The bot randomly selects a movable piece, identifies its valid moves, chooses a random valid move, introduces a delay, executes the move, and returns the new position.
def bot_move_handler(self): # we will be called only when is our turn pieces_able_to_be_moved = self.get_all_possible_pieces_that_can_move() print(pieces_able_to_be_moved) nr_pieces = len(pieces_able_to_be_moved) index_rand = random.randint(0,nr_pieces-1) selected_piece = pieces_able_...
def convert_info(node): all_fields = set(vars(node)) # TODO: make sure "node" is a dataclass so that we don't have to hard code # c_fields c_fields = {'body', 'defs', 'name', 'args', 'decorator_list', 'returns', 'type_comment', 'type_params'} #set([f.name for f in fields(...
The code converts a `FunctionDef` object into a formatted string representation, extracting its label, return type, and body. It uses pattern matching to handle specific structures, raises an error for unsupported cases, and constructs a string with converted components. The main task is transforming function definitio...
def convert_def(df): match df: case utils.FunctionDef(label, [], body, _, rtyp, _): info = convert_info(df) return (f"(Def '{label_name_(label)} '() '{convert_type(rtyp)}" f" {info} {convert_body(body)})") case _: raise Exception('convert_def: ...
def convert_info(node): all_fields = set(vars(node)) # TODO: make sure "node" is a dataclass so that we don't have to hard code # c_fields c_fields = {'body', 'defs', 'name', 'args', 'decorator_list', 'returns', 'type_comment', 'type_params'} #set([f.name for f in fields(...
The function `convert_ast` converts an x86 program abstract syntax tree (AST) into a standardized string representation. It handles two main cases: programs with definitions (`X86ProgramDefs`) and those with a body (`X86Program`). For each case, it recursively converts components using helper functions (`convert_def`, ...
def convert_ast(x86program): info = convert_info(x86program) match x86program: case X86ProgramDefs(defs): converted_defs = ' '.join([convert_def(df) for df in defs]) return f"(X86ProgramDefs {info} (list {converted_defs}))" case X86Program(body): return f"(X86...
def showBoard(self): # p1: x p2: o for i in range(0, BOARD_ROWS): print('-------------') out = '| ' for j in range(0, BOARD_COLS): if self.board[i, j] == 1: token = 'x' if self.board[i, j] == -1: ...
The code simulates a two-player game (e.g., tic-tac-toe) over a specified number of rounds, tracking wins and draws for each player. It alternates turns between Player 1 and Player 2, who select moves based on available positions. After each move, the game checks for a win or draw, updates counters, and resets the game...
def play(self, rounds=100): crossWins = 0 zeroWins = 0 draw = 0 for i in range(rounds): if i % 10000 == 0: print("Rounds {}".format(i)) while not self.isEnd: if self.printBoard: self.showBoard() #...
def leave_one_out_x_valid(data): #performs leave out out validation, gets accuracy val = [] #values from nearest neighbors classType = [i[0] for i in data] #puts classifier in array for i in range(len(data)): #loop through data to clean exp tempData = [] data_a...
The code presents a menu for feature selection in a classification project. It prompts the user to select a dataset and an algorithm (Forward Selection or Backward Elimination). After loading the data, it calculates the dataset's feature count and instances. The chosen algorithm is executed, measuring runtime and accur...
def menu(): print('Project 2: CS170 Feature Classification - Brayan Montiel\n') #shortcut paths for assigned files small19 = './Ver_2_CS170_Fall_2021_Small_data__19.txt' large13 = './Ver_2_CS170_Fall_2021_LARGE_data__13.txt' #choose which dataset to run - assuming no incorrect user input file...
def update_trajectory_record(self): point = [0,0] point[0] = int(np.floor(self.grid_size/2) - self.resolution * self.odom.pose.pose.position.x) point[1] = int(np.floor(self.grid_size/2) - self.resolution * self.odom.pose.pose.position.y) self.trajectory_record.append(point) def qtrn_msg_...
This code processes odometry messages to navigate a robot along a predefined path. It checks the robot's state, updates trajectory data, calculates orientation and angular error relative to waypoints, and adjusts movement (straight or corrective) to align with the path. When reaching a waypoint, it advances to the next...
def odom_callback(self, msg): self.odom = msg if (self.state == 'plotting'): print('plotting') return if (len(self.path) == 0): print(len(self.path)) return self.update_trajectory_record() if (self.path_index != len(self.path)): ...
def Setup_Tour(self): tour = [] # Start with random point tour.append(random.choice(self.cities)) # Find next city base on probability for i in range(self.nb_cities - 1): tour.append(self.Find_Next(self.cities.index(tour[-1]), tour)) return tour def get...
This code implements an Ant Colony Optimization (ACO) algorithm to solve the Traveling Salesman Problem (TSP). It initializes a pheromone matrix, iteratively generates ant tours, calculates their lengths, updates pheromones based on tour quality, and tracks the best tour found. The algorithm runs for a specified number...
def execute(self): # Initialize pheromone matrix self.matrix = np.ones((self.nb_cities, self.nb_cities)) best_tour = None best_length = float('inf') for _ in range(self.nb_iters): # Initialize tours for all of ants ant_tours = [] for ...
def update_time(factors: dict): factors["utc_now"] = pytz.utc.localize(datetime.utcnow()) factors["cst_now"] = factors["utc_now"].astimezone(pytz.timezone("America/Chicago")) return None def check_inventory(factors: dict): try: page_html = get_page_html(factors) if check_item_in_stock(pa...
The main task of the code is to continuously monitor and update system factors (e.g., time, inventory, failures) in an infinite loop. It initializes timezone-aware timestamps, tracks daily failures, and periodically executes functions to update status, check inventory, and calculate delays between iterations using `tim...
def main(): factors = dict() factors["time_started"] = pytz.utc.localize(datetime.utcnow()).astimezone( pytz.timezone("America/Chicago") ) factors["daily_failures"] = 0 while True: update_time(factors) check_inventory(factors) update(factors) # check how lon...
def load_model(self): latest = tf.train.latest_checkpoint(self.checkpoint_dir) print(latest) if latest != None: logging.info('load model from {}'.format(latest)) self.last_epoch = int(latest.split('-')[-1]) self.checkpoint.restore(latest) def train_step(self, ...
The code trains a machine learning model over multiple epochs, iterating through training and validation datasets. It computes batch loss, logs training progress, evaluates validation accuracy, saves checkpoints for best performance, and records metrics using TensorFlow summaries. The loop tracks total loss, computes v...
def train(self): self.load_model() for epoch in range(self.last_epoch, hparams.max_epochs): start = datetime.now() total_loss = 0 # train each batch in dataset sum_samples = 0 for batch, (batch_input, batch_target) in enumerate(self.train_data...
def _initialize_kernel(self): root_piece = self._parents[0].pieces[0] self._put_piece_to_kernel(root_piece.id, (0, 0)) def add_piece_candidate(self, piece_id, orientation, position): shared_piece = self._get_shared_piece(piece_id, orientation) if self._is_valid_piece(shared_piece): ...
This code processes candidate puzzle pieces in priority order, placing them into a kernel structure while avoiding position conflicts. It uses a priority queue to select pieces, skips occupied positions, and recursively adds new candidates when pieces are already placed, continuing until all candidates are evaluated.
def run(self): self._initialize_kernel() while len(self._candidate_pieces) > 0: _, (position, piece_id), relative_piece = heapq.heappop(self._candidate_pieces) if position in self._taken_positions: continue # If piece is already placed, find new pie...
def swap(self, index1, index2): tmp_node = self.queue[index1] # Swaps nodes self.queue[index1] = self.queue[index2] self.queue[index2] = tmp_node # Syncs index_table self.index_table[self.queue[index1].node_id] = index1 self.index_table[self.queue[index2].node_i...
This function removes the minimum element from a priority queue implemented as a min-heap. It swaps the root (minimum) with the last element, removes the swapped minimum, and restores the heap structure by bubbling down the new root element. The operation maintains O(log|V|) time complexity for the bubble-down step and...
def delete_min(self): # Swap min with last self.swap(0, self.get_last_index()) # Remove min min_dist_node = self.queue.pop() self.index_table.pop(min_dist_node.node_id) # Bubble last down, Time: O(log|V|), Space: O(log|V|) self.bubble_down(0) # Return m...
def generate_paths(self): self.paths = [] self.next_steps = [] for robot_id in range(self.number_of_robots): self.assign_goal(robot_id) conflicts = [self.robot_positions,self.next_steps] # print(conflicts) path = a_star.main(self.forest,self.robot_...
The main task of the code is to advance a simulation by one time step, incrementing the time counter, generating paths, executing movement logic, and triggering activity-related processes. This method orchestrates sequential updates to simulate dynamic behavior in a system, likely for pathfinding, motion, or event-driv...
def step(self): self.time_steps += 1 self.generate_paths() self.move() self.activity()
def load_map(file_name): map_path = '\\' + file_name dir_path = os.path.abspath(os.path.dirname(__file__)) path = dir_path + map_path map_array = np.load(path) return map_array def collisions_calc(collisions): if collisions != None: flat_list = flatten_list(collision...
This code initializes a map for robot navigation by loading obstacle data, defining collision boundaries, and setting up parameters like resolution and robot radius. It processes input maps (either file paths or arrays), generates obstacle coordinates, calculates collision areas, and prepares motion models for pathfind...
def __init__(self, file = 'map30.npy', robot_radius = 1, collisions = None): self.nodecount = 0 self.resolution = 1 self.rr = robot_radius if type(file) == str: self.map_array = load_map(file) self.obstacle_map = self.map_array.astype(np.int32).tolist() ...
def get_shortest_path(self, origin, destination, start_time, end_time, day_of_week, week_of_year, threshold=None, wait_time=0, subgraph=None, _prev_trip_id=None): """ Returns the trip with the shortest time (weight) from u to v by implementing the Dijktra's algorithm. T...
This function computes the K shortest paths from origin to destination, considering time constraints and graph structure. It iteratively generates alternative paths by modifying the graph to avoid cycles, using reversed or standard graphs based on start_time. It handles long journeys by selectively choosing spur nodes,...
def _get_k_shortest_path_reversed(self, origin, destination, start_time, end_time, day_of_week, week_of_year, threshold, wait_time, K, only_spur_transfer_nodes=True, remove_nodes=False): assert K > 0, "Cannot have a negative value for k...
def _get_k_shortest_path_reversed(self, origin, destination, start_time, end_time, day_of_week, week_of_year, threshold, wait_time, K, only_spur_transfer_nodes=True, remove_nodes=False): assert K > 0, "Cannot have a negative value for k...
This function implements Yen's algorithm to find the K shortest paths between origin and destination stations, considering time constraints, confidence thresholds, and transfer wait times. It uses Dijkstra's algorithm internally, handles reversed paths when start_time is None, and manages inaccessible nodes/edges durin...
def get_k_shortest_path(self, origin, destination, start_time, end_time, day_of_week, week_of_year, threshold, wait_time=0, K=1, only_spur_transfer_nodes=True, remove_nodes=False): """ Returns K shortest trips from u to v by implementing the Yen's ...
def find_winning_moves(self, player): winning_moves = [] #for loops iterate over all the possible positions on the board. #The range(3) function generates a sequence of numbers from 0 to 2, which represents the rows and columns of the board. for row in range(3): for col in range(3): ...
The function determines the computer's move in a game by prioritizing: 1) Blocking the player's immediate win, 2) Securing its own win if available, 3) Using bidirectional search for optimal moves, and 4) Falling back to random moves when no strategic options exist. It ensures adaptive gameplay by checking winning poss...
def make_computer_move(self): #returns a list of potential moves that would result in a win for the player player_wins = self.find_winning_moves('X') if player_wins: # it means that the player has a winning move available. # The code then randomly selects one of the winn...
def generate_sudoku(difficulty): # Create an empty Sudoku board board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)] #This line calls the solve_sudoku function to solve the Sudoku puzzle on the empty board. # This ensures that the initial state of the puzzle is a valid solution. solve_sudoku(board) ...
The main task of the code is to generate a Sudoku puzzle based on a user-specified difficulty level (1-5), display the initial unsolved board, solve the puzzle using a solver function, and print the completed solution. The code uses input for difficulty, creates a Sudoku grid, makes a deep copy to preserve the original...
def main(): # Generate a Sudoku puzzle with the desired difficulty level difficulty = int(input("Enter the difficulty level (1-5): ")) board = generate_sudoku(difficulty) # Print the initial Sudoku board print("Initial Sudoku Board:") print_board(board) # Solve the Sudoku puzzle ...
def print_board(self): for row in self.board: print('|'.join(row)) print('-' * 5) def check_winner(self, player): for row in self.board: if row[0] == row[1] == row[2] == player: return True for col in range(3): if self.board[0][col...
The main task of the code is to run a game loop where a player and computer alternate turns in a tic-tac-toe game. It checks for win/draw conditions after each move, displays the board, and handles user input for player moves while the computer makes automated moves. The loop terminates when a player or computer wins, ...
def play(self): while True: self.print_board() if self.check_winner('X'): print("Game over. Player wins!") break if self.check_winner('O'): print("Game over. Computer wins!") break if len(self.get_...
def print_board(self): for row in self.board: print('|'.join(row)) print('-' * 5) def check_winner(self, board): for row in board: if row[0] == row[1] == row[2] != ' ': return row[0] for col in range(3): if board[0][col] == board[1...
This code implements a game loop for a Tic-Tac-Toe game, alternating between human and computer turns. It continuously displays the board, checks for a winner after each move, and ends when a player wins, printing the result. The human inputs their move coordinates, while the computer generates its move automatically.
def play(self): while True: self.print_board() if self.check_winner(self.board) is not None: print("Game over. {} wins!".format(self.check_winner(self.board))) break if self.current_player == 'X': row = int(input("Enter the ro...
def process(self, op: Operation): success = False if (op.operation == Command.READ.value): success = self.process_read(op) elif (op.operation == Command.WRITE.value): success = self.process_write(op) elif (op.operation == Command.COMMIT.value): success...
The main task of the code is to execute a given operation, process its success or failure, and handle transaction aborts by updating timestamps and reprocessing related operations. It prints version control status, runs the operation, and if processing fails, aborts the transaction, updates timestamps, clears created i...
def run_operation(self, op: Operation): print("=======================================") print("Current version control:") print(self.version_control) print(f"Run operation: {op.format()}") success = self.process(op) if success: return aborted_ids = ...
def prepare_item(self, op: Operation): if (op.operation != Command.COMMIT.value and op.item.label not in self.version_control.map): new_item = Item(op.item.label) self.version_control.add_new_version(new_item) def prepare(self, op: Operation): trx = self.find_tran...
The code processes a file line-by-line, creating Operation objects from each line. It prepares these operations, prints version control information, and sequentially executes each operation. The main task involves reading input data, initializing operations, and managing their execution in a controlled workflow.
def run(self): while True: str = self.file_handler.next_line() if str == '': break self.operations.append(Operation(str)) for op in self.operations: self.prepare_item(op) print(self.version_control) for op in self.operatio...
def on_init(self): if (key := self.repository.get_cache_key("API_KEY")): openai.api_key = key else: dialog = ApiKeyDialog(self) if dialog.exec() == QDialog.Accepted: openai.api_key = dialog.api_key() if dialog.save_api_key(): ...
The main task of the code is to initialize a GUI-based OpenAI API client application. It sets up a window with a menu bar, input prompt area, generate button, chat output display, and a sidebar for managing saved prompts. The interface includes event handlers for user interactions like generating text and accessing set...
def __init__(self, repository: Repository): self.__repository = repository self.conversation_id = self.repository.get_cache_key("LAST_CONVERSATION_ID") or 0 super().__init__() self.setWindowTitle("OpenAI API Client") menu_bar = QMenuBar(self) self.setMenuBar(menu_bar) ...
def _get_html_content(self): """ getting google search result page's html content via bs4 :return: html context or exception """ try: r = requests.get(url=self._url, headers=self.user_agent) if r.ok: return BeautifulSoup(r.content, ...
The code's main task is to retrieve HTML content, parse it using either mobile or web-specific parsing methods based on a flag, handle parsing errors, and return the parsed results.
def run(self): """ runner. :return: """ html_text = self._get_html_content() try: if self._is_mobile == 1: self._parse_mobile_content(html_text) else: self._parse_web_content(html_text) except Exception as ...
def log_prior(self, k_index, mf_index, mf_value): return self.log_prior_y(k_index) + self.log_prior_xy(k_index, mf_index, mf_value) def log_conditional(self, k_index, mf_index, mf_value, features): # features here is an array sum_condition = 0 ''' How to remove the loop ...
The code computes the numerator for a probabilistic model by summing log-prior and log-conditional probabilities for each feature, then applying logsumexp to stabilize the computation. It initializes an array, iterates over features to calculate combined log probabilities, and returns the aggregated result.
def numerator(self, k_index, features): join_array = np.zeros((self.feature_number),dtype=np.double) for i in range(self.feature_number): value_index = self.dict_list[i][features[i]] join_array[i] = self.log_prior(k_index, i, value_index) + self.log_conditional...
def checkdone(self): for r in range(self.size): for c in range(self.size): if self.board[r][c] == 0: return 0 return 1 def sanitycheck(self): if np.any(self.board > self.size): return 0 for x in range(self.size): row = self.board[x] res = self.checkline(row) if res == 0: return 0 t...
The code checks if a puzzle is solved by verifying `checkdone()` and `sanitycheck()`. If both pass, it prints a success message, displays the board, and returns `True`. Otherwise, it returns `False`.
def isdone(self): done = self.checkdone() sc = self.sanitycheck() if done and sc: print("\n\nSolved! Hooray!") self.printboard() if self.interactive: self.D.spin() return True else: return False
def choose_size(self): m4 = '04' m9 = '09' m16 = '16' w,h = self.large_font.size(m4) # I used monospaced so they should all be the same s = (w if w>h else h) print(s) spacing = (self.width - 2*self.buff - 3*s)/2. print(spacing) four = Msg('04', self.buff, self.width/2, self.purple) #{'msg':'4', 'w':se...
This code initializes a Pygame window for a Sudoku solver, setting up the display, fonts, colors, and grid structure. It creates a playable Sudoku board with visual elements like gray cell boxes, black grid lines, and colored message indicators for solving states. The main task is to establish the graphical interface a...
def __init__(self, size): pygame.init() self.fps = 500 self.fpsClock = pygame.time.Clock() self.width = int((screen_width)/3.) print(f"WINDOW WIDTH: {self.width}") self.window = pygame.display.set_mode((self.width, (int(self.width*1.2)))) pygame.display.set_caption("Sudoku Solver :)") self.done = False ...
def get_introspect_token(self): return ( cache.get(self.make_introspect_cache_key()) or self.do_get_introspect_token() ) def do_get_introspect_token(self): response = requests.post(self.oauth2_login_url, data={ 'grant_type': 'client_credentials', '...
This function validates an access token via OAuth2 introspection by sending a POST request to a specified URL. It retrieves user details, scopes, and expiration time from the response, caches the user data with expiration and mutex flags, and returns the user object. If unauthorized (401), it attempts to refresh the in...
def do_get_user_by_access_token(self, access_token): response = requests.post( self.oauth2_introspect_url, data={'token': access_token}, headers={ 'Authorization': 'Bearer {}'.format( self.get_introspect_token()) } ) ...
def check_funds(self, amount): if self.get_balance() < amount: return False return True def withdraw(self, amount, description = ""): if not self.check_funds(amount): return False self.ledger.append({"amount": -amount, "description": description}) return True def category_name(self): ...
This code transfers a specified amount from the current category to another category, ensuring sufficient funds. It performs a withdrawal from the current category and a deposit into the target category, updating both with transfer-related messages. It returns True if successful, False otherwise.
def transfer(self, amount, category): if not self.check_funds(amount): return False self.withdraw(amount, "Transfer to " + category.category_name()) category.deposit(amount, "Transfer from " + self.category_name()) return True
def load_data(filename): """ Load gene and trait data from a file into a dictionary. File assumed to be a CSV containing fields name, mother, father, trait. mother, father must both be blank, or both be valid names in the CSV. trait should be 0 or 1 if trait is known, blank otherwise. """ da...
The code computes the probability of each person having 0, 1, or 2 genes and having/manifesting a trait, based on input data. It iterates through all possible gene/trait combinations, calculates joint probabilities using the joint_probability function, updates probabilities in a dictionary, normalizes them to sum to 1,...
def main(): # Check for proper usage if len(sys.argv) != 2: sys.exit("Usage: python heredity.py data.csv") people = load_data(sys.argv[1]) # Keep track of gene and trait probabilities for each person probabilities = { person: { "gene": { 2: 0, ...
def missing_ranks(p,q): ranks_pq_dir = os.path.join(ranks_dir, "map_{}_{}".format(p,q)) matrices_md = set(multidegrees(p,q)) ranks_md = set() for mdFile in glob.glob(os.path.join(ranks_pq_dir, "*.ranks")): if os.path.getsize(mdFile)==0: os.remove(mdFile) continue ...
The function generates a dictionary mapping (p,q) pairs to their corresponding rank data from .ranks files, provided no missing ranks exist. It checks each (p,q) pair for missing ranks, breaks if found, otherwise constructs the dictionary by reading .ranks files in a directory structure. Returns False if missing ranks ...
def make_rank_dict(matToComp): rankDict={} for (p,q) in matToComp: mr = missing_ranks(p,q) if len(mr)>0: break else: rankDict[(p,q)] = {} ranks_pq_dir = os.path.join(ranks_dir,"map_{}_{}".format(p,q)) for mdFile in gl...
def getUserCity(userid): if "User2City" not in setting: user2city= getUserLocation() for user in user2city: print(" | user2city | '{}' -> '{}'".format(user, user2city[user])) else: user2city=setting["User2City"] if userid in user2city: return user2city[userid] ...
The function `predict_user` generates a user's POI (Point of Interest) itinerary using a BERT model, adhering to a time constraint. It initializes context with user data, POI embeddings, and location details, then iteratively predicts the next POI sequence while ensuring the total duration stays within the allowed seco...
def predict_user(bertmodel, pois, user, seqid, p0, pn, t0, tn, seconds, path): bertlog.debug("LINE:%d ============================================", LINE()) bertlog.debug("LINE:%d, -- predict_user( %s, %d,%d,%s,%s, seconds allowed:%d, path:%s )", LINE(), user, p0,pn,t0,tn , seconds, str(path)) bertlog.debu...
def getUserCity(userid): if "User2City" not in setting: user2city= getUserLocation() for user in user2city: bertlog.info(" | user2city | '%s' -> '%s'", user, user2city[user]) else: user2city=setting["User2City"] if userid in user2city: return user2city[userid] else: ...
The function `predict_user` generates a user's itinerary (sequence of POIs) using a BERT model, constrained by a time limit. It initializes with user data, POI embeddings, and a starting POI pair (p0, pn). The loop iteratively predicts subsequent POIs, updating the sequence while ensuring the total duration (calculated...
def predict_user( bertmodel, pois, user, seqid, p0, pn, t0, tn, seconds, path): bertlog.debug("LINE:%d ============================================", LINE()) bertlog.debug("LINE:%d, -- predict_user( %s, %d,%d,%s,%s, seconds allowed:%d, path:%s )", LINE(), user, p0,pn,t0,tn , seconds, str(path)) bertlog.deb...
def reviews_sentiments(city, pois): #poiid_comments = read_reviews(city, pois) #for poiid in poiid_comments: # comments = poiid_comments[poiid] # print (comments) # assert(0) import torch from transformers import pipeline import statistics sentiment_analysis = pipeline("se...
The main task of the code is to train and evaluate a BERT-based model for predicting user preferences in a city's points-of-interest (POIs) using sequential visit data. It loads datasets, preprocesses POI reviews, and trains the model iteratively over specified epochs. At key intervals, it evaluates model performance o...
def main(bert, city, epochs, USE_CUDA=True, args=None): # read in from spmf.sh / ### for city in ['Buda','Delh','Edin','Glas','Osak','Pert','Toro'] #e = args.epochs (pois, userVisits, evalVisits, testVisits) = load_dataset( city, DEBUG=1 ) bertlog.info( " [[[[[ RUN PARAMETERS : %s ]]]]]", st...
def distance_dict(pois): allpois = pois['poiID'].unique() poi_dict = dict() dist_mat = get_distance_matrix(pois) poi_dict_p = dict() for p in allpois: ### allpois[p] -> [p1:dist1, p2:dist2 ,....] by distance for q in allpois: if p != q: pq_dist = dist_mat[...
The main task of the code is to train and evaluate a BERT-based model for predicting user preferences in POI (Point of Interest) visits across different cities. It loads datasets, processes user visit data, computes statistical metrics (e.g., duration, photo counts), trains the model iteratively, and evaluates its perf...
def main(bert, city, epochs, USE_CUDA=True, args=None): import torch torch.multiprocessing.set_sharing_strategy('file_system') os.environ["TOKENIZERS_PARALLELISM"] = "False" # read in from spmf.sh / # for city in ['Buda','Delh','Edin','Glas','Osak','Pert','Toro'] (pois, userVisits, evalVisits,...
def add_ec2_security_group(self): """ Add EC2 Security Group """ if not self.security_group: vpc = self.get_vpc() security_group_name = f"{self.stack_name}-sg" self.security_group = ec2.SecurityGroup( self, id=security_group_name, vpc=v...
The code creates an internet-facing application load balancer (ALB) with a dynamically generated name, associates it with a VPC, and configures security groups. It checks if public access is allowed, restricting the ALB to whitelisted IPs if disabled. The ALB is then assigned the configured security group and returned.
def get_load_balancer(self): load_balancer_name = f"{self.stack_name}-load-balancer" load_balancer = elb.ApplicationLoadBalancer( self, id=load_balancer_name, vpc=self.vpc, internet_facing=True ) load_balancer_security_group = self.add_ec2_security_group() if not se...
def add_ecr_image(self, repo_name: str): ecr_repo_id = f"{repo_name}-ecr-repo" repo = ecr.Repository.from_repository_name( self, id=ecr_repo_id, repository_name=repo_name ) return ecs.ContainerImage.from_ecr_repository(repo) def add_fargate_api_task( self, repo_name,...
This code provisions an AWS Fargate service with a load balancer, configuring auto-scaling, health checks, and IAM permissions. It creates an ECR container image, sets up a task definition with specified CPU/memory, attaches a managed policy, enables remote execution, and outputs the load balancer's DNS name for servic...
def add_load_balancer(self, parameters: Mapping[str, Any]): desired_count = parameters.get("desired_count") repo_name = f"{self.stack_name}-ecr-container" memory_limit = parameters.get("memory_limit") cpu = parameters.get("cpu") image = self.add_ecr_image( repo_name=...
def add_role(self, iam_parameters: Mapping[str, Any]): """ Add an IAM role to the stack """ if not self.role: managed_policies = [] for policies in iam_parameters.get("managed_policies"): for policy_name, policy_arn in policies.items(): ...
The `build` method constructs AWS resources by iterating through a list of resources, determining each resource's type, and invoking corresponding methods (e.g., `add_role`, `add_vpc`) to create or configure the resource. It uses parameters from each resource definition where applicable, such as for IAM roles, VPCs, RD...
def build(self): for resource in self.resources: resource_type = resource.get("type") parameters = resource.get("parameters") if resource_type == AWSResources.IAM_ROLE.value: self.add_role(parameters) elif resource_type == AWSResources.VPC.value: ...
def render_screen(self) -> None: self.screen.fill((0,0,0)) self.boxes.draw(self.screen) for player_group in self.player_groups: player_group.paint(self.screen) display.flip() def is_over(self) -> None: if len(self.player_groups) == 1: return True r...
(This function manages a game loop, handling user input for player movement via arrow keys, rendering the screen, and updating game state. It exits when the game ends or ESC is pressed. If auto-play is enabled, it automatically updates and renders without manual input. Returns 10 if no human player remains, otherwise t...
def start(self,clock) -> int: running = True self.render_screen() while running: if self.is_over(): break if not self.auto_play: for event_ in pg_event.get(): if event_.type == KEYUP and event_....
def is_train_test_file_exists(self) -> bool: try: logging.info(f"Checking if train & test data is available") is_train_file_exist = False is_test_file_exist = False train_file_path = self.data_ingestion_artifact.train_file_path test_file_path = self.d...
The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema compliance, and detecting data drift. If successful, it returns a `DataValidationArtifact` with validation status, schema/report file paths, and a success message. Exceptions are logged and re-raised as...
def initiate_data_validation(self) -> DataIngestionArtifact: try: self.is_train_test_file_exists() self.vaidate_datatset_schema() self.is_data_drift_found() data_validation_artifact = DataValidationArtifact(schema_file_path=self.data_validation_config.schema_fil...
def page_1(): st.title("Colorful Demo App") st.subheader("This app allows color-blind people use their electronic devices as no color-blind people") st.text("We use OpenCV and Streamlit for this demo") st.subheader("Our main goal is to find your customise color filter") def page_2(): # "st.session_s...
The main task of the code is to create a Streamlit app with a sidebar menu for navigating three pages. It stores the selected page in session state, initializes a random number for Page 2, sets a test value, and renders the corresponding page function.
def main_loop(): st.set_page_config(page_title="Colorful Demo App", page_icon="👋") st.session_state.page_select = st.sidebar.radio('Pages', ['Page 1', 'Page 2', 'Page 3']) st.session_state.page_select == 'Page 1' if st.session_state.page_select == 'Page 1': page_1() if st.session_state.pa...