dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def forward_propagation(activation, weight, z, neuron, bias): for i in range(1,len(neuron)): for j in range(neuron[i]): for k in range(neuron[i-1]): #print('I ',i,' J: ',j,' K: ',k) #print(' WEIGHT:',weight[i][j][k]) #print('ACTIVATION: ',activation[i-1][k]) z[i][j] += activation[i-1][k] * weight...
The code implements a neural network for training and testing on MNIST data. It initializes layers, neurons, weights, and biases, then performs forward propagation to compute activations. Backpropagation adjusts weights and biases using calculated errors and a learning rate. The network trains for 5 epochs on training ...
def neural_network(): neuron=[] activation=[] error=[] weight=[] z=[] bias = [] n = int(input('No of layers:\n')) for i in range(n): print('No. of neuron in ',i,' layer:\t') neuron.append(int(input())) for l in range(n): activation_neuron = [] error_neuron = [] z_neuron = [] for m in range(neuro...
def forward_propagation(activation, weight, z, neuron, bias): for i in range(1,len(neuron)): for j in range(neuron[i]): for k in range(neuron[i-1]): z[i][j] += activation[i-1][k] * weight[i][j][k] z[i][j] += bias[i][j] activation[i][j] = sigmoid(z[i][j]) return activation, z def loss_calculation(...
This code defines a neural network with multiple layers, initializes weights and biases randomly, and trains it using backpropagation on XOR gate data. It performs forward propagation, calculates loss, updates weights/biases iteratively, and evaluates the trained model's performance by computing the average squared err...
def neural_network(): neuron=[] activation=[] error=[] weight=[] z=[] bias = [] n = int(input('No of layers:\n')) for i in range(n): print('No. of neuron in ',i,' layer:\t') neuron.append(int(input())) for l in range(n): activation_neuron = [] error_neuron = [] z_neuron = [] for m in range(neuro...
def before_integrate(self, y0, t_eval): t_eval = copy.deepcopy(t_eval) if (t_eval is not None) and (len(t_eval) > 0): self.t_eval = t_eval assert isinstance(t_eval, list), 't_eval must be of type list' assert (self.t1 - t_eval[-1]) * (t_eval[0] - self.t0) >= 0, \ ...
This code performs time integration using predefined or calculated steps, handling tensor inputs, and returns integrated results. It checks input type, generates integration steps, executes the integration, aggregates results, and optionally returns steps.
def integrate(self, y0, predefine_steps = None, return_steps=False, t_eval = None): self.before_integrate(y0, t_eval) # check if f is a function that returns tensor if isinstance(y0, tuple) or isinstance(y0, list): use_tuple = True print('Currently only support tensor fu...
def clear(self,nstart): (x,y)=nstart self.x=[] self.y=[] self.z=[] self.parent=[] self.x.append(x) self.y.append(y) self.z.append(z) #first node is the only node whose parent is itself self.parent.append(0) def expand (self): #add random node x = random.uniform (0,2000) y = random.uniform (0, ...
The main task of the code is to perform path planning using a sensing-based RRT (Rapidly-exploring Random Tree) algorithm. It iteratively expands and biases the tree to explore the environment, checks if the goal is reached, generates a path to the goal, prunes the path for optimization, and visualizes the result. The ...
def sense(self): while(len(self.newstart)!=0): #first observation state cn=self.newstart[0] cx=self.wayx[cn] cy=self.wayy[cn] cz=self.wayz[cn] self.clear((cx,cy,cz)) #balance between extending and biasing for i in range(0,nmax): if i%10!=0: self.expand() else: self.bias() #check if...
def baselineScene(self): if self.stage == 'cue': self.drawTextCentered([0,0], [2, 0.5], self.cue_text, self.text_color) elif self.stage == 'fixation': self.drawImageCentered([0,0], [0.5, 0.5], self.images['fixation']) def trainingScene(self): if self.stage == 'cue_rest': ...
The `paintGL` method determines the current scene state (`self.scene`) and delegates rendering to the appropriate scene-specific method: `baselineScene()`, `trainingScene()`, or `gameScene()`. Its primary task is to dynamically select and execute the correct rendering logic based on the scene context, enabling differen...
def paintGL(self): if self.scene == 'baseline': self.baselineScene() elif self.scene == 'training': self.trainingScene() elif self.scene == 'game': self.gameScene()
def process_naive( x: np.ndarray, waveform: np.ndarray, os_factor: int ) -> Tuple[np.ndarray, str]: # Waveform generation y = process_naive_linear(waveform, x) assert np.isnan(y).any() == False if os_factor != 1: y = decimate(y, os_factor) name = "naive" if os_factor != 1: ...
The function `routine` processes input data `x` using different algorithms (NAIVE, ADA, or ADA with mipmap) based on `details`, generating output data. It constructs a name with optional frequency, logs start/end, and returns the name, frequency, generated data, and details. The algorithm choice depends on `details.alg...
def routine( details: AlgorithmDetails, x, cache, freq: int = None ) -> Tuple[str, int, np.ndarray[float], AlgorithmDetails]: if freq is None: name = details.name else: name = details.name_with_freq(freq) logging.info("{} : started".format(name)) if details.algorithm is Algorithm.NAI...
def callDETAW(supmodel,leachoption): owd = os.getcwd() dir_dst = "../DETAW/" os.chdir(dir_dst) months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] if supmodel == 1 or supmodel == 2: inputfile = "./Input/historical_study/LODI_PT.csv" elif supmodel == 3:...
The code reads parameters from a file, executes model functions (callDETAW, callDCD, and variants), generates outputs, and cleans up temporary files. It processes model options and leach scale factors from input lines, runs simulations with different extensions, and restores the original working directory after operati...
def main(): pyhecdss.set_message_level(0) owd = os.getcwd() modelparafile = "./NODCU/DCD_parameters.inp" fmp = open(modelparafile,"r") modeloption = 0 outputfile = "" for line in fmp: if line: if not("#" in line): if "Model to streamline" in line: ...
def create_user(self, name, password, email='cnefd@example.com'): url = url_for('api.userlistresource', _external=True) data = {'name': name, 'password': password, 'email': email} response = self.test_client.post( url, headers=self.get_accept_content_type_headers(), ...
This test verifies the creation and retrieval of a Category resource. It creates a user, then creates a new Category, checks creation success (201 status), confirms database count, retrieves the category via its URL, validates authentication, and ensures the retrieved data matches the original name.
def test_create_and_retrieve_category(self): """ Ensure we can create a new Category and then retrieve it """ create_user_response = self.create_user(self.test_user_name, self.test_user_password) self.assertEqual(create_user_response.status_code, status.HTTP_201_CREATED) ...
def create_user(self, name, password, email='cnefd@example.com'): url = url_for('api.userlistresource', _external=True) data = {'name': name, 'password': password, 'email': email} response = self.test_client.post( url, headers=self.get_accept_content_type_headers(), ...
This test verifies that a user can successfully retrieve a list of categories after creating two categories. It checks authentication, HTTP status codes (201 for creation, 200 for retrieval), and ensures the returned data contains exactly two entries with the expected names 'Error' and 'Warning' in order.
def test_retrieve_categories_list(self): """ Ensure we can retrieve the categories list """ create_user_response = self.create_user(self.test_user_name, self.test_user_password) self.assertEqual(create_user_response.status_code, status.HTTP_201_CREATED) new_category_name_...
def create_user(self, name, password, email='cnefd@example.com'): url = url_for('api.userlistresource', _external=True) data = {'name': name, 'password': password, 'email': email} response = self.test_client.post( url, headers=self.get_accept_content_type_headers(), ...
The main task of the code is to test the ability to update an existing category's name via a PATCH request. It verifies user authentication, category creation, successful PATCH update (200 OK), and confirms the updated name via a subsequent GET request, ensuring data consistency and correct HTTP status responses throug...
def test_update_category(self): """ Ensure we can update the name for an existing category """ create_user_response = self.create_user(self.test_user_name, self.test_user_password) self.assertEqual(create_user_response.status_code, status.HTTP_201_CREATED) new_category_na...
def create_user(self, name, password, email='cnefd@example.com'): url = url_for('api.userlistresource', _external=True) data = {'name': name, 'password': password, 'email': email} response = self.test_client.post( url, headers=self.get_accept_content_type_headers(), ...
The main task of the code is to test the creation and retrieval of a message in an IoT application. It verifies user authentication, message creation with a category, database record counts, and successful retrieval of the message via its URL, ensuring data consistency and correct HTTP status codes throughout the proce...
def test_create_and_retrieve_message(self): """ Ensure we can create a new message and then retrieve it """ create_user_response = self.create_user(self.test_user_name, self.test_user_password) self.assertEqual(create_user_response.status_code, status.HTTP_201_CREATED) ne...
def create_user(self, name, password, email='cnefd@example.com'): url = url_for('api.userlistresource', _external=True) data = {'name': name, 'password': password, 'email': email} response = self.test_client.post( url, headers=self.get_accept_content_type_headers(), ...
The main task of the code is to test that a duplicate message cannot be created. It verifies the initial successful creation of a message, retrieves it via its URL, and then attempts to create the same message again, expecting a 400 Bad Request error while ensuring the message count remains unchanged at 1.
def test_create_duplicated_message(self): """ Ensure we cannot create a duplicated Message """ create_user_response = self.create_user(self.test_user_name, self.test_user_password) self.assertEqual(create_user_response.status_code, status.HTTP_201_CREATED) new_message_mes...
def create_user(self, name, password, email='cnefd@example.com'): url = url_for('api.userlistresource', _external=True) data = {'name': name, 'password': password, 'email': email} response = self.test_client.post( url, headers=self.get_accept_content_type_headers(), ...
This test verifies the correct retrieval of paginated messages from an API. It creates two test messages, then checks that the first page returns both items with proper pagination metadata, while the second page correctly returns no results and shows the previous page link. The test ensures proper handling of authentic...
def test_retrieve_messages_list(self): """ Ensure we can retrieve the messages paginated list """ create_user_response = self.create_user(self.test_user_name, self.test_user_password) self.assertEqual(create_user_response.status_code, status.HTTP_201_CREATED) new_message_...
def create_user(self, name, password, email='cnefd@example.com'): url = url_for('api.userlistresource', _external=True) data = {'name': name, 'password': password, 'email': email} response = self.test_client.post( url, headers=self.get_accept_content_type_headers(), ...
This test verifies updating specific fields of an existing message via PATCH request. It creates a user and message, then updates 'printed_times' and 'printed_once' fields, confirming the update succeeds with 200 OK status and validates the modified data is correctly retrieved via GET request.
def test_update_message(self): """ Ensure we can update a single field for an existing message """ create_user_response = self.create_user(self.test_user_name, self.test_user_password) self.assertEqual(create_user_response.status_code, status.HTTP_201_CREATED) new_message...
def manage_reviewed_by_label(self, review_state, action, reviewed_user): base_dict = self.hook_data.get("issue", self.hook_data.get("pull_request")) user_label = f"{self.reviewed_by_prefix}{reviewed_user}" pr_owner = base_dict["user"]["login"] if pr_owner == reviewed_user: re...
This function processes user comments to add or remove specific labels on a pull request. It checks if the requested label is predefined, skips SonarSource comments, and applies the 'remove' or 'add' action. For 'lgtm', it uses a dedicated method to manage approval states, while other labels are directly added/removed....
def label_by_user_comment(self, pull_request, user_request, remove, reviewed_user): if not any( user_request.lower().startswith(label_name) for label_name in USER_LABELS_DICT ): self.app.logger.info( f"Label {user_request} is not a predefined one, will...
def set_run_tox_check_pending(self, pull_request): if not self.tox_enabled: return self.app.logger.info( f"{self.repository_name}: Processing set tox check pending" ) last_commit = self._get_last_commit(pull_request) last_commit.create_status( ...
This method processes user commands for a pull request, triggering actions like running tox checks or cherry-picking commits. It parses the command, determines if it's a cancellation, executes the corresponding operation, and applies/removes labels on the pull request based on the user's input and context.
def user_commands(self, command, pull_request, reviewed_user): remove = False self.app.logger.info( f"{self.repository_name}: Processing label/user command {command} by user {reviewed_user}" ) command_and_args = command.split() _command = command_and_args[0] i...
def basepairs_closed(structure): """test if all brackets are closed correctly in a dot-bracket string""" try: bp_map = get_basepair_indices_from_dotbracket(structure) return True except (ValueError, KeyError): return False def hairpin_loops_long_enough(structure): """check if any paired si...
The function checks if a dotbracket RNA/DNA secondary structure is valid by verifying base pair closure, hairpin loop lengths (>3), presence of base pairs, and optionally disallowing isolated base pairs. It returns True if all criteria are met, ensuring structural plausibility.
def is_likely_to_be_valid_structure(structure, allow_isolated_bps=False): """tests if a structure in dotbracket format is likely to be a valid structure: basepairs closed, length of hairpin loops (>3), presence of basepairs and optionally isolated base pairs""" if not basepairs_closed(structure): return ...
def dotbracket_to_coarsegrained_lev1(dotbracketstring): """transform a full dotbracket representation to a coarse-grained (type 1 as defined in Janssen, Reeder, Giegerich (2008). BMC bioinformatics)""" fine_grained_to_coarse_grained_symbol = {'(': '[', ')': ']', '.': '_'} basepair_index_mapping = get_basep...
This function converts a dotbracket string into a coarse-grained structural representation based on the specified `shape_level` (1, 2, or 5). It delegates to level-specific helper functions (`lev1`, `lev2`, `lev5`) to process the input, raising an error for unsupported levels.
def dotbracket_to_coarsegrained_for_level(dotbacketstring, shape_level): if shape_level == 1: return dotbracket_to_coarsegrained_lev1(dotbacketstring) elif shape_level == 2: return dotbracket_to_coarsegrained_lev2(dotbacketstring) elif shape_level == 5: return dotbracket_to_coarsegrained_lev5...
def parse_input(filename): output = [] with open(filename, "r") as file: for line in file: output.append(int(line.strip())) return output def get_deltas(adapters: list, output: bool = True): prev_voltage = 0 delta_dict = {} for adapter in adapters: delta = adapter - p...
The main task of the code is to process a list of adapters by sorting them, calculating voltage differences between consecutive adapters, and determining the number of valid ways to connect them based on allowed voltage gaps.
def main(): adapters = parse_input("day10") adapters.sort() get_deltas(adapters) find_valid_connections(adapters)
def readCipher(inpath="day9"): with open(inpath, 'r') as infile: return list(map(int, infile.read().splitlines())) def part1(cipher): for i in range(25, len(cipher)): if not isValid(i, cipher): return cipher[i] def part2(cipher): target = part1(cipher) for i, num in enumerate...
The main task of the code is to read a cipher, compute results from two parts (part1 and part2) using the cipher, and print the outcomes. It executes part1 and part2 functions on the cipher data, displaying their results in a formatted output.
def main(): cipher = readCipher() print(f"Part 1: {part1(cipher)}\nPart 2: {part2(cipher)}")
def calculate_AO(self): sma_5 = self.sma(self.price_data[-5:], 5) sma_34 = self.sma(self.price_data[-34:], 34) append_list_as_row('smas.csv', [sma_5, sma_34]) #print(34,sma_34) #print(5,sma_5) self.ao.append(sma_5 - sma_34) append_list_as_row('ao.csv', [sma_5-sma_...
The code's main task is to analyze price data for trading signals. It checks if at least 34 data points exist, calculates AO values, appends the latest price to buy periods, and triggers swing checks when buy/sell points balance. If unbalanced, it initiates sell evaluation, supporting dynamic trading strategy adjustmen...
def check_AO(self): if len(self.price_data) >= 34 : self.calculate_AO() if len(self.buy_period) > 0: self.buy_period.append(self.price_data[-1]) if len(self.buy_ps) == len(self.sell_ps): self.check_swing() else: self...
def calculate_AO(self): sma_5 = self.sma(self.price_data[-5:], 5) sma_34 = self.sma(self.price_data[-34:], 34) append_list_as_row('smas.csv', [sma_5, sma_34]) #print(34,sma_34) #print(5,sma_5) self.ao.append(sma_5 - sma_34) append_list_as_row('ao.csv', [sma_5-sma_...
The code's main task is to analyze price data for a trading strategy by checking if sufficient historical data exists, calculating the AO indicator, appending new buy periods, and deciding between checking price swings or initiating sell actions based on the balance of buy and sell points. It manages trading signals by...
def check_AO(self): if len(self.price_data) >= 34 : self.calculate_AO() if len(self.buy_period) > 0: self.buy_period.append(self.price_data[-1]) if len(self.buy_ps) == len(self.sell_ps): self.check_swing() else: self...
def dictionary(): dic_list = [] with open('dictionary.txt', 'r', encoding='UTF-8') as words: for line in words.readlines(): dic = line.strip() dic_list.append(dic) return dic_list def quickSort(arr): less = [] pivotList = [] more = [] if len(arr) <= 1: ...
The code benchmarks and compares the performance of various sorting algorithms (quickSort, quickSortText, mergeSort, mergesort) on both unsorted and sorted lists. It measures execution time in microseconds, checks the first element post-sorting, and handles potential RecursionErrors. The task evaluates efficiency and c...
def main(): d = dictionary() print('Completed reading in', len(d), 'words to the list.') print('The first word in the dictionary list is:', d[0]) print('\t') print('SORTING UNSORTED LIST') d1 = list(d) print('The first word is: {}'.format(d1[0])) start = time.clock() qsorted = quick...
def draw_background(): screen.fill(color_background) def draw_box(box, color): top_left = get_box_coords(box) pg.draw.rect(screen, color, pg.Rect(top_left, (box_length, box_length))) def draw_fill_last_tile(): if last_box_tile is not None: #at start it is None box, tile = last_box_tile ...
The function `draw_all` renders a game board's visual elements by drawing the background, highlighting the next playable box, greying out inaccessible boxes, and displaying tiles (crosses/circles) and box symbols (large crosses/circles) based on the board's state. It iterates through 9x9 tiles to render individual symb...
def draw_all(board): draw_background() for i in range(9): #draw box colors if i == board.get_next_box() or ( board.get_next_box() == -1 and board.check_box_accessible(i)): #highlight the next box– highlight ALL if can go in any box draw_box(i, color_box_highlight) ...
def draw_all(board): draw_background() for i in range(9): #draw box colors if i == board.get_next_box() or ( board.get_next_box() == -1 and board.check_box_accessible(i)): #highlight the next box– highlight ALL if can go in any box draw_box(i, color_box_highlight) ...
This function handles the main game loop, processing events like quitting, drawing the board, and handling player mouse clicks. It detects mouse releases to trigger tile placement, checks for valid moves, updates the game state, switches players, and displays win messages or errors. If a win occurs, it resets the game....
def game_loop(): #exiting for event in pg.event.get(): if event.type == pg.QUIT: sys.exit() #------DRAWING------- draw_all(board) #------PLAYER CLICKING------ global was_pressed #this var is so that we only process a click # the moment it was released, ...
def get_colors(size: int, kwargs: Dict[str, Any], base_color: str = COLORS['BLUE']) -> None: if 'color' not in kwargs: kwargs['color'] = [base_color] * size elif kwargs['color'] == 'random': kwargs['color'] = get_random_colors_from_dict(size) elif kwargs['...
The main task of the code is to generate a bar chart visualizing the distribution of a discrete feature in a DataFrame, either by counts or frequencies, while returning a DataFrame containing the unique values, their counts, and percentages. It allows customization of plot appearance, grid settings, labels, and support...
def plot_hist_discrete_feature(ax: plt.Axes, dataframe: pd.DataFrame, column: str, frequency: bool = False, **kwargs) -> pd.DataFrame: """ Plot a histogram for a specified column in a Dat...
def get_colors(size: int, kwargs: Dict[str, Any], base_color: str = COLORS['BLUE']) -> None: if 'color' not in kwargs: kwargs['color'] = [base_color] * size elif kwargs['color'] == 'random': kwargs['color'] = get_random_colors_from_dict(size) elif kwargs['...
The function visualizes the distribution of a target column across groups in a DataFrame, either as population counts or frequency percentages, with customizable plot styles. It returns a DataFrame containing the computed distribution values, enabling analysis of group-target relationships through bar plots with adjust...
def plot_groupby(ax: plt.Axes, dataframe: pd.DataFrame, group: str, target: str, frequency: bool = False, **kwargs) -> pd.DataFrame: """ Plot the distribution of a group and target column in a DataFrame. Parameters: ...
def get_colors(size: int, kwargs: Dict[str, Any], base_color: str = COLORS['BLUE']) -> None: if 'color' not in kwargs: kwargs['color'] = [base_color] * size elif kwargs['color'] == 'random': kwargs['color'] = get_random_colors_from_dict(size) elif kwargs['...
This function generates a boxplot using seaborn for specified columns in a DataFrame, allowing customization of colors, median/outlier styles, grid settings, titles, and saving the plot. It adjusts colors dynamically, modifies plot elements like labels and spines, and supports saving to a file.
def plot_boxplot(ax: plt.Axes, dataframe: pd.DataFrame, x: str, y: str, **kwargs) -> None: """ Plot a boxplot for a specified x and y column in a DataFrame. Parameters: ----------- ax (plt.Axes): The Axes object to plot ...
def get_colors(size: int, kwargs: Dict[str, Any], base_color: str = COLORS['BLUE']) -> None: if 'color' not in kwargs: kwargs['color'] = [base_color] * size elif kwargs['color'] == 'random': kwargs['color'] = get_random_colors_from_dict(size) elif kwargs['...
The function plots feature importances using a bar chart, sorts features by importance, customizes plot colors and labels, and returns a dictionary or transposed DataFrame of features and their corresponding importances.
def plot_feature_importance(ax: plt.Axes, features: pd.Index, importances: np.ndarray, **kwargs) -> Dict[str, float]: """ Plot feature importances. Parameters: ----------- ax (plt.Axes): The plot's axes. ...
def establish_connection(): host = socket.gethostname() port = 4001 client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_socket.connect((host, port)) print(client_socket) #Connection establishment message message = client_socket.recv(1024) if(message.decode()=="...
The main task of the code is to create a voter login interface with OTP authentication. It establishes a connection, generates a QR code for TOTP, collects user credentials (ID, password, OTP), and triggers server login validation. The interface dynamically updates the GUI, handles connection failures, and prepares dat...
def voter_login(root,frame1): client_socket = establish_connection() if(client_socket == 'Failed'): message = "Connection failed" failed_return(root,frame1,client_socket,message) root.title("Voter Login") for widget in frame1.winfo_children(): widget.destroy() userID =...
def create_game_over_surface(font1, font2): text1 = font1.render("Game over", True, pygame.Color('red')) text2 = font2.render("Press R to restart", True, pygame.Color('red')) w = max(text1.get_width(), text2.get_width()) h = text1.get_height() + text2.get_height() result = pygame.Surface((int(w * 1....
This code implements a snake game with hexagonal/triangular grid switching. It initializes Pygame, handles user input for movement and grid type changes, manages game states, draws game elements, and displays scores. The game runs in a loop, updating the screen at 5 FPS, and restarts upon key presses, with a game-over ...
def main(): pygame.init() win = pygame.display.set_mode((1280, 720)) pygame.display.set_caption("Grids") font1 = pygame.font.SysFont('serif', int(win.get_width() / 20)) font2 = pygame.font.SysFont('serif', int(win.get_width() / 30)) font3 = pygame.font.SysFont('serif', int(win.get_width() / 40))...
def load(self): with open("data.json", "r+") as f: data = json.load(f) return data def get_data_user(self, id): self.update_id() data = self.load() for i in data["data"]: id_user = i[0] if id_user == id: return i def get_all_use...
The main task of the code is to delete a user from a JSON data file by their ID. It loads the data, checks if the user exists, removes the user from the list, updates the file, and calls a method to adjust IDs.
def delete_user(self, id): data = self.load() user = self.get_data_user(id) all_users = self.get_all_users() if user in all_users: data["data"].pop((id-1)) print(f"{user} was deleted") with open("data.json", "w") as f: json.dump(data, f...
def get_l1_regularization(model): regularization_loss = 0 for name, param in model.named_parameters(): if 'weight' in name: regularization_loss += torch.sum(abs(param)) return regularization_loss def get_clip_value(gn_container, ref_window): if ref_window == -1: value = sum(g...
This code trains a neural network model using specified configurations, tracking training/validation losses and accuracies over epochs. It applies gradient clipping, L1 regularization, and adjusts learning rates. The best model is saved based on validation accuracy, while logging gradients and metrics. Final outputs in...
def train(best_model_path, last_model_path, config, criterion, data, logger, model, optimizer): best_state = { 'val acc': 0, 'train acc':0, 'epoch': 0 } features, labels, idx_train, idx_val, idx_test = data[1], data[2], data[3], data[4], data[5] train_losses = np.zeros(confi...
def get_dgl_dataset(dataroot, dataset): dglcitationgraph._normalize = dummy_normalization dglcitationgraph._preprocess_features = dummy_normalization if dataset == 'cora': graph = dgl.data.CoraDataset() elif dataset in ['citeseer', 'pubmed']: graph = dgl.data.CitationGraphDataset(name=d...
The function `load_data` loads and preprocesses graph datasets (via DGL or PyG) based on the configuration. It validates the dataset, constructs the graph, applies feature normalization if specified, adds self-loops if enabled, and returns the processed graph skeleton, features, labels, and masks (train/val/test). The ...
def load_data(config): if not config['data']['dataset'] in config['data']['all_datasets']: raise NotImplementedError else: if config['data']['implement'] == 'dgl': graph = get_dgl_dataset(dataroot=config['path']['dataroot'], dataset=config['data']...
def sanity_check(config): assert config['data']['dataset'] in config['data']['all_datasets'] assert config['data']['implement'] in ['dgl', 'pyg'] assert config['arch']['implement'] in ['dgl', 'pyg'] assert config['arch']['activation'][0] in ['relu', 'lkrelu', 'elu'] #assert config['arch']['unit'] in...
The main task of the code is to configure and add a `FileStorageObserver` for logging experiments. It validates the config, creates a log directory, generates a comment from the config, constructs a file storage path using config parameters, and appends the observer to `ex.observers` for tracking experimental data. The...
def add_observer(config, command_name, logger): ''' config: dictionary; its keys and values are the variables setting in 3the cfg function typically we do not need to use command_name and logger here ''' sanity_check(config) post_processing(config) os.makedirs(config['path']['log_dir'], exis...
def load_tasks(): if os.path.exists("tasks.json"): with open("tasks.json", "r") as file: tasks = json.load(file) return tasks else: return {"tasks": []} def display_tasks(tasks_listbox, tasks): tasks_listbox.delete(0, tk.END) if not tasks["tasks"]: tasks_listb...
The main task of the code is to create a To-Do List GUI application using Tkinter. It allows users to add, update, delete, and view tasks through a graphical interface with input fields, buttons, and a listbox. The tasks are loaded initially, displayed in the listbox, and managed via functions linked to buttons like "A...
def main(): tasks = load_tasks() root = tk.Tk() root.title("To-Do List") root.geometry("450x400") tasks_listbox = tk.Listbox(root, width=50, height=10, bg="#f0f0f0", selectbackground="#a6a6a6") tasks_listbox.pack(pady=10) display_tasks(tasks_listbox, tasks) label_title = tk.Label(ro...
def first(self, symbol, from_term): result = set() if symbol in self.grammar.terminals or symbol == "epsilon": result.add(symbol) elif symbol in self.grammar.nonterminals: for nont, term in self.grammar.productions: if nont == symbol: ...
This function determines the appropriate production rule for a given nonterminal and terminal symbol in a grammar. It checks if the nonterminal is a terminal or $, returning "except" or "pop" if matched. For nonterminals, it computes the FIRST set, checks for terminal matches, and retrieves the corresponding rule. If t...
def find_production(self, nonterminal, terminal): if nonterminal in self.grammar.terminals.union('$'): if nonterminal == terminal: if terminal == '$': return "except" return "pop" elif nonterminal in self.grammar.nonterminals: r...
def get_hour_OD(self): print("\nNumber of entries in original dataframe: ", len(self.bookings_df.index)) #filter bookings data self.bookings_df=self.bookings_df.loc[(self.bookings_df['duration']>3*60) & (self.bookings_df['duration']<90*60)] self.bookings_df=self.bookings_df.loc[self.book...
The code initializes a scenario-based simulation by loading configuration parameters from a JSON file, calculating key operational metrics (e.g., battery autonomy, charging rates), reading trip and grid data, processing OD matrices, and setting up charging station placements. It prepares essential variables for modelin...
def __init__(self, scenario_conf): self.json_file=scenario_conf self.scenario=json.load(open(self.json_file,"r")) self.battery_capacity_reduced=self.scenario["battery_capacity"]*(self.scenario["max_charging_th"]-self.scenario["min_charging_th"]) self.dist_autonomy=self.battery_capacity_r...
def pacify(): tap(pacify_X, pacify_Y) def communicate(): tap(communicate_X, communicate_Y) def punish(): tap(punish_X, punish_Y) def intimidate(): tap(intimidate_X, intimidate_Y)
The code identifies an action from input speech, executes the corresponding function (pacify, communicate, punish, intimidate), and returns whether the action was successfully performed. If the action is unrecognized, it notifies the user and returns False.
def do_action(speech): match = phrases.action(speech) print("Appropriate action: "+match) acted = True print("Acting...",end="") if match == "pacify": pacify() elif match =="communicate": communicate() elif match == "punish": punish() elif match == "intimidate": ...
def tap(x,y): call("adb -s {sid} shell input tap {x} {y}".format(sid=sid,x=x,y=y)) def skip(): print("tap -> skip") tap(skip_X, skip_Y) time.sleep(DELAY_SKIP) print("tap -> anywhere") tap(congrats_X, congrats_Y) time.sleep(DELAY_CONGRATS) def back(): call("adb -s {sid} shell input keyeve...
The code automates a recruitment process by simulating a tap action at coordinates (recruit_X, recruit_Y), waiting for a predefined delay, skipping a step, and then returning back. It prints status updates for each action.
def recruit(): print("tap -> recruit") tap(recruit_X, recruit_Y) time.sleep(DELAY_RECRUIT) skip() print("<- back") back()
def _start_loop(self): repeat = True while self.IS_RUNNING: self.word = get_random_word() self.attempted_letters = [] self.display = ['_' for _ in self.word] self.attempts_available = math.ceil(len(self.word) / 2) self.guessed_letters = [] ...
The code's main task is to execute a word guessing game by printing a title, initiating the game loop, displaying results, and showing leaderboards. It sets the game state to running, processes the game loop, and outputs outcomes and rankings after completion.
def run(self): art.tprint('Guess The Word') self.IS_RUNNING = True self._start_loop() self._print_results() self._show_leaders()
def snr_rangeEquation_BPSK_pulses(Pt, Gt, Gr, sigma, wavelength, R, B, F, L, T, n_p, n_c): """"SNR of range equation with coherent processing (CP) \tn_p := number of pulses \tn_c := number of chips """ return snr_rangeEquation_CP(Pt, Gt, Gr, sigma, wavelength, R, B, F, L, T, n_p, n_c) def snr_rangeE...
The code performs three radar system analysis tasks: (1) Plots BPSK SNR vs. target distance for varying transmit powers and radar cross-sections (RCS), comparing results to a threshold. (2) Evaluates SNR impact of CPI time and duty factor on detection range. (3) Generates 2D contour plots showing minimum detectable ran...
def main(): import numpy as np import matplotlib.pyplot as plt ## problem 1 ############################################################# # given antenna_diameter= 1.5*(0.0254*12) # convert feet to meters fc = 10e9 B = 10e6 Ncode = 13 L = 10**(8/10) # 8dB F = 10**(6/10) # 5dB ...
def VG_col_chng(): T7.config(bg='green') T6.config(bg='red') F6.delete("Ta6") F6.delete("Ta8A") F6.delete("Ta8B") def grip_attach(): global B14 B14= Button(F5, text="YES", bg="yellow", font="bold, 12", relief=RAISED, borderwidth=10, command=lambda:[ B14.destroy(), L9.pack_forget(), L10....
The code's main task is to verify user selection of the correct gripper type (V-Gripper) and confirm attachment of either vertical or horizontal grippers to an EOT hook. It displays prompts, manages GUI elements, and triggers actions like color changes and function calls based on user input (YES/NO) to proceed with gri...
def pose_verify(): global L8 L8=Label(F5, text="The system suggested to use V-Gripper.\n Is it right?", bg='gray',fg='white', font='bold, 20') L8.pack() global L9 L9= Label(F5, text=" Please attach Vertical Gripper to EOT hook. \n Finished?", bg='gray', fg='white', font='bold, 20') global L10 ...
def eat_if(self, *matches: TokenKind) -> Optional[Token]: token = self.peek() if token is None: return None if token.kind in matches: self.eat() return token return None def unary_node(kind: TokenKind, content): base = {} assert kind in [Toke...
The main task of the code is to parse unary expressions, handling unary minus, parenthesized expressions, and literals (variables/numbers). It recursively constructs an abstract syntax tree (AST) with nodes representing these constructs, raising errors for unexpected tokens.
def parse_unary(self): if self.eat_if(TokenKind.minus): return unary_node(TokenKind.minus, self.parse_unary()) elif self.eat_if(TokenKind.open_paren): content = self.parse_expr() self.consume(TokenKind.closed_paren) return paren_node(content) elif...
def Reset(self): self.StopTcpServer() self.StartTcpServer() self.SendVideo = Thread(target=self.sendvideo) self.ReadData = Thread(target=self.readdata) self.SendVideo.start() self.ReadData.start() def stopMode(self): try: stop_thread(self.infraredRun) ...
This function establishes a TCP connection to receive and process client commands, parsing incoming data to control hardware components like motors, servos, LEDs, and sensors. It handles command execution, mode switching, and thread management for real-time device operations, with error handling for connection failures...
def readdata(self): try: try: self.connection1, self.client_address1 = self.server_socket1.accept() print("Client connection successful !") except: print("Client connect failed") restCmd = "" self.server_socket1.clos...
def setup_earthdata_login_auth(endpoint): """ Set up the request library so that it authenticates against the given Earthdata Login endpoint and is able to track cookies between requests. This looks in the .netrc file first and if no credentials are found, it prompts for them. Valid endpoints i...
The main task of the code is to refresh an authentication token by first deleting the provided old token and then retrieving a new token from the specified URL. The function handles token lifecycle management by invalidating the existing token and acquiring a replacement, ensuring secure and up-to-date authentication c...
def refresh_token(old_token: str): setup_earthdata_login_auth(edl) delete_token(token_url,old_token) return get_token(token_url)
def foreachMemberOfClass(T : gdb.Type): """Generator to iterate through member of a class Args: T (gdb.Type): Input type Yields: field from T that is not is_base_class """ for field in T.fields(): if not field.is_base_class: yield field def arithmeticType2NumpyDtype(t ...
This function converts a GDB struct type into a list of NumPy dtypes, handling nested structures up to a specified recursion depth. It recursively processes struct members, converting basic types to NumPy equivalents and treating deeper structs as byte strings when exceeding depthMax. The output includes field names an...
def struct2dtype(T : gdb.Type, depth : int = 0, depthMax : int = 3): """Convert a gdb.Type to a list of np.dtype with potentially nested struct Nested struct are parsed as what would appear in a numpy structured array with the output name prefixed with outter class scope name Args: T (gdb.Type...
def getKokkosViewExtent(view : gdb.Value): """Get the size for all dimensions of a Kokkos::View as an numpy array Args: view (gdb.Value): Input Kokkos::View Returns: np.ndarray of the view's extents and np.ndarray of whether a dimension is dynamic (1) or static (0). In case of a scalar view, t...
The function `view2NumpyArray` converts a `Kokkos::View` (or `Kokkos::DualView`) from GDB into a NumPy array. It extracts the view's data pointer, dimensions, strides, data type, and span, then uses these to construct a NumPy array via `pointer2numpy`. The `depthMax` parameter limits recursion into nested structs, trea...
def view2NumpyArray(view : gdb.Value, depthMax : int = 3): """Create numpy array from a Kokkos::View Args: view (gdb.Value): Input Kokkos::View depthMax (int): Maximal allowed recursion depth into the nested struct. Any struct or class below this level will be treated as byte string of...
def parseArguments(self, inputArgs): parser = argparse.ArgumentParser() parser.add_argument("view", type=str, help="Name of the view object") parser.add_argument("ranges", type=int, nargs='*', default=[], help="Ranges for each of the dimens...
This code converts a Kokkos view to a NumPy array, extracts metadata like extents and strides, and displays the data. It uses pandas to format multi-dimensional arrays with structured or numeric types, handling ranges and index settings. The output includes view traits if specified, ensuring comprehensive data visualiz...
def invoke(self, inputArgs, from_tty): args = self.parseArguments(inputArgs) view = gdb.parse_and_eval(args.view) r = self.parseRanges(args.ranges) arr = view2NumpyArray(view, args.depthMax)[r] if args.viewTraits: # Print the view type traits extents, _ = ...
def is_leaseholder(self) -> bool: return self._raft_node.is_leader() def quorum_read(self, msg) -> None: # majority of all nodes, not counting with self majority = self.compute_excluding_majority() quorum = sample(self._node_ids, majority) for node_id in quorum: send(...
This function handles read requests in a distributed system. If the node is the leaseholder, it performs a direct read; otherwise, it probabilistically chooses between quorum-based or leaseholder-based reads to balance consistency and availability.
def handle_read(self, msg) -> None: if self.is_leaseholder(): if value := self._raft_node.direct_read(msg.body.key): reply(msg, type="read_ok", value=value) else: reply(msg, type="error", code=20, text="key not found") else: chosen_valu...
def bootstrap(): run_commands( "if [ ! -d downloads ]; then mkdir downloads; fi", "python bootstrap.py", ) def buildout(): initialize_south_svn_repo() run_commands("bin/buildout", ) def update_db(): run_commands( "bin/django syncdb", "bin/django migrate", )
The code's main task is to initialize a system by sequentially executing three key processes: bootstrapping (setting up initial configurations), building out components (assembling or constructing system elements), and updating the database (applying schema changes or data migrations) to prepare the application for ope...
def initialize(): bootstrap() buildout() update_db()
def render_help_dict(self, notes:dict, columns: int = 1): # display_cols = st.columns(columns) # for idx, title in enumerate(notes.keys()): # use_col = display_cols[idx % columns] # # use_col.text(title, help=notes[title]) # with use_col.popover(...
The main task of the code is to render a UI for searching and displaying "Blue Magic" spells with filters. It creates a title, search input, favorites toggle, filters results, displays spell counts, and renders each spell with dividers. Additional elements include a help popover and a URL bar for sources.
def render_all_blue(self, search_value: str = None, columns: int = 1, key: str='main'): title_cols = st.columns(columns) with title_cols[0 % columns]: st.subheader('!Blue Grimoire') with title_cols[1 % columns]: with st.popover('Help with !Blue'): ...
def _resolve_job_name(self, job_name:str) -> List[str]: """ A method to resolve any input FF5 job or unknown job option and return all associated actual jobs. Args: job_name (str): The name of the FF5 job class or unknown option to resolve to full name. Returns: ...
This method resolves input job names (or lists) into their full valid forms, validates them against known job codes, and sets internal job attributes. It converts single strings to lists, resolves each job name, checks validity, raises exceptions for invalid inputs, and updates job codes, tags, and hints.
def set_jobs(self, jobs: str|List[str]) -> list[str]: # TODO: Implement job dataclass objects instead of strings. """ A method which will take a job or unknown option or a list thereof and return a resolved list of all jobs. Args: job_name (str|List[str]): The name o...
def toggle_debug(self, debug: bool = None) -> bool: """ Change the app debug setting. This method can set the current debug setting to a specific true/false setting by passing in a value, or the existing state can be toggled without needing to know the current state by leaving em...
This code initializes a class to manage and process data related to game elements like bosses, blue magic spells, and hints. It sets up file paths, loads data from specified directories, initializes data structures, and compiles hints based on provided jobs. Debug mode and display style are configured, with automatic d...
def __init__( self, jobs: str|list[str] = None, debug: bool = False, display_style: str = 'text', ) -> None: self.debug = debug self.hints_path = Path("Enkibot") self.hints_repo_url = "https://github.com/Kyrosiris/Enkibot/" self._hints_raw = dict() ...
def init_label_dict(num_classes): label_dict = {} for i in range(num_classes): label_dict[i] = (0, 0, 0) return label_dict def get_target_label_short(eval_y): eval_y_short = [] for index, label in enumerate(eval_y): if label > 0: eval_y_short.append(index) return eval...
The function evaluates a TextCNN model on given data by calculating loss and metrics like F1-score, precision, and recall using confusion matrices. It processes data in batches, computes predictions from logits, updates a confusion matrix, and aggregates micro/macro F1 scores. The output includes average loss, F1-score...
def do_eval(sess, textCNN, evalX, evalY, num_classes): number_examples = len(evalX) eval_loss, eval_counter, eval_f1_score, eval_p, eval_r = 0.0, 0, 0.0, 0.0, 0.0 batch_size = FLAGS.batch_size label_dict_confuse_matrix = init_label_dict(num_classes) for start, end in zip(range(0, number_examples, ba...
def instantiate_weights(self): with tf.name_scope("embedding"): self.User_Embedding = tf.get_variable("user_embedding", shape=[self.vocab_size, self.embed_size], initializer=self.initializer) self.Label_Matrix = tf.get_variable("label_emb...
This code initializes a neural network model for multi-label classification. It sets up placeholders for input data, labels, and training flags; configures hyperparameters like learning rate and filters; instantiates model weights; defines inference logic, loss calculation (for multi-label tasks), and training operatio...
def __init__(self, FLAGS, filter_sizes, vocab_size, clip_gradients=5.0): self.num_classes = FLAGS.num_labels self.batch_size = FLAGS.batch_size self.sequence_length = FLAGS.sentence_len self.vocab_size = vocab_size self.embed_size = FLAGS.embed_size self.learning_rate = t...
def generate_steps(model_name: str, new_steps: str, generator: str = 'random(edge_coverage(100))', app_dir: str = None) -> List[Dict]: """ This is the top level builder for making test steps. Args: model_name: The name of the model file - no extension needed. new_steps: Whether to recalcula...
The function `prepare_steps` generates, expands, and prunes model steps based on a given model name and parameters. It first creates initial steps using `generate_steps`, then expands them with `step_expander`, and finally trims unnecessary steps via `prune_steps` using a decision map. The output is a refined list of m...
def prepare_steps(model_name, new_steps=False, decision_map=None): """ This uses the above functions to prepare the test steps. Args: model_name (str): The name of the model file - no extension needed. new_steps (bool): Whether to recalculate the model steps. Returns: model_ste...
def _removeIndents(self, content): return re.sub(r"\t", "", content) def _removeComments(self, content): noMultilineComments = re.sub(r"(OBTW(?<=OBTW)(.|\n)*?(?=TLDR)TLDR)", "", content) noComments = re.sub(r"BTW .*", "", noMultilineComments) return noComments def _tokenizeSourc...
The main task of the code is to process input content by removing indents and comments, then tokenize the cleaned source code into a list of tokens for further analysis or processing.
def process(self, content): self.tokens = [] content = self._removeIndents(content) content = self._removeComments(content) self._tokenizeSourceCode(content) return self.tokens
def _nextTokenIs(self, tokenType): if isEmpty(self.tokens): return None return self.tokens[0].lexemeType == tokenType def _popNextToken(self): if isEmpty(self.tokens): return None self._updateCurrentLineNumber() return self.tokens.pop(0) def _throwError...
This method checks if the next token matches the specified type. If it does, the token is consumed; otherwise, a SyntaxError with the given message is raised. It ensures proper token sequencing during parsing.
def _expectNextToken(self, tokenType, errorMessage): if self._nextTokenIs(tokenType): self._popNextToken() else: self._throwError(SyntaxError, errorMessage)
def _nextTokenIs(self, tokenType): if isEmpty(self.tokens): return None return self.tokens[0].lexemeType == tokenType def _popNextToken(self): if isEmpty(self.tokens): return None self._updateCurrentLineNumber() return self.tokens.pop(0) def _getValue(s...
This method performs explicit type casting by checking for a typecasting keyword, retrieving a variable's value, and applying the specified type conversion. It validates syntax elements like variable identifiers and type literals, throwing errors if they are missing. If all components are present, it returns the type-c...
def _ExplicitTypecast(self): if self._nextTokenIs(TOKEN.EXPLICIT_TYPECASTING_KEYWORD): self._popNextToken() if self._nextTokenIs(TOKEN.VARIABLE_IDENTIFIER): variableIdentifierToken = self._popNextToken() variableIdentifier = variableIdentifierToken.lexeme...
def _nextTokenIs(self, tokenType): if isEmpty(self.tokens): return None return self.tokens[0].lexemeType == tokenType def _popNextToken(self): if isEmpty(self.tokens): return None self._updateCurrentLineNumber() return self.tokens.pop(0) def _throwError...
This method handles variable type recasting by validating the existence of a declared variable, checking for a recasting keyword, parsing a type literal, casting the variable's value to the specified type, and updating the variable. It returns True on successful recasting or None if the variable isn't processed, throwi...
def _RecastingStatement(self): if self._nextTokenIs(TOKEN.VARIABLE_IDENTIFIER): variableIdentifierToken = self._popNextToken() variableIdentifier = variableIdentifierToken.lexeme value = None if variableIdentifier not in self.memory.keys(): self....
def _nextTokenIs(self, tokenType): if isEmpty(self.tokens): return None return self.tokens[0].lexemeType == tokenType def _popNextToken(self): if isEmpty(self.tokens): return None self._updateCurrentLineNumber() return self.tokens.pop(0) def _assign(sel...
This function processes an input statement by checking for the 'input' keyword and a variable identifier. If found, it prompts the user for input using easygui, assigns the input value to the variable, outputs the value, and returns True. If no valid input statement is detected, it returns None.
def _Input(self): children = [] if self._nextTokenIs(TOKEN.INPUT_KEYWORD): self._popNextToken() if self._nextTokenIs(TOKEN.VARIABLE_IDENTIFIER): variableIdentifierToken = self._popNextToken() variableIdentifier = variableIdentifierToken.lexeme ...
def create_input(model_name, batch): input_sequences=[] task_number=[] output_sequences = [] for idx, text in enumerate(batch['text']): input_sequences.append(text) task_number.append(0) output_sequences.append(get_output(model_name, batch['HS'][idx])) if batch['HS'][idx...
This function trains a sequence-to-sequence model (e.g., T5) by iterating over epochs, processing input/output sequences with tokenization, adding task-specific prompts, computing loss via forward passes, performing backpropagation, and validating the model. It tracks training loss, saves checkpoints, and visualizes lo...
def train_model(args, model, optimizer, tokenizer, s_wte, train_dataloader, val_dataloader): losses = [] for epoch in tqdm(range(args.start_epoch,args.epochs)): print("Training epoch %d" % epoch) print() model.train() t0 = time.time() for batch in tqdm(train_dataloader): ...
def arg_parse(): parser = argparse.ArgumentParser('arguments for training') # load pretrained model parser.add_argument('--model', type=str, default='T5', choices=['T5','BERT','ELECTRA']) parser.add_argument('--model_path', type=str, default=None, help='absolute path to model checkpoint') parser...
The main task of the code is to train and evaluate a model on the Hateval dataset. It loads training, validation, and test data, initializes a model and optimizer, trains the model using the training data, and evaluates it on the test set. The code also prints dataset lengths and sets a random seed for reproducibility.
def main(): args = arg_parse() set_seed(args.seed) # eval_batch_size = 1 if args.model in ['T5'] else args.batch_size eval_batch_size = args.batch_size train_dataset, val_dataset, test_dataset = load_hateval_data(args.data_path) train_dataloader = torch.utils.data.DataLoader(train_dataset['tra...
def getafulldata(dataset): con = sqlite3.connect("./data/location.s3db") alldata = pd.read_sql_query("SELECT BlightViolationNumber, Call311Number, AmbientCrime8, AmbientCrime7 - AmbientCrime8 as crime7, AmbientCrime6 - AmbientCrime7 as crime6, AmbientCall8, AmbientCall6 - AmbientCall7 as call6, AmbientCall7- Am...
The function `BenchMarks` evaluates multiple classifiers (`clfs`) on a dataset (via `datagetter`) to identify the best-performing model for precision, recall, F1-score, and ROC metrics. It iterates through each classifier, computes performance metrics, and tracks the classifier achieving the highest value for each metr...
def BenchMarks(clfs, datagetter=None): if datagetter is None: datagetter = lambda : getafulldata('Newdata') maxprecision =0 maxrecall=0 maxf1 =0 maxroc =0 bestprecision= None bestrecall= None bestf1 = None bestroc= None for clf in clfs: target, prediction = getPre...
def checkPrediction(clf): checkPredictionFromFactory(clf, lambda : getdata('Newdata')) def checkCompletePrediction(clf): checkPredictionFromFactory(clf, lambda : getalldata('Newdata')) def checkPredictionFromFactory(clf, datagetter): pred = getPrediction(clf, datagetter) printPrediction(pred,clf) def ge...
The code's main task is to demonstrate and test a classifier's prediction capabilities in three stages: basic, complete, and full predictions. It sequentially prints status labels ("basic," "complete," "full") and invokes corresponding validation functions, with the final stage using a lambda to fetch new data for eval...
def diplayPredictor(clf): print("basic") checkPrediction(clf) print("complete") checkCompletePrediction(clf) print("full") checkPredictionFromFactory(clf, lambda : getafulldata('Newdata'))
def _map_arg(value, maps): """ Return mapped 'value' if mapping found in 'maps' Input: value: str Path (string) in the host system Ex: '/host/path/something' maps: list List of length-2 tuples [('/host/path','/container/path')] Output: Mapped...
This function generates a command-line string from provided arguments and keyword arguments, applying parameter mappings if configured. It constructs the command by joining the 'exec' keyword with transformed arguments and keyword-value pairs, logs the command, and executes it via the instance's call method, returning ...
def _sh(*args, **kwargs): """ Run and return result of 'exec' in 'sh_local' with argument 'args/kwargs' """ if self._maps: _maps_t = self._maps.get(tuple, None) v = [ _map_arg(v, _maps_t) for v in args ] _maps_d = self._maps...
def _log(self, text, level="INFO"): if type(level) == type(str()): level = logging.getLevelName(level) self.logger.log(level, text) def _get_hashable_task(task): return (task[0], json.dumps(task[1]), task[2], task[3]) def _create_new_tor_client(self): if self.tor != None: ...
This function manages a task queue using Tor jobs, monitoring job status, handling timeouts, errors, and rescheduling. It tracks running/start jobs, logs system state, processes messages from Tor connections (e.g., task removal, rescheduling, IP blocking), and executes tasks when IPs are available. It ensures tasks are...
def _handle_queue(self): ip_warning_written = False start_wait_for_ip = None while not self.stop: self.lock.acquire() current = time.time() tj_running = len(list(filter(lambda x: x.start_time is not None, self.tor_jobs))) tj_starting = len(list(fi...
def get_answer(update): answers = update.poll.options ret = "" for answer in answers: if answer.voter_count == 1: ret = answer.text return ret def add_typing(update, context): context.bot.send_chat_action( chat_id=get_chat_id(update, context), action=telegram.C...
This function processes a poll response by recording the user's answer, updating the global index, and sending the next question. It appends the answer to a list, sends feedback messages, and triggers the next question in a sequence.
def poll_handler(update, context): global index global user_answers user_answer = Answer() user_answer.question = update.poll.question user_answer.answer = get_answer(update) add_typing(update, context) add_text_message(update, context, f"Your answer was {user_answer.answer}") add_text...
def read_page_no(): with open("../scrapers/page_pointer.json", "r") as file: data = json.load(file) return data["start"], data["end"] def anime_details(anime_url): driver = webdriver.Chrome() driver.get(anime_url) name = driver.find_element(By.TAG_NAME, "h1").text.strip() media_info =...
The code scrapes anime data from "anime-planet.com" using Selenium, iterating through multiple pages to collect anime links, extract details via the anime_details function, and save the data. It tracks runtime, manages page ranges, and clears temporary data after each page to optimize memory usage.
def get_all_anime(): anime_data = [] driver = webdriver.Chrome() start_page, end_page = read_page_no() total_running_time = 0 for page_id in range(start_page, end_page): start_time = time.time() url = f"https://www.anime-planet.com/anime/all?page={page_id}" driver.get(url) ...
def refine_predictions( features, probs, banks): feature_bank = banks["features"] probs_bank = banks["probs"] pred_labels, probs, pred_labels_all, pred_labels_hard = soft_k_nearest_neighbors( features, feature_bank, probs_bank ) return pred_labels, probs, pred_labels_all, pred_l...
This code trains a model using a semi-supervised learning approach with MoCo (Momentum Contrast) framework. It processes labeled and unlabeled data, computes pseudo-labels via entropy minimization, applies contrastive loss, updates memory banks, and optimizes through classification, contrastive, and divergence losses. ...
def train(epoch, net, moco_model, optimizer, trainloader, banks): loss = 0 acc = 0 net.train() moco_model.train() for batch_idx, batch in enumerate(trainloader): weak_x = batch[0].cuda() strong_x = batch[1].cuda() y = batch[2].cuda() idxs = batch[3].cuda() ...
def merge_outliers(self, c_dict): c_dict_new = defaultdict(dict) class_days = self.get_class_days(c_dict) # dictionary of class days print("class_days:") print(class_days) # for subj in class_days.keys(): for i in range(len(self.subjects)): days_list = class_days[self.subjects[i]] del class_days[s...
The main task of the code is to merge class schedules by detecting and resolving time conflicts between subjects. It copies and updates class dictionaries, extracts class days and times, and iterates through subjects to compare their time slots with others. Overlapping times are identified, and conflicting entries are ...
def merge_classes(self): class_dict_new = defaultdict(dict) class_dict_cur = self.class_dict.copy() class_dict_new = self.merge_outliers(class_dict_cur) # Update class_dict_cur to reflect the subjects and days left in it class_dict_cur = self.delete_overlap_dd(class_dict_new, class_dict_cur) """ print...
def __init__(self, running_time, config_type, reward_function=None, postpone_penalty=0, write_to=None) -> None: self.num_envs = 1 self.running_time = running_time self.counter = 0 self.nr_bad_assignments = 0 self.nr_postpone = 0 self.config_type = config_type self...
The `reset` method reinitializes the environment to its starting state, ensuring independence between episodes by not resetting random number generators. It reinitializes internal components via `__init__`, captures the initial state, and returns it alongside an empty dictionary, preparing the environment for a new epi...
def reset(self): """Resets the environment to an initial state and returns an initial observation. Note that this function should not reset the environment's random number generator(s); random variables in the environment's state should be sampled independently between multiple ...
def parse_shellcode(filename): file_lines = get_file_lines(filename) shellcode_string = filter_shellcode(file_lines) shellcode_bytes = string_to_bytes(shellcode_string) return shellcode_bytes def generate_random_key(length): import random return [random.randint(0, 255) for _ in range(length)] de...
The main task of the code is to encrypt shellcode using XOR with a user-provided or randomly generated key, then output the encrypted shellcode and key in a C++ header file format. It parses command-line arguments for input/output files, key selection, and formatting options, performs the XOR operation, and writes the ...
def main(): parser = argparse.ArgumentParser(prog="Shellcode encrypter", description="Encrypts shellcode by xoring it with a key") parser.add_argument("input_file", help="Input file containing the shellcode") parser.add_argument("-o", "--output-f...
def load_session(self): self.get_cookie() if 'sessionId' in self.cookie: session_id = self.cookie['sessionId'].value data = STORE.get_session(session_id) if data == None: session_id = STORE.create_session() data = STORE.get_session(sess...
This code handles GET requests by routing them to appropriate methods based on URL path components. It loads a session, parses the request path to identify collection type (e.g., "gardens" or "me") and ID, then retrieves specific garden data, lists all gardens, or fetches user data. Invalid paths return 404 errors.
def do_GET(self): """ Handle GET requests. """ self.load_session() coll, id, valid = self.parse_path() if not valid: self.response(404) return if coll == "gardens": if id: self.get_one_garden(id) else: ...
def load_session(self): self.get_cookie() if 'sessionId' in self.cookie: session_id = self.cookie['sessionId'].value data = STORE.get_session(session_id) if data == None: session_id = STORE.create_session() data = STORE.get_session(sess...
This code handles DELETE requests by determining the resource type (e.g., sessions, gardens, comments, flowers) from the URL path, validating the request, and executing the corresponding deletion operation. It uses session loading and path parsing to route requests to specific methods like delete_session(), delete_gard...
def do_DELETE(self): """ Handle DELETE requests. """ self.load_session() coll, id, valid = self.parse_path() if not valid: self.response(404) return if coll == "sessions" and not id: self.delete_session() elif coll == "gardens" and id:...
def load_map_data(map_file): memory_config = load_memory_config(map_file) sections = load_sections(map_file) return memory_config, sections def get_summary(memory_config, sections, as_json=False): def get_size(section): try: return sections[section]["size"] except KeyError: ...
This script processes a linker-generated MAP file to extract and report sizes of ELF files and archives. It uses command-line arguments to control output format (JSON or text), detail level (summary vs. per-archive/file breakdowns), and output destination. The tool reads the MAP file, parses memory configurations, and ...
def main(): parser = argparse.ArgumentParser("idf_size - a tool to print IDF elf file sizes") parser.add_argument( '--toolchain-prefix', help="Triplet prefix to add before objdump executable", default=DEFAULT_TOOLCHAIN_PREFIX) parser.add_argument( '--json', help="Ou...
def jump_to(nx, ny, nz): global x global y global z x, y, z = nx, ny, nz def get_value(s, name): # gets a value from the string, like: found, x = get_value('N1000G0X4.56Y34.78M6', 'X'), gives found = true, x = 4.56 pos = s.find(name) if pos == -1: return False, 0.0 numstr = '' for...
This code reads an NC file to parse G-code commands, extracts X/Y/Z coordinates, and controls a tool's movement by updating its position based on the parsed values, using global variables for tool settings and current coordinates.
def read_nc_file(fpath): # set the tool position to z50mm jump_to(0, 0, 50) # set a tool diameter of 3mm global rad rad = 1.5 # open the nc file f = open(fpath) global x global y global z nx = x ny = y nz = z while (True): line = f.readline() ...
def createSegments(self, data): data = literal_eval(data) edi = "" for seg in data: edi += self.ele_delimiter.join(seg) + self.seg_delimiter return edi def getLoopSegments(self, data, key): edi = "" try: for loop in data.get(key): e...
The function processes claim data to generate an EDI string by concatenating segments from the main loop and nested sub-loops (e.g., provider names, locations). It iterates through input data, appends segments using `createSegments`, processes sub-loop keys with `getLoopSegments`, and conditionally includes optional lo...
def Loop_2300_CLAIM_INFORMATION(self, data): assert data is not None edi = "" sub_loops_keys = ["has_loop_2310a_referring_provider_name", "has_loop_2310b_rendering_provider_name", "has_loop_2310c_service_facility_location_name", \ "has_loop_2310d_supervising_provider_name", "has_loop...
def createSegments(self, data): data = literal_eval(data) edi = "" for seg in data: edi += self.ele_delimiter.join(seg) + self.seg_delimiter return edi def getLoopSegments(self, data, key): edi = "" try: for loop in data.get(key): e...
This function processes hierarchical patient data to generate an EDI string. It iterates through input data, extracts hierarchical levels, combines segments from multiple loops (patient name, claim info), and concatenates them in sorted order to form a structured EDI output.
def Loop_2000C_PATIENT_HIERARCHIAL_LEVEL(self, data): assert data is not None hl23_edi = dict() for hl23 in data: hl23_level = int(hl23.get("Hierarchical ID Number")) hl23_data = self.createSegments(hl23.get("LOOP_segments")) + \ self.getLoopSegments(hl23,...
def createSegments(self, data): data = literal_eval(data) edi = "" for seg in data: edi += self.ele_delimiter.join(seg) + self.seg_delimiter return edi def getLoopSegments(self, data, key): edi = "" try: for loop in data.get(key): e...
This function processes hierarchical subscriber data to generate an EDI string. It iterates through input data, constructs EDI segments by combining specific loops (2010BA, 2010BB) and conditionally adds claim or patient hierarchy loops. Results are stored in a dictionary keyed by hierarchical levels, then concatenated...
def Loop_2000B_SUBSCRIBER_HIERARCHICAL_LEVEL(self, data): assert data is not None hl22_edi = dict() for hl22 in data: hl22_level = int(hl22.get("Hierarchical ID Number")) hl22_data = self.createSegments(hl22.get("LOOP_segments")) + \ self.getLoopSegments(h...
def createSegments(self, data): data = literal_eval(data) edi = "" for seg in data: edi += self.ele_delimiter.join(seg) + self.seg_delimiter return edi def getLoopSegments(self, data, key): edi = "" try: for loop in data.get(key): e...
This function processes hierarchical billing provider data by constructing EDI segments. It iterates through input data, combines segments from multiple loops, recursively processes subscriber hierarchies, and concatenates results in sorted hierarchical order to generate a structured EDI output string.
def Loop_2000A_BILLING_PROVIDER_HIERARCHICAL_LEVEL(self, data): assert data is not None hl20_edi = dict() for hl20 in data: hl20_level = int(hl20.get("Hierarchical ID Number")) hl20_data = self.createSegments(hl20.get("LOOP_segments")) + \ self.getLoopSegm...
def GetGroups(name, token): con = Connection(Get_Server_Ip(), 8080) con.Send(f'G/{name}/NULL/{token}') code = con.WaitUntilRecv(format_incoming=RemoveNullTerminator) error = TokenErrorHandler(code) if error: return con.Send('Ready') groups = con.RecvList('GO', 'END') con.Close() return groups def GetTasks(na...
This function retrieves all user groups, fetches associated tasks for each group, creates structured Group objects with task lists and positions, and optionally sorts groups by position if specified. It handles empty data cases by returning empty lists.
def GetAllGroups(username, token, sort=True): groups = [] groupsraw = GetGroups(username, token) if groupsraw is None: return [] for group in groupsraw: tasksraw = GetTasks(username, token, group) tasks, pos = CreateTaskList(tasksraw) groups += [Group(group, tasks, int(pos))] if len(groups) > 1 and sort: ...
def GetTasks(name, token, group): con = Connection(Get_Server_Ip(), 8080) con.Send(f'R/{name}/{group}/{token}') code = con.WaitUntilRecv(format_incoming=RemoveNullTerminator) error = TokenErrorHandler(code) if error: return con.Send('Ready') updated_items = con.RecvList('GO', 'END') con.Close() return update...
This function handles updating a task's name and completion status via POST request. It retrieves task data, validates input, updates the specified task, and logs changes. If the task isn't found, it returns an error. The updated task is pushed back to the system, with a debug log detailing the change.
def updatetask(request): if request.method == 'POST': ToUpdate = request.POST.get("taskname", "") newname = request.POST.get("newname", "") if newname == '': newname = None username = request.POST.get("name", "") token = request.POST.get("token", "") group = request.POST.get("group", "") done = reques...
def GetTasks(name, token, group): con = Connection(Get_Server_Ip(), 8080) con.Send(f'R/{name}/{group}/{token}') code = con.WaitUntilRecv(format_incoming=RemoveNullTerminator) error = TokenErrorHandler(code) if error: return con.Send('Ready') updated_items = con.RecvList('GO', 'END') con.Close() return update...
The main task of the code is to handle a POST request for deleting a task. It retrieves task details, validates the task's existence, removes it from the user's task list, updates the tasks, and logs the action. If the task isn't found or the request isn't POST, it returns appropriate error messages.
def removetask(request): if request.method == 'POST': ToDelete = request.POST.get("taskname", "") ToDelete = unquote(ToDelete) username = request.POST.get("name", "") token = request.POST.get("token", "") group = request.POST.get("group", "") tasksraw = GetTasks(username, token, group) tasks, pos = Creat...
def RenameGroup(name, token, group, newname): con = Connection(Get_Server_Ip(), 8080) con.Send(f'N/{name}/{group}/{token}') code = con.WaitUntilRecv(format_incoming=RemoveNullTerminator) error = TokenErrorHandler(code) if error: return con.Send('Ready') con.WaitUntilRecv(format_incoming=RemoveNullTerminator) ...
The code handles a POST request to rename a group by extracting parameters (username, token, group, newname) from the request, invoking the RenameGroup function, logging the action, and returning a success response. Non-POST requests trigger a warning log and an error response.
def renamegroup(request): if request.method == 'POST': newname = request.POST.get("newname", "") username = request.POST.get("name", "") token = request.POST.get("token", "") group = request.POST.get("group", "") RenameGroup(username, token, group, newname) debug_log(f"User '{username}' renamed group {grou...
def DeleteTasks(name, group, token): con = Connection(Get_Server_Ip(), 8080) con.Send(f'D/{name}/{group}/{token}') code = con.WaitUntilRecv(format_incoming=RemoveNullTerminator) error = TokenErrorHandler(code) if error: return con.Send('Ready') con.Close() def debug_log(text): cprint(f"[DEBUG]", "grey", 'on_c...
The code handles a POST request to delete a group by extracting the username, token, and group name from the request. It calls the DeleteTasks function with these parameters, logs a debug message upon successful deletion, and returns a "Success" response. If the request is not POST, it logs a warning and returns an err...
def delete_group(request): if request.method == 'POST': username = request.POST.get("name", "") token = request.POST.get("token", "") group = request.POST.get("group", "") DeleteTasks(username, group, token) debug_log(f"User '{username}' deleted group {group}.") return HttpResponse("Success") else: warn...
def GetAllGroups(username, token, sort=True): groups = [] groupsraw = GetGroups(username, token) if groupsraw is None: return [] for group in groupsraw: tasksraw = GetTasks(username, token, group) tasks, pos = CreateTaskList(tasksraw) groups += [Group(group, tasks, int(pos))] if len(groups) > 1 and sort: ...
This code updates the order of items within user groups based on POST data. It parses new group configurations, compares them to existing groups, and triggers task updates when item orders change. The function handles authentication via token/name, processes group/item hierarchies, and logs updates without returning ac...
def UpdateItemOrder(request): if request.method == 'POST': token = request.POST.get("token", "") username = request.POST.get("name", "") newgroups = request.POST.get("newgroups" , "") oldgroups = GetAllGroups(username, token) masteritems = [] for i in oldgroups: masteritems += i.items itemdict = {} ...
def GetAllGroups(username, token, sort=True): groups = [] groupsraw = GetGroups(username, token) if groupsraw is None: return [] for group in groupsraw: tasksraw = GetTasks(username, token, group) tasks, pos = CreateTaskList(tasksraw) groups += [Group(group, tasks, int(pos))] if len(groups) > 1 and sort: ...
This function handles a POST request to update user group order by parsing 'newgroups' input, mapping old groups to their objects, updating each group's position, and pushing tasks with the new order. It validates the request method, processes token/username inputs, splits group data, adjusts positions, logs changes, a...
def UpdateGroupOrder(request): if request.method == 'POST': token = request.POST.get("token", "") username = request.POST.get("name", "") newgroups = request.POST.get("newgroups" , "") oldgroups = GetAllGroups(username, token) newgroups = newgroups.split('/') groupdict = {} for i in oldgroups: groupdi...
def GetAllGroups(username, token, sort=True): groups = [] groupsraw = GetGroups(username, token) if groupsraw is None: return [] for group in groupsraw: tasksraw = GetTasks(username, token, group) tasks, pos = CreateTaskList(tasksraw) groups += [Group(group, tasks, int(pos))] if len(groups) > 1 and sort: ...
The code handles a POST request to create a group by retrieving user credentials and group name from the request, fetching existing groups, invoking a task-pushing function, logging the creation, and returning a success response. Non-POST requests trigger a warning and an error message.
def creategroup(request): if request.method == 'POST': username = request.POST.get("name", "") token = request.POST.get("token", "") group = request.POST.get("group", "") groups = GetAllGroups(username, token) PushTasks(username, token, group, [], len(groups)) debug_log(f"User '{username}' created group {g...
def GetTasks(name, token, group): con = Connection(Get_Server_Ip(), 8080) con.Send(f'R/{name}/{group}/{token}') code = con.WaitUntilRecv(format_incoming=RemoveNullTerminator) error = TokenErrorHandler(code) if error: return con.Send('Ready') updated_items = con.RecvList('GO', 'END') con.Close() return update...
This function handles adding a new task via POST request. It validates input data, retrieves existing tasks, appends the new task (with generated ID and status), removes empty entries, and updates task storage. It logs success or warnings for non-POST requests.
def addtask(request): if request.method == 'POST': ToUpdate = request.POST.get("taskname", "") username = request.POST.get("name", "") token = request.POST.get("token", "") done = request.POST.get("done", "") group = request.POST.get("group", "") if group == "": raise NameError("Group is empty!") task...
def update_entry(): if debuglevel >= 2: my_logger.info('{time}, shooters.load_all_shooters.open_shooter_popup.update_entry.Called'.format( time=str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) )) # shooter guid_value = id_val...
The main task of the code is to determine whether to update or add a shooter entry based on the `_mode` value ("edit" or otherwise), then reload the main form and close the popup window. Debug logs track function calls and completion.
def determineAction(): if debuglevel >= 2: my_logger.info('{time}, shooters.load_all_shooters.open_shooter_popup.determineAction.Called'.format( time=str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) )) if load_form == False: ...
def build_new_qualifying_record_set(my_event): qual_definition = my_event["qualifying"] no_of_targets = int(qual_definition["no_of_targets"]) shots_per_target = int(qual_definition["no_of_shots"]) if debuglevel >= 1: my_logger.info('{time}, shooters.build_new_qualifying_record_set.Ca...
The code creates a popup window for managing shooter profiles, allowing users to add or edit details such as personal information, rifle specifications, scope data, and cartridge components. It dynamically builds UI elements with tabs for different sections, handles form input validation, and processes data to either i...
def open_shooter_popup(_mode, json_record, primary): if debuglevel >= 2: my_logger.info('{time}, shooters.load_all_shooters.open_shooter_popup.Called'.format( time=str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) )) if _mode != "add" and echojson == 1: ...
def skipWhitespace(self): while self.ch in [' ', '\t', '\n', '\r', ',']: self.readChar() def peekChar(self): if self.readPosition >= len(self.input): return 0 else: return self.input[self.readPosition] def readChar(self): if self.readPosition >= len(s...
This function identifies and returns the next token from input, handling operators (=, +, -, etc.), identifiers, numbers, strings, and special syntax rules for keywords like 'then', 'no', and 'execution', including validation and error checking for expected subsequent tokens.
def NextToken(self): tok: Token = Token() self.skipWhitespace() if self.ch == '=': if self.peekChar() == '=': ch = self.ch self.readChar() tok = Token(EQ, ch + self.ch) else: tok = self.newToken(ASSIGN, se...
def __create_suite(self, name) -> None: self.syntax['suite'] = dict({ 'name': name, 'tests': list(), 'executionOrder': list() }) def __create_tests(self, name, i) -> dict: test = dict({ 'name': name, 'params': list(), 'resul...
The code processes a stack of tokens to populate a syntax structure. It identifies SUITE/TEST/ORDER tokens, creates corresponding entries in `self.syntax`, and appends tests to suites. It uses `__create_suite`, `__create_tests`, and `__create_order` helper methods to build the syntax tree, ensuring proper nesting and e...
def populate(self) -> None: for i, tok in enumerate(self.stack): if tok.Type == SUITE and self.stack[i + 1].Type == IDENT: self.__create_suite(self.stack[i + 1].Literal) elif tok.Type == TEST and self.stack[i + 1].Type == IDENT: self.syntax['su...
def __parse_args(self) -> dict: """Parse the arguments given to the program. Returns a dictionary with the arguments.""" psr = argparse.ArgumentParser( prog="main.py", description="A program to store ngrams in a database and analyse " "them. To start interactive shell call progra...
The code executes a CLI program based on parsed arguments: starts a shell if no args or --shell is specified, creates a database with --create_db, transfers data with --transfer, or exits otherwise.
def run_cli(self) -> None: """Execute the program according to the passed arguments.""" args: dict = self.__parse_args() # if no arguments are supplied or user asks for shell, start shell if (len(sys.argv) == 1) or args["shell"]: Prompt().cmdloop() return ...
def insert_post_lists(page_html: str) -> str: with open("templates/postList.html", "r", encoding="utf8") as list_file: list_html = list_file.read() extraction = extract("\+item\+", list_html) page_html_matches = findall("({{posts(.*?)}})", page_html) for match in page_html_matches: items...
The main task of the code is to generate a final HTML page by combining a template with content from a specified page file. It reads a template and page HTML, processes the page content (including Markdown conversion and list insertion), extracts head content, replaces template placeholders with processed data, applies...
def apply_template(page_filepath: str, apply_vars_fn=None) -> str: with open("templates/page.html", "r", encoding="utf8") as template_file: template_html = template_file.read() with open(page_filepath, "r", encoding="utf8") as page_file: page_html = page_file.read() page_html = insert_post_...
def load_data(messages_filepath, categories_filepath, messages_file_encoding="utf-8", categories_file_encoding="utf-8"): """ Loads data from the given CSV files using the given corresponding encoding. @param messages_filepath: Messages data CSV file path. @...
The main task of the code is to process disaster message and category datasets by loading, cleaning, and saving the data into a SQLite database. It checks for three input filepaths, loads and merges the data, cleans it, and stores the cleaned dataset in a specified database file. If incorrect arguments are provided, it...
def main(): if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) ...
def check_slope(point): lineA = [(0,1),(0,0)] angleA = ang(point,lineA) return angleA < slope or (90 - angleA) < slope def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]...
This code enables mouse-based image cropping to extract a region of interest (ROI), applies edge detection and Hough transform to identify lines, computes their intersections, orders key points, and saves the processed ROI with calculated coordinates. The primary task is to interactively select an image region, analyze...
def mouse_crop(event, x, y, flags, param): # grab references to the global variables global x_start, y_start, x_end, y_end, finished, slope, cropping, coords # if the left mouse button was DOWN, start RECORDING # (x, y) coordinates and indicate that cropping is being if event == cv2...
def _create_feature_extractor(self, args): # Series of downconvolutions and bottleneck layers downconv_input = self.x # Determine how many possible downsamples to perform in each direction self.down_x = int(math.log2(args.n_x))-2 self.down_y = int(math.log2(args.n_y))-2 ...
This code initializes a TensorFlow model for a physics-informed neural network, setting up state variables, gradient placeholders, and parameters. It defines spatial discretization steps, normalization parameters, and loads a 3D mask for cylinder geometry. The code constructs a computational graph with feature extracti...
def __init__(self, args): # Placeholder for states and control inputs self.x = tf.Variable(np.zeros((args.batch_size*args.seq_length, args.n_x, args.n_y, args.n_z, 5), dtype=np.float32), trainable=False, name="state_values") self.grad_vals = tf.Variable(np.zeros((args.batch_size, args.seq_lengt...