dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def controller(self): v = 4 # Moving 1m/sec w = pi/4 # Rotating at pi/2 rad/s # Two conditions must be met to go straight; # (1) We are past the initial time (say past 2 seconds) # (2) The robot's are facing straight _,_, currentHead1 = self.state1 x2,...
The `animate` function updates a visualization of robotic movement and particle filtering. It clears prior data, advances the bots' positions via `controller()`, updates particle distributions based on timing logic, and redraws bot paths, particle locations, headings, and covariance ellipses. It synchronizes plot eleme...
def animate(self, i=None): # Clearing what we previously had self.bots = [] # For plotting bot self.sensors = [] # For plotting sensors self.particleHeadings1 = [] # For plotting bot1 particle headings self.particleHeadings2 = [] ...
def controller(self): v = 4 # Moving 1m/sec w = pi/4 # Rotating at pi/2 rad/s # Two conditions must be met to go straight; # (1) We are past the initial time (say past 2 seconds) # (2) The robot's are facing straight _,_, currentHead1 = self.state1 x2,...
This code runs a simulation loop without matplotlib animations, primarily for debugging. It executes the controller, checks if sufficient time has passed to update particles, increments the measurement time if not, and plots ellipses for visualization. The core tasks involve controlling the simulation, timing particle ...
def run(self): """ Use this code to run without matplotlib animations. Mostly for debugging purposes. """ self.controller() if self.measureTime > self.updateDelay: self.updateParticles() else: self.measureTime += self.dt ...
def controller(self): v = 4 # Moving 1m/sec w = pi/4 # Rotating at pi/2 rad/s xPrior = self.state self.state = self.sample_motion_model_velocity([v,w], xPrior) self.prevStates.append(xPrior) # Only storing after we have left that state. # Let's also move thos...
The main task of the code is to animate a robot's movement and particle filter visualization by clearing previous data, updating bot positions, managing particle predictions, rendering sensor paths, covariance ellipses, and time tracking, while handling conditional bot-stealing logic to ensure dynamic and accurate real...
def animate(self, i=None): # Clearing what we previously had self.bots = [] # For plotting bot self.sensors = [] # For plotting sensors self.particleHeadings = [] # Fpr plotting the particle headings self.line.set_data([],[]) # Fo...
def controller(self): v = 4 # Moving 1m/sec w = pi/4 # Rotating at pi/2 rad/s xPrior = self.state self.state = self.sample_motion_model_velocity([v,w], xPrior) self.prevStates.append(xPrior) # Only storing after we have left that state. # Let's also move thos...
The code's main task is to execute a simulation or process without matplotlib animations, primarily for debugging. It calls a controller, updates particles based on timing checks, triggers a one-time "bot stealing" action if conditions are met, and plots ellipses. The method manages timing delays, particle updates, and...
def run(self): """ Use this code to run without matplotlib animations. Mostly for debugging purposes. """ self.controller() if self.measureTime > self.updateDelay: self.updateParticles() else: self.measureTime += self.dt ...
def guess_cauth_id(self): return self.get_pubtkt_infos().get('cid') def check_identity(self, cauth_id): try: if self.guess_cauth_id() != cauth_id: abort(401, 'Wrong user') else: return True except Exception: logger.exception("Co...
This function generates an API key for a user identified by `cauth_id` (or guessed if unspecified), validates the user's identity, associates the key with the user's services, and returns the key. If an existing API key exists for the user, it raises a 409 conflict error.
def post(self, cauth_id=None): if not cauth_id: cauth_id = self.guess_cauth_id() self.check_identity(cauth_id) username = self.guess_username() try: key = db.create_api_key(cauth_id) logger.debug('Created API Key for cauth_id %s' % cauth_id) ...
def guess_cauth_id(self): return self.get_pubtkt_infos().get('cid') def check_identity(self, cauth_id): try: if self.guess_cauth_id() != cauth_id: abort(401, 'Wrong user') else: return True except Exception: logger.exception("Co...
The code deletes an API key associated with a specified or guessed `cauth_id`, verifies identity, removes the key from the database, and deletes it from linked services. It logs the action and returns a 204 No Content status.
def delete(self, cauth_id=None): if not cauth_id: cauth_id = self.guess_cauth_id() self.check_identity(cauth_id) db.delete_api_key(cauth_id) username = self.guess_username() for service in self.services: service.delete_api_key(username) logger.debu...
def get_default_device(): """Pick GPU if available, else CPU""" if torch.cuda.is_available(): return torch.device('cuda') else: return torch.device('cpu') def to_device(data, device): """Move tensor(s) to chosen device""" if isinstance(data, (list, tuple)): return [to_device(...
The code identifies a bird species in an image by loading a pre-trained ResNet34 model, applying normalization statistics, and mapping model predictions to bird names via a JSON file. It returns the identified species.
def identify_bird(image): """ Identify a bird in an image. :param image: An image file. :return: The identified bird species. """ # Read JSON file containing bird labels and convert the content to a Python object with open('bird_map.json', 'r') as json_file: bird_name_map = json.lo...
def get_args(): parser = argparse.ArgumentParser("Launch a sweep of jobs") # positional arguments that need to be set for each sweep parser.add_argument("partition", type=str) parser.add_argument("j_name", type=str) parser.add_argument("file", type=str) parser.add_argument("qos", type=str) ...
The main task of the code is to orchestrate an experiment by parsing command-line arguments, setting up the experiment directory, and initiating a hyperparameter sweep or training process. It retrieves input parameters, configures the experiment environment, and triggers the execution of the specified task, likely invo...
def main(): args = get_args() args.exp_dir = setup(args) launch_sweep(args)
def save_model(self, idx_episode): safe_path = self.output_path + "/qnet" + str(idx_episode) + ".cptk" self.saver.save(self.sess, safe_path) # self.q_network.save_weights(safe_path) print("+++++++++ Network at", idx_episode, "saved to:", safe_path) def select_action(self, state, is_train...
The code trains a reinforcement learning agent by interacting with an environment, collecting experiences into a replay memory, updating the neural network parameters using sampled experiences, and periodically saving model weights. It employs epsilon-greedy policies for exploration, tracks metrics like reward and loss...
def fit(self, env, num_iterations, max_episode_length=None): """Fit your model to the provided environment. Its a good idea to print out things like loss, average reward, Q-values, etc to see if your agent is actually improving. You should probably also periodically save your network ...
def save_model(self, idx_episode): safe_path = self.output_path + "/qnet" + str(idx_episode) + ".h5" self.q_network.save_weights(safe_path) print("Network at", idx_episode, "saved to:", safe_path) def select_action(self, state, is_training = True, **kwargs): """Select the action based on...
The code trains a reinforcement learning model by interacting with an environment, collecting experiences in a replay memory, and updating the neural network parameters. It uses a decaying epsilon-greedy policy for action selection, tracks episode metrics, and periodically updates the target network. The process includ...
def fit(self, env, num_iterations, max_episode_length=None): """Fit your model to the provided environment. This is where you sample actions from your network, collect experience samples and add them to your replay memory, and update your network parameters. Parameters ...
def find_similar_images_knn(target_image_path, dataset_folder, similar_images=5): """ Find the most similar images to the target image in the dataset using KNN. Returns a list of tuples (image_path, distance). """ # Load or extract feature list if os.path.exists(feature_list_path): featu...
The main task of the code is to find similar images to a target image using KNN, save the results in a CSV file, and visualize them. It loads the target image from a specified folder, executes a KNN-based similarity search, stores the outcomes in CSV format, and generates plots of the similar images. The target image i...
def main(): target_image_path = os.path.join(data_folder, f'image_{target_image:04d}.jpg') # Adjust for 1-based indexing of images print(f'Finding similar images for image_{target_image:04d} using KNN') # Find similar images using KNN results = find_similar_images_knn(target_image_path, data_folder, ...
def ask_for_letter(self): letter = '' # we import the string module to give us access to an easy way to create a list of the entire alphabet while letter not in list(string.ascii_lowercase): letter = input("\nPlease guess a letter! (a..z): ").lower() return letter def update_...
The main task of the code is to handle a single turn in a guessing game. It processes a player's letter guess, updates the displayed word, tracks guesses, decrements remaining attempts if the letter is incorrect, and checks for win/loss conditions. If the game isn't over, it recursively continues to the next turn.
def play_turn(self): # a turn begins by asking a player for their guess letter = self.ask_for_letter() # update the word with the letter, maybe self.update_user_word(letter) # decrement the available guesses # unless the letter matches and it's not already in the @guess...
def set_mode(self): mode = '' while mode not in ['e', 'm', 'h']: mode = input("\nThis can be (e)asy, (m)edium or really (h)ard. The choice is yours: ") return mode def joined_user_word(self): return "".join(self.user_word) def play_turn(self): # a turn begins by askin...
The code initializes a Hangman game by loading words from a CSV file, setting game mode, selecting a random target word, tracking guesses, and starting the first turn. It configures the game state, including the hidden word representation, allowed attempts, and debug output if enabled.
def __init__(self, debug=False): # are we in debug mode? self.debug = debug # possible words, selected at random # self.words = { # 'e' : ['dog','cat','bug','hat','cap','lit','kin','fan','fin','fun','tan','ten','tin','ton'], # 'm' : ['plain','claim','brine','cri...
def fewest_candidate_cell(self, grid: list[int]) -> Optional[int]: """ return the empty cell with fewest possible candidate, by counting bits and find the cell with highest bits. It should pick the cell with most 1s in binary representation. >>> sudoku = Sudoku() >>> grid = [0b1...
The code recursively solves a puzzle (e.g., Sudoku) by selecting cells with the fewest possible candidates. It checks if a cell can accept a number, updates the grid, and recursively explores solutions. If no empty cells remain, it returns a valid solution. If a cell has no valid numbers, it backtracks. It collects all...
def naive_solve(self, grid: list[int]) -> list[str]: cell_to_try = self.fewest_candidate_cell(grid) if cell_to_try == None: # no empty cells. # i.e. a solution is found. solution = ''.join(str(-i) for i in grid) return [solution] bit = grid[cell_t...
def fewest_candidate_cell(self, grid: list[int]) -> Optional[int]: """ return the empty cell with fewest possible candidate, by counting bits and find the cell with highest bits. It should pick the cell with most 1s in binary representation. >>> sudoku = Sudoku() >>> grid = [0b1...
The code implements a recursive backtracking algorithm to solve a Sudoku puzzle by randomly selecting valid numbers for the cell with the fewest candidates. It checks for a complete grid, identifies the next cell with the least possible values, shuffles available options, and recursively attempts each choice until a so...
def random_solver(self, grid: list[int]) -> list[int]: """ randomly generate a complete sudoku grid from a partially filled grid """ next_cell = self.fewest_candidate_cell(grid) if next_cell == None: return grid bit = grid[next_cell] if bit == 2 ** se...
def validate_puzzle_string(self, puzzle: str) -> Result[bool, str]: """ Validate a string as a representation of Sudoku puzzle accept 0 or . to represent an empty cell DOES NOT check whether if it is a valid answer in Sudoku Return False for empty input >>> sudoku = Sudoku() ...
The code solves a Sudoku puzzle using backtracking. It validates the input puzzle string, maps it to a grid, checks for unsolvability, and employs a naive backtracking algorithm to find all valid solutions. If solvable, it returns the list of solutions; otherwise, it returns error messages for invalid inputs, unsolvabi...
def solve_puzzle(self, puzzle: str) -> Result[list[str], 'str']: """ solve a sudoku puzzle by backtracking. >>> puzzle1 = "123434122341412." >>> sudoku2x2 = Sudoku(width=2) >>> sudoku2x2.solve_puzzle(puzzle1) Ok(['1234341223414123']) >>> puzzle2 = "12343412.........
def random_digit_list(self) -> list[int]: """ return a random shuffled list of numbers allowed in a row/column/square >>> sudoku = Sudoku() >>> list1 = sudoku.random_digit_list() >>> len(list1) 9 >>> all((i in list1)for i in range(1, 9)) True >>> r...
The code generates a valid Sudoku solution by creating a random first row, filling the grid using a solver, and converting the result into a string of negative integers.
def generate_random_solution(self) -> str: """ Generate a random Sudoku grid which is a valid solution. """ first_row = self.random_digit_list() grid = [0 for _ in range(self.number_of_cells)] for (idx, number) in enumerate(first_row): grid = self.update_grid(...
def map_puzzle_to_grid(self, puzzle: str) -> list[int]: """ calculate the number candidates for each cell in a sudoku puzzle. valid numbers are represented by bits. e.g.: 0: all nums in 1-9 are valid 3: ( = 0b000000011) num 1 & 2 are not valid 511: (= 0b111111111)...
The code evaluates a Sudoku puzzle's difficulty by calculating a score combining two factors: (1) the sum of squared branching factors (Bi-1)² for each node, multiplied by 100, and (2) the count of initial empty cells. It first checks if the puzzle is solvable and has a unique solution. If not, it returns an error. The...
def evaluate_difficulty(self, puzzle: str, solution: str | None = None) -> Result[int, str]: """ Calculate a difficulty score of a puzzle using an algorithm in this article https://dlbeer.co.nz/articles/sudoku.html The difficulty score consists of two parts: 1. For the branching factor B...
def trainig(marketSymbol:MarketSymbol.BTC, train_dataset, selected_features, agent_type=AgentType.A2C, timesteps=5000, learning_rate=7e-4, dicount_factor=0.9): # Create trading A2C agent if agent_type is AgentType.A2C: env_train = CryptoTradingDiscretEnv(train_dataset, marketSymbol.name, selected_featur...
The main task of the code is to perform hyperparameter tuning for reinforcement learning agents (DQN and Multi-Agent) in cryptocurrency trading scenarios. It systematically tests combinations of learning rates, discount factors, and training time steps across multiple datasets (BTC, ETH, LTC), evaluates performance met...
def hyper_paramters_tuning(): timesteps = 5000 epoch = 100000 balance = 100000 # Create feature selection agent datasets_files = ["data/processed/Binance_BTCUSDT_minute_processed.csv", "data/processed/Binance_ETHUSDT_minute_processed.csv", "data/processed/Binance_LTCUSDT_minute_processed.cs...
def trainig(marketSymbol:MarketSymbol.BTC, train_dataset, selected_features, agent_type=AgentType.A2C, timesteps=5000, learning_rate=7e-4, dicount_factor=0.9): # Create trading A2C agent if agent_type is AgentType.A2C: env_train = CryptoTradingDiscretEnv(train_dataset, marketSymbol.name, selected_featur...
The code runs DQN and multi-agent trading strategies on cryptocurrency datasets, using predefined features and hyperparameters, to evaluate performance metrics and save results in CSV/text files for BTC, ETH, and LTC markets.
def run_trading_agents(feature_seleted="_features"): datasets_files = ["data/processed/Binance_BTCUSDT_minute_processed.csv", "data/processed/Binance_ETHUSDT_minute_processed.csv", "data/processed/Binance_LTCUSDT_minute_processed.csv"] marketSymbols = [MarketSymbol.BTC, MarketSymbol.ETH, MarketSymbol.LTC] s...
def treePolicy(self, node): while not node.isTerminal: if not node.isFullyExpanded(): return self.expand(node) else: node = self.getBestChild(node, self.explorationConstant) return node def defaultPolicy(self,state): while len(state.feature...
This code performs a simulation step in a Monte Carlo Tree Search (MCTS) algorithm. It selects a node via `treePolicy`, categorizes it in `self.level` by its feature subset size, evaluates it with `defaultPolicy` to obtain a reward, and then backpropagates this reward to update the tree. The main task is to explore and...
def simulate(self): node = self.treePolicy(self.root) m = node.state.feature_subset if len(m) not in self.level.keys(): self.level[len(m)] = [node] else: self.level[len(m)].append(node) rolloutReward = self.defaultPolicy(node.state) mReward = rollout...
def udf_drop_event_keys(drop_event_keys: list[str]): return udf(lambda value: drop_event_keys_func(value, drop_event_keys), BinaryType()) def flatten_json(column: dict[str, Any]) -> str: flattened = flatten(json.loads(column)) return bytearray(json.dumps(flattened).encode()) def encode_json(column: dict[str...
The main task of the code is to process a Kafka stream by transforming a DataFrame with metadata enrichment, schema information, and event processing based on configuration parameters. It adds timestamps, renames columns, hashes payloads, and encodes JSON events, returning a processed DataFrame for further streaming op...
def processor(spark: SparkSession, df: DataFrame, configuration_set: dict[str, Any], logger: Any) -> pyspark.sql.streaming.StreamingQuery: drop_event_keys = configuration_set.get("drop_event_keys") if drop_event_keys: df = df.withColumn("value", udf_drop_event_keys(drop_event_keys)(col("value"))) el...
def name( ) -> None: global base_dictionary base_dictionary["name"] = input("What is the name of the item? ") return def type( ) -> None: global base_dictionary while True: item_type = input("What is the item type? ") item_type.lower() if item_type in VALID...
The code's main task is to repeatedly generate and display a dictionary entry by prompting the user for inputs through multiple functions (name, type, rarity, etc.), then offering to create another entry. It uses a loop to reset the dictionary, collect data, and print results, with user confirmation to repeat the proce...
def main( ) -> None: global base_dictionary while True: base_dictionary = {} name() type() rarity() homebrew() details() attunement() variations() print(base_dictionary) user_input = input("Want to do another one? ...
def rdt_1_0_wait(self): self.txt_command_output.insert(tk.END, "Enter stop to stop simulation \n") if self.command_input.get() == "stop": return self.stop_simulation() self.txt_command_output.delete("1.0", "end") self.txt_command_output.insert(tk.END, "rdt_send(data)\n") ...
This function processes user input commands to trigger specific simulation scenarios. It checks the input against predefined strings like "rdt 1.0 normal", "stop", or various "rdt 3.0" and "tcp" modes, then calls corresponding methods such as rdt_1_0_wait(), stop_simulation(), or tcp_wait() to execute the selected simu...
def on_run_command_button_click(self): input = self.command_input.get() if input == "rdt 1.0 normal": self.rdt_1_0_wait() elif input == "stop": self.stop_simulation() elif input == "rdt 2.0 normal" or input == "rdt 2.0 lost": self.rdt_2_0_wait() ...
def homepage_content(): st.write('With our app you can see the data related to EDA and BVP while keeping a track of your calories and weight!') st.divider() st.write('The EDA stands for Electrodermal activity. EDA is used to measure the conductance of the skin, also known as sweat.') st.write(' The...
The main task of the code is to create a Streamlit application that loads CSV data, manages tab navigation via buttons, and displays corresponding content based on user selection. It reads a CSV file, converts the 'Time' column to datetime, uses query parameters to track the current tab (Homepage, Gym, Health, Pop-up),...
def main(): global current_tab csv_file_path = r"C:\Users\kosta\streamlit\Exporting_data_file\11-11-2023 14h46m51s\df_result.csv" data = pd.read_csv(csv_file_path) data['Time'] = pd.to_datetime(data['Time']) tab = st.experimental_get_query_params().get("tab", ["Homepage"])[0] current_tab = ta...
def merge_taxon_node(taxon, SESSION): logger.info(f' MERGE node ({taxon["ScientificName"]})') rank = sanitize_rank(taxon["Rank"]) SESSION.run( f'MERGE (n:Taxon:{rank} {{name: "{taxon["ScientificName"]}", ' f' Rank: "{rank}", ' f' TaxId: "{taxon["TaxId"]}" ' f"}})" ) d...
The main task of the code is to merge a taxon's lineage information into a database by connecting the taxon to its parent node, merging lineage nodes, and establishing hierarchical relationships. It processes the taxon's scientific name, merges its node, links it to the last lineage node, and recursively merges the ful...
def merge_taxon(taxon, SESSION): logger.info(f'Merging lineage for {taxon["ScientificName"]}') # handle connecting taxon to first parent merge_taxon_node(taxon, SESSION) merge_taxon_node(taxon["LineageEx"][-1], SESSION) merge_taxon_link(taxon["LineageEx"][-1], taxon, SESSION) # merge lineage ar...
def euclid_gcd(a, b, step=0): step += 1 if b == 0: return abs(a), step return euclid_gcd(b, euclid_mod(a, b), step) def read_file(path: str): f = open(path, "r") ls = f.readlines() f.close() result = [] for s in ls: nums = s.split(" ") result.append([ int(nums[0]...
The main task of the code is to test the Euclidean algorithm for computing the greatest common divisor (GCD) with various integer pairs, including edge cases like negatives and zeros. It then reads numerical data from a file, performs an experiment on the data, and writes the results to an output file. The code demonst...
def main(): print(euclid_gcd(13, 3)) print(euclid_gcd(13, -3)) print(euclid_gcd(-13, 3)) print(euclid_gcd(-13, -3)) print(euclid_gcd(3, 0)) print(euclid_gcd(0, 3)) print(euclid_gcd(0, 0)) # random_file(NUMBER_FILE_PATH) ls = read_file(NUMBER_FILE_PATH) print(ls) result = ex...
def GetNodeAt(self, posInLinkedList): if self.IsEmpty(): return None currentNode = self.GetHead() indexPos = 0 while currentNode != None: if indexPos == posInLinkedList: return currentNode currentNode = currentNode.GetNxtNode() ...
This function removes a node at a specified position in a doubly linked list. It identifies the node and its neighbors, adjusts pointers to bypass the node, and updates the list's head/tail if needed. It returns the removed node or None if the position is invalid.
def RemoveAtPosition(self, posInLinkedList): deadNode = self.GetNodeAt(posInLinkedList) if deadNode == None: print("No node to remove at that position!") return None prvNode = deadNode.GetPrvNode() nxtNode = deadNode.GetNxtNode() if nxtNode == No...
def Length(self): return len(self.GetLinkedList()) def GetNodeAt(self, posInLinkedList): if self.IsEmpty(): return None currentNode = self.GetHead() indexPos = 0 while currentNode != None: if indexPos == posInLinkedList: return currentNode ...
This function inserts a new node into a linked list at a specified position. If the position is invalid or unspecified, it appends the node to the end. It retrieves the predecessor and successor nodes at the target position, then calls AddNode to link the new node between them, maintaining the list's integrity.
def InsertNode(self, newNode, posNxtNode = None): if posNxtNode == None or posNxtNode > self.Length(): #Append to end of list posNxtNode = self.Length() prvNode = self.GetNodeAt(posNxtNode - 1) nxtNode = self.GetNodeAt(posNxtNode) self.AddNode(newNode, prvNode, n...
def hitungLenUser(array): kondisi = True banyak = 0 # jumlah totl jin i = banyak while (kondisi) : if EOP(array[i+3]) : kondisi = not(kondisi) elif(array[i+3][2] == 'Pengumpul' or array[i+3][2] == 'Pembangun'): banyak += 1 i += 1 return banyak def juml...
The code generates a report summarizing: total Jins, their types (Pengumpul/Pembangun), the most/least productive Jin based on candi data, and the stock of building materials (pasir, batu, air). It uses helper functions to count Jin roles, determine productivity from candi data, and retrieve material quantities.
def laporanjin(user, candi, bahan_bangunan): # arrray1 = user ,array2 = bahan, array 3= candi # laporan bagian data user N = hitungLenUser(user) print("> Total Jin: ",N) N = 103 nPengumpul = jumlahJin('Pengumpul',user,N) nPembangun = jumlahJin('Pembangun',user,N) print("> Total JIn Pengumpu...
def integerBahan(bahan_bangunan): bahan_bangunan[1][2] = int(bahan_bangunan[1][2]) bahan_bangunan[2][2] = int(bahan_bangunan[2][2]) bahan_bangunan[3][2] = int(bahan_bangunan[3][2]) return def inputBahan(pasir,batu,air,tipe,bahan_bangunan): integerBahan(bahan_bangunan) if(tipe == 'Pengumpul'): ...
The function `berhasilBangun` checks if sufficient materials (pasir, batu, air) are available for construction. If so, it records the successful building of a candi, updates material stocks, and modifies data structures. If materials are insufficient, it reports the shortage. The task involves validating resources, upd...
def berhasilBangun(pasir,batu,air,jlhPembangun,bahan_bangunan,candi,user, candiTemp): integerBahan(bahan_bangunan) if(pasir <= bahan_bangunan[1][2] and batu <= bahan_bangunan[2][2] and air <= bahan_bangunan[3][2]): print("Jin berhasil membangun total "+str(jlhPembangun)+" candi.") inputBahan(pas...
def jumlahJin(peran,user): jlhPengumpul = 0 jlhPembangun = 0 i = 0 while(not(EOP(user[i+3]))): if(user[i+3][0] != '-1'): if(user[i+3][2] == 'Pengumpul'): jlhPengumpul += 1 else:# role = 'pembangun' jlhPembangun += 1 i += 1 if(p...
The function `batchBangun` coordinates multiple 'Pembangun' builders to gather random construction materials (pasir, batu, air) and build candi structures. It calculates total material usage, prints progress, and triggers the final construction process via `berhasilBangun`, ensuring builders are utilized efficiently fo...
def batchBangun(user, bahan_bangunan,candi): jlhPembangun = jumlahJin('Pembangun',user) candiTemp = [[0 for i in range(3)] for j in range(jumlahJin('Pembangun',user)+1)] pasir = 0 batu = 0 air = 0 if(jlhPembangun == 0): print("Kumpul gagal. Anda tidak punya jin pembangun. Silahkan summon...
def askCityName(names, yesno_classifier): city = ner.getNamedEntity("GPE", listen(names)) talk(f"Is {city} the correct city?", names) answer = yesno_classifier.classify(listen(names)) if answer == "yes": talk("Okay brilliant!", names) return city else: talk("Okay, try wording...
The main task of the code is to book a flight by interactively collecting user inputs: determining destination (via yes/no classification or guided questions), origin city, departure date, and flight type (one-way/return). It confirms the booking details and returns the structured flight information if validated, or re...
def bookFlight(names): yesno_classifier = Classifier("yesno.json") placeSimilarity = PlaceSimilarity() talk("Do you know where you would like to go?", names) answer = yesno_classifier.classify(listen(names)) if answer == "yes": talk("What is the name of the city you would like to go?", name...
def write_jsons(input_urls: list[str], dict_name: str, single: bool): """ Download info of course in json file """ courses = get_courses(input_urls) single_output_dict = {} course_ids = [] for input_url, course_dict in courses: if not course_dict: print_message(1, [input_...
The main task of the code is to process command-line arguments for downloading NPTEL course materials (e.g., videos, syllabus, transcripts) or generating JSON metadata. It supports options to dump course data into JSON files, either as multiple files or a single file, and allows selective downloading of resources based...
def main(): """ Run from command line """ dict_names = [ "all", "modules", "yt", "direct", "assignements", "transcripts", "books", ] required_names = ["videos", "syllabus", "transcripts", "assignements", "books"] choices_str = f"Availab...
def load_sigma(self, path): ctime = time.time() print("Loading sigma...",) sigma = np.load(path + "sigma.npy") print("Done. Elapsed time:", time.time() - ctime, "s") return sigma def init_sigma(self, C, M, T): ctime = time.time() print("Initializing sigma...",) ...
This code trains a matrix factorization model for collaborative filtering using sparse check-in matrices. It initializes user and location latent factors (U, L), iteratively updates them via gradient-like steps involving regularization terms (Lambda, alpha, beta), and minimizes reconstruction error between observed and...
def train(self, sparse_check_in_matrices, max_iters=100, load_sigma=False): Lambda = self.Lambda alpha = self.alpha beta = self.beta T = self.T K = self.K C = sparse_check_in_matrices M, N = sparse_check_in_matrices[0].shape if load_sigma: si...
def load_sigma(self, path): ctime = time.time() print("Loading sigma...",) sigma = np.load(path + "sigma.npy") print("Done. Elapsed time:", time.time() - ctime, "s") return sigma def init_sigma(self, C, M, T): ctime = time.time() print("Initializing sigma...",) ...
This code trains a matrix factorization model on sparse check-in matrices by iteratively updating latent factors U (T matrices) and L (1 matrix) to minimize reconstruction error. It initializes parameters, computes coordinate-wise updates using observed entries, applies regularization terms (Lambda, alpha, beta), and i...
def train(self, sparse_check_in_matrices, temp_dir, max_iters=10, load_sigma=False): Lambda = self.Lambda alpha = self.alpha beta = self.beta T = self.T K = self.K C = sparse_check_in_matrices M, N = sparse_check_in_matrices[0].shape if load_sigma: ...
def training_folds(clases,data_name,algorithm): datos=leer_datos(data_name) #filterclass class_data=[]# lista de diccionarios donde: #'data':elementos de esa clase, 'n-folder':numero de elementos de esta clase en cada folder,'index':indice para separar los datos de esta clase en folders} for y ...
The main task of the code is to evaluate machine learning models (decision trees, Naive Bayes, SVMs) by calculating training and validation errors, saving results to files, and computing statistical metrics like averages, standard deviations, and t-tests to compare model performances. The active section focuses on deci...
def main(): #----------------Arboles------------------------ filetree=open("TreeErrores.txt", "w") filetree.write("TrainingError ValidationError\n") error_trees=training_folds([0,1],"BBBs.data","trees") error_trees=[(x/100,y/100) for (x,y) in error_trees] for (training,validation) in error_...
def myraph(dest, guess): theta = NewtonRaphson(lambda theta: g(dest,theta), dg_dtheta, guess, 1e-4) return theta def refill(color): PB8.value(0) motor2.setloc(0) motor1.setloc(0) pyb.delay(2000) PB8.value(1) pyb.delay(500) PB8.value(0) pyb.delay(500) PB8.value(1) pyb.dela...
This function continuously converts Cartesian coordinates (x,y) from input values into joint angles (theta1, theta2) for a robotic arm using inverse kinematics. It normalizes the angles to [-π, π], sends the results with additional status data via UART, and triggers motor movement and color refill operations. The loop ...
def TaskFindThetas(): theta = [] lastthet1 = math.pi/4 lastthet2 = math.pi/6 col = 2 while True: if X_Vals.num_in() > 0: curx = X_Vals.get()+60 cury = Y_Vals.get() theta = myraph([curx,cury], [lastthet1, lastthet2]) # converting target(x,y) -> target(thet...
def sendJoints(self): for index in range(self.arm.servoNumber - 1): self.bluetoothConnection.writeData(self.getJointAngleCommand(index)) self.sendGrab() def sendGrab(self): self.bluetoothConnection.writeData(self.getGrabAngleCommand()) def sendSpeed(self): self.bluetoothConne...
This code processes user commands to control a robotic system. It interprets single-word commands like "joints", "grab", or "forward" to trigger specific actions, and handles multi-part commands starting with "angle", "coordinate", or "speed" to adjust parameters. The function routes commands to corresponding methods, ...
def processCommand(self, command): splitCommand = command.split(' ') if command == "joints": self.sendJoints() elif command == "grab": self.sendGrab() elif command == "speed": self.sendSpeed() elif command == "kinematics": self.send...
def getConfiguration(self): return np.array([[self.q1], [self.q2], [self.q3]]) def getY(self, configuration): q1 = configuration[0][0] q2 = configuration[1][0] q3 = configuration[2][0] return self.a * cos(q1 + q2 - self.theta) + self.a * cos(q1 - self.theta) + self.lenE * sin(q1 ...
The main task of the code is to update the object's coordinates by modifying the x-position while maintaining the derived y-coordinate from the current configuration and using the pre-defined phi value (self.q3) for rotation. It calculates y based on the configuration, then calls changeCoordinates with the new x, compu...
def changeXPosition(self, x): configuration = self.getConfiguration() y = self.getY(configuration) phi = self.q3 self.changeCoordinates(x, y, phi)
def getConfiguration(self): return np.array([[self.q1], [self.q2], [self.q3]]) def getX(self, configuration): q1 = configuration[0][0] q2 = configuration[1][0] q3 = configuration[2][0] return self.a * sin(q1 + q2 - self.theta) + self.a * sin(q1 - self.theta) - self.lenE * cos(q1 ...
This method updates the Y-coordinate of an object by calling `changeCoordinates` with the current X position derived from the configuration, the provided Y value, and a predefined parameter `phi` stored in `self.q3`
def changeYPosition(self, y): configuration = self.getConfiguration() x = self.getX(configuration) phi = self.q3 self.changeCoordinates(x, y, phi)
def getConfiguration(self): return np.array([[self.q1], [self.q2], [self.q3]]) def getX(self, configuration): q1 = configuration[0][0] q2 = configuration[1][0] q3 = configuration[2][0] return self.a * sin(q1 + q2 - self.theta) + self.a * sin(q1 - self.theta) - self.lenE * cos(q1 ...
This method updates an object's coordinates by converting a given phi angle from degrees to radians and applying it to the current x and y coordinates through the changeCoordinates method.
def changePhiAngle(self, phi): configuration = self.getConfiguration() x = self.getX(configuration) y = self.getY(configuration) phi = radians(phi) self.changeCoordinates(x, y, phi)
def find_word (s, hash_table): idx = hash_word(s, len(hash_table)) #we need to make sure original hash is s if hash_table[idx] == s: return True else: ind = 1 step = step_size(s, 7) new_index = (idx + ind * step) % len(hash_table) #we need to find empty string ...
The function determines if a string `s` can be reduced to the vowels 'a', 'i', or 'o' by recursively checking substrings generated by `reducible_helper`, using `hash_table` for validation and `hash_memo` for memoization to avoid redundant checks. It returns `True` if a valid reduction path exists, otherwise `False.`
def is_reducible (s, hash_table, hash_memo): ticker = False if ('a' not in s and 'o' not in s and 'i' not in s): return False if (len(s) == 1 and (s == 'a' or s == 'o' or s == 'i')): if find_word(s, hash_memo) is False: insert_word(s, hash_memo) return True if find_w...
def is_prime ( n ): if (n == 1): return False limit = int (n ** 0.5) + 1 div = 2 while (div < limit): if (n % div == 0): return False div += 1 return True def insert_word (s, hash_table): idx = hash_word(s, len(hash_table)) if hash_table[idx] == '': #if hash table index is empty ...
The code reads words from a file, computes a prime-based hash table size, hashes words with collision handling, identifies reducible words recursively using memoization, and outputs the longest reducible words in alphabetical order.
def main(): # create an empty word_list word_list = [] # read words from words.txt and append to word_list #sys.stdin = open('word_list.in.txt', 'r') #COMMENT OUT THIS LINE for line in sys.stdin: line = line.strip() word_list.append (line) # find length of word_list lenlist = len(word_list) ...
def remove_publications_before_projects(df_publications: pd.DataFrame, df_projects: pd.DataFrame, day_diff_allowed:int=0) -> pd.DataFrame: """Remove publications published before the associated project start date. Args: ...
The main task of the code is to package and process intermediate data files (programs, grants, projects, publications) into final outputs. It loads data, applies special handling (e.g., filtering publications relative to projects), packages each dataset using column configurations, generates enumerated values for speci...
def package_output_data(): """Run all data packaging steps for all data types.""" print(f"\n---\nDATA PACKAGING:\n" f"Performing final data packaging steps...\n---\n") # Single data model dict defined in config column_configs = config.COLUMN_CONFIGS # Load programs data if os.path....
def get_max_chunk_number(output_folder): """Get the maximum chunk number from existing filenames.""" existing_chunk_files = [file for file in os.listdir(output_folder) if file.startswith('publicationDetails')] if not existing_chunk_files: return 0 else: ...
The code retrieves publication details (title, authors, date) for each PMID in a DataFrame using the PubMed API, chunks the results into CSV files of specified size, and avoids reprocessing existing data. It handles errors by logging issues and saving NaN values for failed requests, ensuring incremental processing and ...
def build_pmid_info_data_chunks(df_pmid, output_folder, chunk_size): """Get publication information for each PMID in the input DataFrame and export as separate csv files. Args: df_pmid (pd.DataFrame): DataFrame with 'coreproject' and 'pmid' columns. output_folder (str): Folder to store th...
def get_pmids_from_projects(projects_df, print_meta=False): """Iterate through project data and use NIH RePORTER API to get all PMIDs. Args: projects_df (pd.Dataframe): DataFrame of all projects from the workflow that aggregates grants into project values print_meta (bool): Boolean ...
The function gathers and processes publication data for research projects by retrieving PMIDs via the NIH RePORTER API, fetching detailed publication information from PubMed and iCite, merging and cleaning the data, and exporting results while filtering out outdated or incomplete records. It integrates publication deta...
def gather_publication_data(projects_df, print_meta=False): """Use multiple sources to gather publication data associated with projects. This function performs the following general steps: 1. Use the NIH RePORTER API to get PMIDs associated with each project 2. Use the PubMed API to get publication inf...
def parse_ts_primitive(current_z_string, current_class_dict, prop): current_class_dict["type"] = get_ts_primitive_type(prop["type"]) current_z_string += get_z_type(prop["type"]) if "modifiers" in prop: modifiers = prop["modifiers"] current_z_string += parse_modifiers_to_z_string(modifiers) ...
The function generates TypeScript code from a dictionary representation by processing properties, handling data types (primitive, generic, complex), managing imports, and rendering a Jinja2 template to output a `.ts` file with class definitions, imports, and schema details.
def build_ts(dict_repr, output_dir, template_folder): z_properties = [] class_properties = [] classes_to_import = set() baseclass = dict_repr.get("baseclass") if baseclass is not None: classes_to_import.add(baseclass) for prop in dict_repr["properties"]: current_z_string = f"{p...
def report(message): progress_title(f'[Model Loader] - {message}') if progress_canceled(): raise CancelException() def get_state_dict_from_checkpoint(pl_sd): pl_sd = pl_sd.pop("state_dict", pl_sd) pl_sd.pop("state_dict", None) sd = {} for k, v in pl_sd.items(): new_key = transfo...
The main task of the code is to load a Stable Diffusion model from a specified path, determine if it's an inpainting model, load necessary components like UNet, VAE, text encoder, and scheduler, apply LoRA weights, configure device settings, and return the fully loaded model components for diffusion tasks.
def load_stable_diffusion_model(model_path: str, lora_list: list): report(f"loading {model_path}") if model_path.endswith('.safetensors'): checkpoint = safetensors.torch.load_file(model_path, device="cpu") else: checkpoint = torch.load(model_path, map_location="cpu") checkpoint = get_st...
def get_house_dist_to_facilities(house_loc, pois): """ This returns a map that maps each place/amenity to a list of distances. This list of distances are the shortest distance of each place to each house in house_loc :param house_loc: a dataframe that is the result of the join on pp_data and po...
The function trains a linear regression model to predict house prices using distances to POIs and property types. It creates a design matrix with one-hot encoded property types, fits the model, reduces feature dimensionality, and plots training data with predicted price trends. The model combines spatial features and c...
def train(house_loc_train, pois, property_type, feature_keys, fig, ax): """ fit a linear model on the training data """ print("====================training=====================") house_dist_to_places = get_house_dist_to_facilities( house_loc_train, pois) # get all the distance features...
def get_house_dist_to_facilities(house_loc, pois): """ This returns a map that maps each place/amenity to a list of distances. This list of distances are the shortest distance of each place to each house in house_loc :param house_loc: a dataframe that is the result of the join on pp_data and po...
The function visualizes the relationship between reduced-dimensional features of house locations (derived from distances to POIs) and house prices using a scatter plot, aiding in analyzing how these features correlate with pricing.
def draw_test_data(house_loc_test, pois, feature_keys, fig, ax): house_dist_to_places = get_house_dist_to_facilities(house_loc_test, pois) x = get_features_selected(house_dist_to_places, pois, feature_keys) x_red = dim_red(x) y = np.array(house_loc_test['price'].values) ax.scatter(x_red, y, zorder...
def get_house_dist_to_facilities(house_loc, pois): """ This returns a map that maps each place/amenity to a list of distances. This list of distances are the shortest distance of each place to each house in house_loc :param house_loc: a dataframe that is the result of the join on pp_data and po...
The function predicts a property value by combining spatial features (distance to POIs) and property type indicators, using a pre-trained model. It appends input coordinates to a DataFrame, calculates distances to facilities, extracts selected features, encodes property type as a binary matrix, constructs a design matr...
def predict_single(results, house_loc_test, pois, longitude, latitude, property_type, feature_keys): house_loc_test.loc[-1, 'latitude'] = latitude house_loc_test.loc[-1, 'longitude'] = longitude house_loc_test = house_loc_test.tail(1) house_dist_to_places = get_house_dist_to_facilit...
def get_house_dist_to_facilities(house_loc, pois): """ This returns a map that maps each place/amenity to a list of distances. This list of distances are the shortest distance of each place to each house in house_loc :param house_loc: a dataframe that is the result of the join on pp_data and po...
The code validates a regression model on a test dataset by calculating distances from house locations to POIs, generating features, incorporating property type indicators, predicting house prices, computing mean squared error, and plotting actual vs. predicted prices. It returns predicted price values for evaluation.
def validate(results, house_loc_test, pois, feature_keys): print("==========validating on test dataset==============") house_dist_to_places = get_house_dist_to_facilities( house_loc_test, pois) x = get_features_selected(house_dist_to_places, pois, feature_keys) y = np.array(house_loc_test['pri...
def get_conn(): global conn if conn == None: conn = connect_db() return conn def select_top(conn, table, n): """ Query n first rows of the table :param conn: the Connection object :param table: The table to query :param n: Number of rows to query """ if n == -1: ...
The function retrieves the top `n` records from the 'pp_data' table using a database connection, converts the fetched rows into a pandas DataFrame, and returns it.
def data_pp(n): conn = get_conn() rows = select_top(conn, 'pp_data', n) return sql_row_to_df('pp_data', rows)
def get_conn(): global conn if conn == None: conn = connect_db() return conn def select_top(conn, table, n): """ Query n first rows of the table :param conn: the Connection object :param table: The table to query :param n: Number of rows to query """ if n == -1: ...
The main task of the code is to retrieve the top `n` records from the 'postcode_data' database table, convert them into a pandas DataFrame, and return it. The function establishes a database connection, fetches the specified number of rows, and transforms the result into a structured DataFrame for further analysis or p...
def data_postcode(n): conn = get_conn() rows = select_top(conn, 'postcode_data', n) return sql_row_to_df('postcode_data', rows)
def feature_selection(house_loc, pois, draw=False): """ returns a list of keys that can be used as features here features would be represented as the shortest dist from the house to that particular facility/place select features by plotting graphs and finding corr between price and the shortest ...
The main task of the code is to predict property prices using a model trained on location data (latitude, longitude, date) and OSM-derived features. It retrieves housing data, extracts points of interest (POIs), splits data into training/test sets, selects relevant features, trains the model, validates predictions, and...
def predict_price(latitude, longitude, date, property_type, draw=False): # get the prices_coordinate_data house_loc = assess.retrieve_houses( access.get_conn(), latitude, longitude, date, property_type) # get OSM data pois = assess.retrieve_pois(latitude, longitude, house_loc) if (draw): ...
def execute_command(command): result = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) logging.info("EXECUTE_COMMAND: %s" % command) stdout = result.stdout.read() if stdout: return stdout else: return None def get_asn(vtysh_config):...
The main task of the code is to configure FRR (FRRouting) BGP settings for each VRF by validating the BGP ASN from the current configuration, retrieving VRF details, and ensuring proper FRR configurations including password, neighbors, and default route origination for each VRF. It aborts if no BGP ASN is found, ensuri...
def main(): # Ensure FRR config for each vrf conf = str(execute_command("/usr/bin/vtysh -c 'show run'"), 'UTF-8') asn = get_asn(conf) if not asn: logging.warning("WARNING: No BGP ASN found! Aborting...") return False vrfJson = json.loads(execute_command("/sbin/ip -j vrf show")) b...
def prepare_bk(bkk_file, settings, file_name="BKK_Temp.pl"): file_1=open(file_name,"w") file_1.close() file_1=open(file_name,"a") file_2=open(settings,"r") file_1.write(":- use_module('metagol').\n") file_1.write(":- multifile body_pred/1.\n") file_1.write(":- multifile head_pred/1.\n") ...
The function learns a logic program from positive and negative examples using Metagol. It prepares background knowledge, splits data into training/test sets, trains a model with specified parameters, evaluates its accuracy, precision, sensitivity, and specificity, and returns a MIL object containing the learned theory ...
def metagolnt_learn(file="BK.pl", test_size=0.33, positive_example="pos_example.f", negative_example="neg_example.n", shuffle=False, settings=[], num_pos=1, num_neg=1, verbose=False, max_run=2 ): start_time = time.time() if type(settings)!=list: final_bk_file = prepare_bk(file, settin...
def prepare_bk(bkk_file, settings, file_name="BKK_Temp.pl"): file_1=open(file_name,"w") file_1.close() file_1=open(file_name,"a") file_2=open(settings,"r") file_1.write(":- use_module('metagol').\n") file_1.write(":- multifile body_pred/1.\n") file_1.write(":- multifile head_pred/1.\n") ...
This function performs cross-validation for a machine learning model using positive and negative examples. It splits data into folds, trains a model on each training fold using metagol_NT, evaluates on the test fold, and collects accuracy, precision, sensitivity, specificity, and F-score metrics. Results and runtime ar...
def metagolnt_cross_validation(file="BK.pl", CV=2, positive_example="pos_example.f", negative_example="neg_example.n", shuffle=False, settings=[], num_pos=1, num_neg=1, verbose=False, max_run=2): mil_cv_accuracy, mil_cv_precision, mil_cv_sensitivity, mil_cv_specificity, mil_cv_fscore = ...
def format_word_list(word_list_name: str) -> list[str]: with open(word_list_name, 'r') as file: wordlist = [word.strip() for word in file] return wordlist def find_valid_word_coordinates(list_of_words: list[str], matrix: np.ndarray) -> list[tuple[int, int]]: global valid_coordinates valid_coordi...
The function processes a string matrix to convert it into a grid, identifies valid words from a predefined list that can be formed within the grid, scores each valid word, and returns a sorted list of these scored words in descending order.
def find_words_form_string_matrix(string_matrix: str) -> list[tuple[int,str]]: list_of_words = format_word_list("wordlist.txt") letter_matrix = game_matrix.string_to_matrix(string_matrix) valid_words = find_valid_word_coordinates(list_of_words, letter_matrix) # scoring words valid_words = [score_wo...
def generatePerspective(external, path:typing.List, agt_id_nest_lst,entities,variables): logger.debug("generatePerspective") if path == []: return {} # assert(path == []) logger.debug(f'path: {path}') state, action = path[-1] new_state = {} logger.debug(f'current state: {state}') ...
The function `checkingEQ` evaluates the truth of an epistemic query (`eq`) based on the current state, group perspectives, and variables. It handles three query types: **BELIEF** (checks if variables match a generated perspective path), **SEEING** (evaluates observations from a group's perspective), and **KNOWLEDGE** (...
def checkingEQ(external,eq:EpistemicQuery,path:typing.List,state,entities,variables): var_list = external.extractVariables(eq) logger.debug(f"checking eq {eq}, {eq.eq_type}") logger.debug(f'current state: {state}') logger.debug(f'var_list: {var_list}') if eq.eq_type == EQ_TYPE.BELIEF: ...
def getObservations(problem:Problem,state,agt_id_nest_lst,): logging.debug(f"generating observation of agent {agt_id_nest_lst} from state: {state}") new_state = state.copy() temp_agt_nest_list = agt_id_nest_lst.copy() while not temp_agt_nest_list == []: temp_agent_list = temp_agt_nest_list.pop(...
The code evaluates an epistemic query (BELIEF, SEEING, or KNOWLEDGE) against a given world in a problem, determining its truth value. For BELIEF, it generates a perspective-based world, checks variable consistency, and recursively evaluates nested queries. For SEEING, it assesses the query's content against observed st...
def checkingEQ(problem:Problem,eq:EpistemicQuery,path:List,world): var_list = external.extractVariables(problem,eq) logging.debug(f"checking eq {eq}, {eq.eq_type}") if eq.eq_type == EQ_TYPE.BELIEF: logging.debug(f"checking belief for {eq}") # generate the world new_observati...
def check_keydown_events(event, ai_settings, screen, stats, score, ship, aliens, bullets): """Responds to keypresses""" if event.key == pygame.K_RIGHT: #Move ship to the right. ship.moving_right = True elif event.key == pygame.K_LEFT: #Move ship to the left. ship.moving_left ...
This function handles game events by checking for key presses, releases, and mouse clicks. It exits the game on 'Q' or close requests, processes keyboard inputs via check_keydown_events/check_keyup_events, and triggers game start via check_play_button when the play button is clicked, passing relevant game objects and m...
def check_events(ai_settings, screen, stats, score, play_button, ship, aliens, bullets): """Responds to key presses and mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q): sys.exit() elif event.t...
def check_fleet_edges(ai_settings, aliens): """Respond appropriately if any alien has reached an edge.""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def ship_hit(ai_settings, screen, stats, score, ship, aliens, bullets...
This function updates alien positions, checks for collisions between aliens and the ship, and detects if aliens reach the screen's bottom. It triggers responses like ship damage or alien resets when collisions occur, ensuring game mechanics like scoring and enemy behavior are maintained.
def update_aliens(ai_settings, screen, stats, score, ship, aliens, bullets): """Check if fleet is at an edge and Update the position of all aliens in the fleet.""" check_fleet_edges(ai_settings, aliens) aliens.update() #Look for alien-ship collisions if pygame.sprite.spritecollideany(ship, alie...
def unpickle(file): import pickle with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict def initialize_parameters(layers_dims): """ Function which initializes the different parameters of the model. @param layers_dims -- a list of the different sizes ...
The main task of the code is to train a multi-layer neural network on the CIFAR-10 dataset. It initializes parameters, loads and preprocesses data, performs forward and backward propagation for 2 iterations, computes the cost, and updates parameters using gradient descent. The network has 4 layers with dimensions [3072...
def main(): global seed seed = 1 learning_rate = 0.01 layers_dims = [3072, 14, 12, 10] for k in range(1, 2): dataset = unpickle('D:\Programmation\Python\cifar-10-batches-py\data_batch_' + str(k)) X_origin = dataset[b'data'] Y_origin = dataset[b'labels'] X = np.tr...
def convert_keys_to_ints(X, Y): return ( dict((i, v) for (i, (k, v)) in enumerate(X.items())), dict((i + len(X), v) for (i, (k, v)) in enumerate(Y.items())), ) def construct_cossim_lookup(XY, AB): """ XY: mapping from target string to target vector (either in X or Y) AB: mapping from...
The function `run_test` performs a Word Embedding Association Test (WEAT) to assess if there's a statistically significant difference in associations between two target groups (`targ1`, `targ2`) and two attribute groups (`attr1`, `attr2`). It calculates cosine similarities between word embeddings, computes a p-value vi...
def run_test(encs, n_samples, parametric=False): ''' Run a WEAT. args: - encs (Dict[str: Dict]): dictionary mapping targ1, targ2, attr1, attr2 to dictionaries containing the category and the encodings - n_samples (int): number of samples to draw to estimate p-value (use e...
def load_json(sent_file): ''' Load from json. We expect a certain format later, so do some post processing ''' log.info("Loading %s..." % sent_file) all_data = json.load(open(sent_file, 'r')) data = {} for k, v in all_data.items(): examples = v["examples"] data[k] = examples ...
(The code evaluates a machine learning model's performance on multiple tasks by computing embeddings for test data, running statistical tests (esize, p-value), and aggregating results into score metrics for each test case.)
def evaluate_model(self, model, tokenizer): model.to(self.device) model.eval() score = [] for test in self.all_tests: encs = load_json(os.path.join(self.data_dir, f"{test}.jsonl")) encs["targ1"]["encs"] = self.get_embedding_avg(encs["targ1"]["examples"], model, to...
def init(self, barcode, sensor_id): self.try_again = False self.ser = None if not self.use_port == '': self.ports = {self.use_port} for port in self.ports: try: self.ser = serial.Serial( port=port, baudrate=9600, ...
The main task of the code is to read temperature data from a sensor via serial communication. It handles initialization errors, constructs a command message with a checksum, sends it, waits for a response, processes the received data, and returns the calculated temperature value. If any step fails (e.g., timeout, initi...
def get_temperatur(self): if self.error: self.init(self.barcode, self.sensor_id) if self.error: # ist nach initiasierung immer noch error hat init nicbt geklappt return 'Error' if self.fullscale_tempratur == 0 or not self.fullscale_tempratur: self.fullscale_tempratur = ...
def init(self, barcode, sensor_id): self.try_again = False self.ser = None if not self.use_port == '': self.ports = {self.use_port} for port in self.ports: try: self.ser = serial.Serial( port=port, baudrate=9600, ...
The main task of the code is to read pressure data from a sensor by sending a command via serial communication, handling errors during initialization and data retrieval, calculating the pressure value using the fullscale pressure reference, and returning the result or an error if any step fails.
def get_pressure(self): if self.type == 'VFS': # VFS kann keinen Druck return 'Error' if self.error: self.init(self.barcode, self.sensor_id) if self.error: # ist nach initiasierung immer noch error hat init nicbt geklappt return 'Error' if self.fullscale_pressur...
def init(self, barcode, sensor_id): self.try_again = False self.ser = None if not self.use_port == '': self.ports = {self.use_port} for port in self.ports: try: self.ser = serial.Serial( port=port, baudrate=9600, ...
The main task of the code is to retrieve and calculate the flow rate from a sensor by sending a specific command, handling errors during initialization and communication, and processing the received data to return the calculated flow value. It includes checks for sensor type, error handling, fullscale calibration, seri...
def get_flow(self): if self.type == 'RPS': # VFS kann keinen Druck return 'Error' if self.error: self.init(self.barcode, self.sensor_id) if self.error: # ist nach initiasierung immer noch error hat init nicbt geklappt return 'Error' if self...
def process_package(self, package_name, parent="-"): if self.debug: print(f"Process package {package_name}. Parent {parent}") # Check if we have already processed this package if package_name in self.distro_packages: self.sbom_relationship.initialise() self.sb...
The code processes a distribution package for a specified module by setting a parent identifier, executing package processing, and analyzing the package's name and dependencies if processing succeeds.
def process_distro_package(self, module_name): self.parent = f"{self.name}-{self.release}-Package-{module_name}" if self.process_package(module_name): self.analyze(self.get("Name"), self.get("Depends"))
def perform_image_addition(addition, jsonfile, outputWindow): kvp = dict() for i in ["name", "file"]: kvp[i] = addition[i] kvp["file"] = os.path.abspath(kvp["file"]) for line in maskmaker("addres", kvp, [jsonfile]): outputWindow.append(line) def perform_material_addition(addition, jsonfi...
This function routes the processing of an 'addition' task based on its type by calling specialized handler functions for different asset types (image, material, emitter, tweak) or a general handler for "sequence" and "model" types, using a JSON file and output window for operations.
def perform_addition(addition, jsonfile, outputWindow): if addition["type"] == "image": perform_image_addition(addition, jsonfile, outputWindow) elif addition["type"] == "material": perform_material_addition(addition, jsonfile, outputWindow) elif addition["type"] == "emitter": perfor...
def function_open(line, lineno): global current_function m = re.match(r"Function: '([^']+)'", line) if m is None: return False name = m.group(1) if name not in c.callgraph: if print_verbose: sys.stderr.write("Warning: function '" + name + ...
The code processes each line of a file, skipping lines that meet conditions checked by three functions: function_open, function_close, and global_access. It iterates through the file, strips trailing newlines, and applies these checks to determine whether to continue (skip) the line. The primary task is to filter and p...
def load_global(f): for i, line in enumerate(f): line = line.rstrip() if function_open(line, i+1): continue if function_close(line, i+1): continue if global_access(line, i+1): continue
def check_args(argv): global acl_files global print_accesses, print_clang global print_verbose desc = "Merge multiple access control lists" parser = argparse.ArgumentParser(description=desc) parser.add_argument("<acl>", type=argparse.FileType("r"), nargs="+", help="Access control list printed by 'build_ac...
The main task of the code is to process and display Access Control List (ACL) information. It checks command-line arguments, loads ACL data, prints the loaded ACLs, and generates/output code based on the ACLs, likely for configuration or analysis purposes.
def main(): check_args(sys.argv) load_acls() print_acls() print_code()
def check_args(argv): global elf, callgraph_file, global_file, mmio_file, stack_heap_file global N global print_accesses, print_callgraph global print_verbose desc = "Build an access control list using analysis results" parser = argparse.ArgumentParser(description=desc) parser.add_argument(...
The main task of the code is to load an ELF symbol table and various system data (call graph, global variables, MMIO, stack/heap) to construct and print an Access Control List (ACL) using the `build_acl` and `print_acl` functions, ensuring proper symbol resolution and data integration for analysis or security validatio...
def main(): global symtbl check_args(sys.argv) symtbl = elfsym.load_symbol_table(elf) if symtbl is None: sys.exit(1) load_callgraph(callgraph_file) load_global(global_file) load_mmio(mmio_file) load_stack_heap(stack_heap_file) build_acl(N) print_acl()
def _create_cells(self): self._cells = [[Cell(self.win) for _ in range(self.num_row)] for _ in range(self.num_cols)] for i in range(self.num_cols): for j in range(self.num_row): self._draw_cells(i, j) def _break_entrance_and_exit(self): self._cells[0][0].corners = Cel...
This code initializes a maze structure with specified dimensions and settings, creating a grid of cells, breaking walls to form paths, and setting up entrance/exit points. It uses a seed for reproducible randomization and resets cells to unvisited states, enabling maze generation algorithms like recursive backtracking.
def __init__(self, x1, y1, num_row, num_cols, cell_size_x, cell_size_y, win: Window | None = None, seed = None) -> None: self.x1 = x1 self.y1 = y1 self.num_row = num_row self.num_cols = num_cols self.cell_size_x = cell_size_x self.cell_size_y = cell_size_y self.wi...
def bestCut(node, nb_cut, features): """Finds the best cut between nb_cut possible cut Arguments: node {Node} -- the node associated to the dataset we want to split nb_cut {int} -- the number of cuts tested features {list} -- the list of features Returns: (float, di...
The function constructs a decision tree recursively by selecting the best feature cut (via `bestCut`) to partition data at each node. It stops splitting when max depth is reached, no information gain exists, or the node's data is pure (gini = 0). After partitioning, it recursively builds left/right subtrees, decrementi...
def decisionTree(node, n_cuts, features, max_depth): """Builds the decision tree. Arguments: node {Node} -- the root node n_cuts {int} -- the number of cuts tested to find the best cut features {list} -- the list of features ...
def priority(queue): min = math.inf index = 0 for check in range(len(queue)): _,value,_,_ = queue[check] if value<min: min = value index = check #index of the shortest path return index def check_visited(current,visited): for x,y,th in visited: if cur...
The code implements the A* algorithm to find a path from a start point to a goal, using a priority queue (open_set) and tracking visited nodes. It calculates path costs (gcost) and heuristic estimates (tcost), exploring neighbors via kinematic equations. The algorithm returns the path if the goal area is reached, other...
def A_star(): open_set = [] visited = [] start = agent_start tcost = 0 gcost = 0 path = [start] open_set.append((start,tcost,gcost,path)) while len(open_set)>0: index = priority(open_set) (shortest,_,gvalue,path) = open_set[index] #select the node with lowest distance ...
def priority(queue): min = math.inf index = 0 for check in range(len(queue)): _,value,_,_ = queue[check] if value<min: min = value index = check return index def check_visited(current,visited): for x,y,th in visited: if current[0]== x and current[1]=...
The code implements the A* algorithm to find an optimal path from a starting position to a goal, using a combination of path cost and heuristic (based on velocity and position). It checks for goal proximity, expands valid neighbors, and prioritizes nodes with lowest total cost, returning the path if the goal is reached...
def A_star(): open_set = [] visited = [] start = agent_start tcost = 0 gcost = 0 path = [start] open_set.append((start,tcost,gcost,path)) while len(open_set)>0: index = priority(open_set) (shortest,_,gvalue,path) = open_set[index] #select the node with lowest distance ...
def getNextTide(self, highlow=None): """Get next change in tide.""" try: for tide in self.highlow: if dt_now() < tide["time"]: if highlow is None or tide["flag"] == highlow: _LOGGER.debug(f"getNextTide (highlow={highlow}): - {tide}...
This function retrieves the complete tide state by combining the high/low tide status with the ebb/flow direction. If the initial tide state is "Normal," it returns only the ebb/flow information. Otherwise, it concatenates the tide state with the ebb/flow data. It handles missing input by fetching the next tide and cat...
def getTideStateFull(self, nexttide=None): """Get full tide state including both high/low and ebb/flow.""" try: if nexttide is None: nexttide = self.getNextTide() state = self.getTideState(nexttide) if state == "Normal": return self.get...
def c4ddp(u,h,n): a = np.zeros((n)) b = np.zeros((n)) c = np.zeros((n)) x = np.zeros((n)) r = np.zeros((n)) upp = np.zeros((n+1)) a[:] = 1.0/10.0 b[:] = 1.0 c[:] = 1.0/10.0 # for i in range(1,n): # r[i] = (6.0/5.0)*(u[i-1] - 2.0*u[i] + u[i+1])/(h*h) ...
This function computes the right-hand side (RHS) of a PDE system, likely for fluid dynamics, involving convective and diffusive terms. It calculates the Laplacian of the velocity field (wxx, wyy) for diffusion, constructs a Jacobian matrix using upwind schemes for convection, and combines these with the Reynolds number...
def rhs_cu3(nx,ny,dx,dy,re,pCU3,w,s): lap = np.zeros((nx+5,ny+5)) jac = np.zeros((nx+5,ny+5)) f = np.zeros((nx+5,ny+5)) # compute wxx for j in range(2,ny+3): a = w[2:nx+3,j] wxx = c4ddp(a,dx,nx) lap[2:nx+3,j] = wxx[:] # compute wyy for i in range(2,...
def _handle_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): quit() elif (self.spaceship and event.type == pygame.KEYDOWN and event.key == p...
The main task of the code is to run an infinite game loop that continuously handles user input, processes game logic updates, and renders the game's visual state, creating a real-time interactive experience.
def main_loop(self): while True: self._handle_input() self._process_game_logic() self._draw()
def getArgs(): # Add arguments to the parser object parser = argparse.ArgumentParser() parser.add_argument('--subset', type=str, required=True, help="The dataset to use", choices={"2", "3", "combined"}, default="2") parser.add_argument('--max_seq_length', type=int, help="The maximum total input sequence...
The code defines an optimization function for hyperparameter tuning using Optuna. It suggests parameters (learning rate, dropout, dimensions, activation) for a ViLongformer model, trains the model with these settings, evaluates validation accuracy, and saves the best-performing model. The goal is to maximize validation...
def objective(trial, study, train_loader, val_loader): args = getArgs() # Set up trial values to experiment with lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True) dropout_val = trial.suggest_float("dropout_val", 0, 0.5, step=0.1) ib_dim = trial.suggest_int("ib_dim", 200, 500, step=5) activat...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--dropout", type=float, default=None, help="dropout rate.") parser.add_argument("--kl_annealing", choices=[None, "linear"], default="linear") parser.add_argument("--evaluate_after_each_epoch", action="store_true", help="Evaluates th...
The main task of the code is to perform hyperparameter optimization using Optuna when enabled, or train/evaluate a model based on specified arguments. It initializes a study, runs trials, saves the best model, and tests it. If Optuna is disabled, it loads a model, trains it with given parameters, saves checkpoints, and...
def main(): args = get_args() # If optuna flag is enabled perform hyperparameter optimization if args.optuna: # Create optuna study STUDY_NAME = 'vi-' + args.model_type + '-subset' + str(args.subset) study = optuna.create_study(study_name=STUDY_NAME, direction='maximize', storage='s...
def getArgs(): # Add arguments to the parser object parser = argparse.ArgumentParser() parser.add_argument('--subset', type=str, required=True, help="The dataset to use", choices={"2", "3", "combined"}, default="2") parser.add_argument('--model', type=str, required=True, help="The model to use for sentence embe...
The main task of the code is to train and evaluate a BiLSTM model for text classification using precomputed sentence embeddings. It loads a dataset, generates embeddings with a specified model (e.g., MiniLM), prepares data loaders, and either performs hyperparameter optimization via Optuna or directly trains the LSTM. ...
def main(): args = getArgs() dataset = datasets[args.subset] print(args.subset, args.model, 'ARGS') # MiniLM has an input dimension of 384 args.hidden_dim = 768 if args.model != 'minilm' else 384 # Get the sentence transformer to use sentenceTransformer = models[args.model] embedding = SentenceTran...
def getArgs(): # Add arguments to the parser object parser = argparse.ArgumentParser() parser.add_argument('--subset', type=str, required=True, help="The dataset to use", choices={"2", "3", "combined"}, default="2") parser.add_argument('--max_seq_length', type=int, help="The maximum total input sequence...
The code's main task is to train and evaluate a ViLongformer model on a specified dataset, either performing hyperparameter optimization via Optuna or directly training/testing the model. It loads dataset splits, prepares data loaders, and conditionally conducts hyperparameter tuning (with Optuna) or standard training....
def main(): args = getArgs() # Get the dataset dataset = datasets[args.subset] # Read the train, test and val splits df_train = pd.read_csv('./' + dataset + '_train.csv') df_test = pd.read_csv('./' + dataset + '_test.csv') df_val = pd.read_csv('./' + dataset + '_val.csv') train_loader...
def getTripData(): file = open("trips.txt",'r', encoding="utf-8-sig") read = file.readlines() read = [readed.strip() for readed in read] return read def deleteSpecialText(text): # COMMA_MATCHER = re.compile(r",(?=(?:[^\"']*[\"'][^\"']*[\"'])*[^\"']*$)") # return COMMA_MATCHER.split(text) ret...
The function processes GTFS trip data for a specific date by cleaning headers, converting data into a DataFrame with specified string types, and filtering rows based on service IDs active on the given date.
def getTripsPD(date): trip_d = getTripData() header_t = deleteSpecialText(trip_d[0]) trip_d.pop(0) data_string_t = "\n".join(trip_d) data_iot = StringIO(data_string_t) df_t = pd.read_csv(data_iot, header=None, names=header_t, dtype={'route_id':str,'trip_id':str,'service_id':str,'trip_headsign':s...
def getStoptimeData(): file = open("stop_times.txt",'r', encoding="utf-8-sig") read = file.readlines() read = [readed.strip() for readed in read] return read def deleteSpecialText(text): # COMMA_MATCHER = re.compile(r",(?=(?:[^\"']*[\"'][^\"']*[\"'])*[^\"']*$)") # return COMMA_MATCHER.split(text...
The function processes stop time data for a given date by filtering trips, converting text data into a structured DataFrame with specified headers and data types, and returning only the rows corresponding to trips active on that date.
def getStopTimePD(date): stoptime_d = getStoptimeData() header_st = deleteSpecialText(stoptime_d[0]) stoptime_d.pop(0) data_string_st = "\n".join(stoptime_d) data_iost = StringIO(data_string_st) df_st = pd.read_csv(data_iost, header=None, names=header_st, dtype={'trip_id': str, 'arrival_time': s...
def _get_first_image_from_dir(image_dir: str) -> Optional[str]: for subdir, dirs, files in os.walk(image_dir): for file in files: # Check for image file extensions. You can add or remove as needed. if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')): r...
This code validates a dataset's structure by checking the existence of required files like 'dataset_infos.json' and 'thumbnail.jpg', verifying annotations if specified, and ensuring consistent splits and labels. It returns validation results as messages indicating pass/fail status for each check, with error/warning han...
def validate_dataset(self, annotations_required: bool = True): """ Validates dataset structure. Args: annotations_required (bool): Whether the dataset is required to have annotations Returns: Returns a dictionary of key-value pairs, where key is the unique name ...
def sin_converted(x): ''' Description: Calculate the sine of a number using a polynomial approximation Parameters: Double x radians in domain [0, PI/4] Return: Double sine of x radians ''' sine = 0 for i in range(1, DEGREE + 1, 2): # use below formula to get odd degrees, evens are al...
The code calculates the sine of a given angle `x` (in radians) using polynomial approximations by reducing `x` to the interval [0, 2π) and applying symmetry properties. It divides the domain into subintervals, mapping each to a converted function (`sin_converted` or `cos_converted`) for efficient polynomial evaluation....
def sin(x): ''' Description: Calculate the sine of a number using a polynomial approximation Parameters: Double x radians Return: Double sine of x radians ''' # Make sure x is in domain [0, 2PI) if x >= 2 * PI: x -= int(x / (2 * PI)) * 2 * PI if x < 0: x += int(x / (2 * P...
def cos_converted(x): ''' Description: Calculate the cosine of a number using the sine function Parameters: Double x radians in domain [0, PI/4] Return: Double cosine of x radians ''' sinesqrd = sin_converted(x) ** 2 cosine = math.sqrt(1 - sinesqrd) return cosine def sin_converted(x): ...
The code calculates the cosine of a given angle x (in radians) by reducing x to the [0, 2π) domain, then applying interval-specific transformations using sine conversions (e.g., cos(x) = sin(π/2 - x)) and recursive calls for edge cases, ensuring accurate computation through domain partitioning and trigonometric identit...
def cos(x): ''' Description: Calculate the cosine of a number using the sine function Parameters: Double x radians Return: Double cosine of x radians ''' # Make sure x is in domain [0, 2PI) if x >= 2 * PI: x -= int(x / (2 * PI)) * 2 * PI if x < 0: x += int(x / (2 * PI) - ...
def get_radians(): ''' Description: Get number radians from user Parameters: void Return: Double radians ''' while True: inp = input('Enter a number of radians: ') try: inp = float(inp) return inp except: # Catch invalid input print('In...
The code's main task is to compute and display the sine, cosine, and tangent of a user-input radian value. It prompts the user for an angle, calculates the trigonometric functions using Python's math library, prints the results, and generates a graph plotting the cosine and sine values. The program combines input handl...
def run(): ''' Description: Output approximate sine using user input Parameters: void Return: void ''' # INPUT print('Instructions:\nThis program will output the sine, cosine, and tangent of a given number of radians.' + 'Enter a value to recieve the sine, cosine, and tangent of that...
def build_maxheap(array): index = len(array) // 2 - 1 while index >= 0: heapify(array, index, len(array)) index -= 1 def swap(array, begin_index, end_index): array[begin_index], array[end_index] = array[end_index], array[begin_index] def heapify(heap, begin_index, max_index): while begi...
The code implements the heap sort algorithm to sort an array in ascending order. It first builds a max heap, then repeatedly swaps the root (maximum element) with the last unsorted element, reduces the heap size, and re-heapifies the remaining elements until the array is fully sorted.
def heapsort(array): # we begin from the last element because that's where # the highest value element will be after we sort the array; # We are sorting from the smallest to the largest value. last_element_index = len(array) - 1 build_maxheap(array) # Build a max heap # Now the element array[0...
def isProjectNameUsed(ProjectName): if (getProjectID(ProjectName) == -1): return False return True def getUniqueName(seed, ProjectName): sum = 0 for digit in str(seed): sum += int(digit) newName = ProjectName + str(sum) if(isProjectNameUsed(newName)): newName = getUni...
The code creates a new project by converting the project name to uppercase, ensuring its uniqueness by checking against existing names and generating a unique variant if necessary, then inserting the project into the database with the owner's ID and the finalized project name, returning a success message upon completio...
def CreateProject(uID, ProjectName): ProjectName = ProjectName.upper() if isProjectNameUsed(ProjectName): ProjectName = getUniqueName(uID, ProjectName) values = (uID, ProjectName) cursor.execute("INSERT INTO activeProjects (owner, project_name) VALUES (?, ?);", values) ...
def payload_copy(payload_file: pathlib.Path, prefixes: list, domain: str, dry_run=False) -> pathlib.Path: """ Copies `payload_file` to the first valid `prefix` from the `prefixes` list """ # Check if file exists if not payload_file.exists(): raise FileExistsError("File not found: " + str(payload_fi...
The main task of the code is to copy payload files to a destination path, log the operation, and create/associate PIL entries with the copied files. It iterates through each PIL and its payloads, uses `payload_copy` to handle file copying (with a dry-run option), and calls `create_and_link_pil` to register the copied p...
def push_pil(dry_run=True): for pil in pils: for payload in pil['payloads']: copy_args = (pathlib.Path(payload['path']), prefixes, pil['domain']) destination = payload_copy(*copy_args, dry_run) _vlprint(2+int(dry_run), f"Copying payload file {destinati...
def fetch_entries(component: str, uid: int = None): """ Fetch entries using respective endpoints """ url = form_api_url(component, uid) return _get_data(url) def pprint_named_entries(respjson, dump: bool): """ Pretty print named entries """ if dump: print(json.dumps(respjson, indent=4)) ...
The code defines a function `act_on` that processes command-line arguments to perform various actions: configuring and displaying settings, adding tags/payloads, pushing data, and fetching payloads. It handles errors, navigates config dictionaries, and uses helper functions to retrieve/print data, with action-specific ...
def act_on(args): if args.action == 'config': config_dict = cfg.__dict__ try: for ix in args.field: config_dict = config_dict[int(ix) if ix.isnumeric() else ix] except: pass print(config_dict) if args.action == 'show': respjson = fetch_entries...
def val(self): token = None current = self.tokens.peek() if current == "id" or current == "inum" or current == "fnum": token = self.tokens.match(current) else: self.error() return [Node(token["type"], token["val"])] def expr(self, val_node): node = None current = self.tokens.peek...
This code parses assignment or print statements, constructing a syntax tree. It creates a node for "assign" with an identifier and its value, or a "print" node with an identifier. The method consumes tokens, matches expected keywords, and builds a node hierarchy to represent the parsed statement.
def stmt(self): token = None node = Node() if self.tokens.peek() == "id": token = self.tokens.match("id") self.tokens.match("assign") node.set_info("assign") node.add_children([Node(token["type"], token["val"])]) val_node = self.val() node.add_children(self.expr(val_node)...
def stmt(self): token = None node = Node() if self.tokens.peek() == "id": token = self.tokens.match("id") self.tokens.match("assign") node.set_info("assign") node.add_children([Node(token["type"], token["val"])]) val_node = self.val() node.add_children(self.expr(val_node)...
This function parses a sequence of statements. It checks if the next token is "id" or "print", recursively parsing individual statements (via self.stmt()) and subsequent statements (via self.stmts()), collecting results in a list. If the token isn't "$" (end-of-input), it raises an error. The function returns the list ...
def stmts(self): children = [] if self.tokens.peek() == "id" or self.tokens.peek() == "print": children += self.stmt() children += self.stmts() else: if self.tokens.peek() != "$": self.error() return children
def get_tree_df_from_model( self, rfm: RFmodeller, features: list[str] ) -> pd.DataFrame: """ Constructs the tree_df dataframe from the random forest model. This dataframe contains information about each tree in the random forest. The method iterates over each estimator to re...
The code initializes a class to process a random forest model by generating a tree DataFrame, adding cluster information, and appending grid coordinates for visualization or analysis of the model's structure and clustering patterns.
def __init__(self, rfm: RFmodeller, features: list[str]): self.rfm = rfm self.features = features self.tree_df = self.get_tree_df_from_model(rfm, features) self.tree_df = self.add_cluster_information_to_tree_df(rfm, features) self.tree_df = self.add_grid_coordinates_to_tree_df(se...
def load_lamah_forcing(data_dir: Path, basin: str, sub_dataset: str, temporal_resolution: str = '1D') -> pd.DataFrame: """Load forcing data of the LamaH data set. Parameters ---------- data_dir : Path Path to the LamaH directory. basin : str Basin identifier number as string. s...
The function loads hydrological data for a specified basin, determining temporal resolution (hourly/daily) based on configuration. It retrieves forcing data and, if discharge ('qobs') is required, loads and normalizes it using basin-specific area and time resolution, then returns the compiled DataFrame.
def _load_basin_data(self, basin: str) -> pd.DataFrame: """Load input and output data from text files.""" # Determine if hourly or daily data should be loaded, by default daily. temporal_resolution = '1D' if self.cfg.use_frequencies: if any([utils.compare_frequencies(freq, '...