dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_time(self,minute_entry,second_entry): minute = minute_entry.get() second = second_entry.get() if second == "": second = 0 else: second = float(second) if minute =="": pass else: second += float(minute)*60 ...
The main task of the code is to handle time entry input by retrieving start time, duration, and end time from widgets, validate the duration, update subclip details with calculated times, and refresh UI elements by clearing entries and setting new time values.
def on_time_entry_button(self): # when button is pressed get the data from time entry widgets self.start_time = self.get_time(self.start_time_entry_min,self.start_time_entry_sec) self.duration = self.get_time(self.duration_time_entry_min,self.duration_time_entry_sec) self.end_time =...
def frame_generate(self,frame_time,label): if frame_time > (self.clip_time-.08): frame_time = frame_time-.08 image_array = self.source_video.get_frame(frame_time) image_location = Image.fromarray(image_array) image_resized = image_location.resize((150,100)) image = I...
The main task of the code is to create a subclip from a video by validating time inputs, generating start/end frames, saving the subclip, and displaying error messages if invalid times are entered. It handles both valid and invalid time scenarios, resets time validation after processing, and ensures proper frame genera...
def on_create_subclip_button(self,source_window): if self.time_valid: # open start frame self.frame_generate(self.start_time,self.start_frame_label) # open end frame self.frame_generate(self.end_time,self.end_frame_label) # Slight fix to the issue of ...
def define_subclip_gui_components(self,source_window): self.subclip_info_label = tk.Label(self,text="Please Enter subclip information") # start time self.start_time_frame = tk.Frame(self.time_entry_frame,relief=tk.RIDGE,borderwidth=1) self.start_time_label = tk.Label(self.start_tim...
This code initializes a Tkinter GUI window for creating subclips from a video. It sets up variables to track subclip details, time calculations, and video data. The interface includes input fields, buttons to calculate/reset time, create subclips, and close the window. Widgets like frames and buttons are configured wit...
def __init__(self,source_window): tk.Toplevel.__init__(self,source_window) self.grab_set() # Variable set up self.number_of_subclips = source_window.number_of_subclips self.source_video = source_window.source_video_clip self.subclip_name = "" self.time_calculated...
def grad_descent(X, y, reg=0.0, lr=1e-5, eps=1e-6, max_iter=500, print_freq=20): """ This function takes in seven arguments: 1) X, the data with dimension m x (n + 1) 2) y, the label of data with dimension m x 1 3) reg, the parameter for regularization 4) lr, the l...
The function evaluates the accuracy of a softmax regression model across different regularization parameters (lambda_list). For each lambda, it performs gradient descent to find optimal weights, predicts test labels, computes accuracy, and stores results. It then plots accuracy vs. lambda and returns the lambda value t...
def accuracy_vs_lambda(X_train, y_train_OH, X_test, y_test, lambda_list): """ This function takes in five arguments: 1) X_train, the training data with dimension m x (n + 1) 2) y_train_OH, the label of training data with dimension m x 1 3) X_test, the validation data with dime...
def get_rowid(self) -> int: """Generates a random rowid from a list of number to use for quote search Returns: int: A number used as the rowid """ rows = Quote_Game.__rows if rows: row_id = random.choice(rows) rows.remove(row_id) ...
The main task of the code is to retrieve a random quote from a database using a rowid, fetch associated author information via the get_author() method, and return the quote string. It executes a SQL query with the rowid, extracts the quote text, triggers author data retrieval, and finally returns the quote.
def get_quote(self) -> str: """Query the database to get a quote using rowid number Call the get_author() method to get the author information and use it to generate hints Returns: str: The quote string """ row_id = self.get_rowid() if row_id: que...
def AddtoCustomer(johnDoe): default = 'INSERT INTO Customer(CustID, Created, LastSeen, TotalNoOfOrders, BasketSum, BasketAvg, PriceSum, PriceAvg, CustStatus, CustName) VALUES' unique = "("+str(johnDoe.custID) +",'"+ToAcceptableDate(johnDoe.created)+"','"+ToAcceptableDate(johnDoe.lastSeen)+"',"+str(johnDoe.total...
The main task of the code is to add a new customer (johnDoe) by calling multiple functions to populate various data fields: customer details, ID, email, phone numbers, and addresses. It delegates the addition of structured customer information across separate systems or databases through modular helper functions.
def AddCustomer(johnDoe): AddtoCustomer(johnDoe) AddToCustomerListID(johnDoe) AddToEmail(johnDoe) AddToPhoneNumbers(johnDoe) AddToAddresses(johnDoe)
def terminal(board): """ Returns True if game is over, False otherwise. """ if winner(board) is not None: return True # if no winner and at least one empty cell available for row in board: for cell in row: if cell is None: return False # else gam...
This code implements the minimax algorithm with alpha-beta pruning to determine the optimal move in a game. It recursively evaluates all possible actions, pruning branches where the outcome is worse than the current best. The function returns the best action and its utility value, prioritizing outcomes based on the cur...
def minimax_(board, prune): # with pruning if terminal(board): outcome = utility(board) return (None, outcome) player_turn = player(board) isBetterOutcome = isBetterOutcome_factory(player_turn) next_prune = prune_factory(player_turn) action_set = actions(board) action_outcome_...
def Guided_Image_Filter(im,p,r,eps): ''' This Function returns the output for Guided Image Filter applied on Input Image. Parameters ---------- im : Guidance Image p : Input Filter Image r : Radius of Kernel eps : Regularization parameter Returns ------- q :...
The function `TransmissionRefine` applies three guided filtering techniques—GIF, WGIF, and SKWGIF—to a normalized guidance image, using parameters like kernel radius, regularization, and dynamic range constants. It generates refined transmission maps and displays them using OpenCV, aiming to enhance image quality throu...
def TransmissionRefine(im, et, r, eps, lamda, N): ''' Parameters ---------- im : Guidance Image et : Input Filter Image r : Radius of kernel eps : Regularization Parameter lamda : small constant dependent on dynamic range N : Number of Pixels in the Input ima...
def is_portfolio_optimal(self): # Check for every market stock_name = '' units = 0 to_order = {} # Orders to be executed # Initial performance self._performance = self.get_potential_performance(stock_name, units)[0] # Check all stocks for key in self._...
This function manages trading orders by evaluating portfolio optimality, clearing executed orders, canceling non-strategic orders, and creating new buy/sell orders for assets needing adjustment, while tracking pending orders to avoid duplication.
def _order_manager(self, market_orders): # Get all orders, if none market is optimal with the stock to_order = self.is_portfolio_optimal() # Function to clear orders that have been executed self._clear_executed_orders(market_orders) # Funciton to cancel orders not in line with ...
def drop_duplicates(nested_list): """ drop the duplicates in a nested list :param nested_list: a nested list [[1, 3, 4, 6], [2, 4, 8, 3], [4, 1, 2, 3]] :return: nested list without duplicates combination [[[1, 3, 4, 6], [2, 4, 8, 3]] """ if nested_list == []: return [] elif contain...
The function `combine_two_sets` merges elements from `entry_list` into sublists of `nested_list`, appending each entry to generate new combinations. It recursively processes `entry_list`, appending its elements to `nested_list` sublists, then removes duplicates to return unique results. The core task is to create all p...
def combine_two_sets(entry_list, nested_list): """ :param entry_list: [1, 1, 3, 4, 5] :param nested_list: [[1, 1], [1, 3], [1, 4], [1, 5], [1, 3], [1, 4], [1, 5], [3, 4], [3, 5], [4, 5]] :return: [[3, 1, 1], [4, 1, 1], [4, 1, 3], [5, 1, 1], [5, 1, 3], [5, 1, 4], [5, 3, 4]] """ if entry_list == ...
def drop_duplicates(nested_list): """ drop the duplicates in a nested list :param nested_list: a nested list [[1, 3, 4, 6], [2, 4, 8, 3], [4, 1, 2, 3]] :return: nested list without duplicates combination [[[1, 3, 4, 6], [2, 4, 8, 3]] """ if nested_list == []: return [] elif contain...
Your returnThe function generates all unique pairs of elements from the input list, returning them as a list of lists. It recursively combines the first element with the rest of the list and appends combinations from the remaining elements, ensuring no duplicates. For example, given [1,2,3,4,5], it returns every possib...
def combination_of_2_in_list(list_value): """ :param list_value: [1, 2, 3, 4, 5] :return: [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]] """ if list_value == []: return [] else: return drop_duplicates(append_elements_with_v(first_of(list_value),...
def combination_of_2_in_list(list_value): """ :param list_value: [1, 2, 3, 4, 5] :return: [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]] """ if list_value == []: return [] else: return drop_duplicates(append_elements_with_v(first_of(list_value),...
This function generates all possible combinations of size `n` from the input list `list_value` using recursion. For `n=0`, it returns an empty list; for `n=1`, it returns single-element lists. For `n=2`, it uses a helper function to generate pairs. For larger `n`, it recursively combines elements with combinations of s...
def combination_of_n(list_value, n): """ :param list_value: [1, 2, 3, 4, 5] :param n: 3 :return: """ if n == 0: return [] elif n == 1: return [[x] for x in list_value] elif n == 2: return combination_of_2_in_list(list_value) else: return combine_two...
def convert_exp_to_list(input_string): output_list = [] n = 0 while n != len(input_string): # For each character in the string... if is_number(input_string[n]): # If it's a number... temp = input_string[n] # | while True: ...
The code evaluates a mathematical expression by first splitting it into tokens, validating each token as a number or operator, converting the expression to Reverse Polish Notation (RPN), and then solving the RPN-converted expression. The main task is to parse and compute arithmetic expressions using RPN conversion and ...
def calculator(expression): # Divide up the expression into a list of its constituent parts. exp_list = convert_exp_to_list(expression) # Check for invalid tokens in that list. for token in exp_list: if (not is_number(token)) and (not is_operator(token)): print('Invalid token: ' + t...
def drawDivisionLine(self, character, yo): self.drawLineSegment(character, 0, yo, self.getWidth()) def getHeight(self): return self.height*2 def drawDivisionCollumn(self, character, xo): self.drawCollumn(character, xo, 0, self.getHeight()) def getWidth(self): return self.width def drawPo...
The main task of the code is to draw a border around a grid or canvas by rendering horizontal lines at the top and bottom, vertical lines on the left and right, and placing corner characters at all four corners to form a framed boundary.
def drawBorder(self, cornerChar='@', horizontalChar='-', verticalChar='|'): self.drawDivisionLine(horizontalChar, 0) self.drawDivisionLine(horizontalChar, self.getHeight()-1) self.drawDivisionCollumn(verticalChar, 0) self.drawDivisionCollumn(verticalChar, self.getWidth()-1) self....
def clear(self): for i in range(self.height): for j in range(self.width): self.surface[i][j] = ' ' def drawBorder(self, cornerChar='@', horizontalChar='-', verticalChar='|'): self.drawDivisionLine(horizontalChar, 0) self.drawDivisionLine(horizontalChar, self.getHeight...
The main task of the code is to update and display the game scene by clearing the screen, drawing a border, rendering all objects in the scene, printing the current state as a string, and controlling the frame rate using a sleep delay.
def update_print(self): self.clear() self.drawBorder() for object in self.scene: self.drawObject(object) os.system('clear') print(self.toString()) time.sleep(1/self.framerate)
def _make_baselines(self, x_value, x_baselines): # If baseline is not provided default to im min and max values if x_baselines is None: x_baselines = [] x_baselines.append(np.zeros_like(x_value)) # x_baselines.append(np.min(x_value) * np.ones_like(x_value)) # x_baselines.append(np.max(x_...
The function computes XRAI (eXplainable Regression via Attention) attribution maps for input data using Integrated Gradients (IG) or provided base attributions. It validates input shapes, generates segments if unspecified, applies XRAI/XRAI_fast algorithms, and returns results including attribution maps, baselines, and...
def GetMaskWithDetails(self, model, x_value, one_hot, image_nums, baselines=None, segments=None, base_attribution=None, ...
def table_from_pointer(self, ptr): key = self.table_key_from_pointer(ptr) return self.tables[key] def cursor_from_pointer(self, ptr): key = self.cursor_key_from_pointer(ptr) return self.cursors[key] def next_(self, cur): cursor = self.cursor_from_pointer(cur) assert curs...
This code filters rows in a SQLite virtual table by parsing constraints from JSON data, mapping input arguments to method parameters, invoking a dynamically selected table method, and setting the result as a generator for the cursor.
def filter_(self, pVtabCursor, idxNum, idxStr, argc, argv): table = self.table_from_pointer(pVtabCursor.pVtab) cursor = self.cursor_from_pointer(pVtabCursor) idx_data = json.loads(self.ffi.string(idxStr)) constraints = idx_data["constraints"] exprs = [self.interface.get_py_val(ar...
def build_Net(self, mothers): for idx, mother in enumerate(mothers): if (self._id != idx) \ and (np.linalg.norm(np.array(self._location) - np.array(mother._location)) < self.network_distance) \ and (self._SES == mother._SES): self._network.appe...
This function increments gestational age by 1 and triggers pregnancy-related actions: builds networks at start, updates health predictions, schedules antenatal/postnatal visits based on age ranges, initiates delivery at week 9, and updates health status using a logistic function. Network interactions and care visits de...
def increase_age(self, l4_quality, l2_quality, health_outcomes, L2_net_capacity, AP_net_capacity, mothers, ts): """increase gestational age (step)""" self._gest_age = self._gest_age + 1 if self.flag_network: if ts == 0: self.build_Net(mothers) if self._g...
def get_S_F(text): for s in Stocks: Stock = Stocks[s] if Stock['text'] == text: return (Stock['index'],True,False,text,Stock['value']) for f in Factors: Factor = Factors[f] if Factor['text'] == text: return (Factor['index'],False,True,text,Factor['value'])...
This function updates a dynamic slider based on user clicks and selection (stocks/sensitivities). It extracts data from click events, determines if the interaction relates to stock or sensitivity values, and returns an updated slider, figure, and labels. The logic differs for 'stocks' (generating a specific slider) vs ...
def update_dynamic_slider(clickData,radio,dynamic_slider,prior_label,previous_radio,S_values,F_values): if clickData is not None: # always do this, even if clickData is remnant of previous interaction pointIndex = clickData["points"][0]["pointIndex"] # needed later text = clickData["points"][0]['te...
def get_border_ids(): borders = get_borders() ids = [] for y in range(borders[1]): closest = distance_to_closest(0, y)[0] if len(closest) == 1: ids = ids + closest for y in range(borders[1]): closest = distance_to_closest(borders[0], y)[0] if len(closest) ==...
The main task of the code is to process a list of IDs by filtering out border IDs, calculate a map of remaining IDs, sort the map in descending order based on values, print the map, and return the highest value from the sorted map.
def part1(ids): ids_left = [x for x in ids if x not in get_border_ids()] final_map = calculate_map(ids_left) final_map = sorted(final_map.items(), key=lambda item: item[1]) final_map.reverse() print_map() return final_map[0][1]
def create_base_entity_class(self): cls = ast.ClassDef( name=self.BASE_ENTITYCLASS_NAME, bases=[], keywords=[], body=[], decorator_list=[] ) for attr in STATE_VIRTUAL_ATTRS: cls.body.append(ast.AnnAssign(target=ast.Name(id=attr), annotation=ast.Name(id="Any"), simple=1)) ...
This code generates Python source code dynamically using AST, creating imports, base classes, entities, and services. It sorts domains, injects type annotations (Any) for attributes, and structures classes with proper ordering and empty class handling. The output is a parsed AST converted to source code string.
def generate(self): body = [] body.append( ast.ImportFrom( module="typing", names=[ ast.alias(name="Any", asname=None), ast.alias(name="Literal", asname=None), ], ) ) body.appe...
def atom_num_to_xyz(alist, df): anarray = np.zeros((len(alist), 3)) for i, atomnum in enumerate(alist): anarray[i] = np.array(df.iloc[atomnum][['x', 'y', 'z']], dtype=np.float64) return anarray def find_center(match_array): C, r2 = miniball.get_bounding_ball(match_array) return C, (r2) ** (0...
The function calculates the percentage of random points within a critical radius of any atom in 'remainlist' by generating 'n' random samples around the center of 'matchlist', checking if each sample lies within the van der Waals radius of any atom in 'remainlist', and returning the proportion of such points.
def get_crit_perct(remainlist, matchlist, df, crit_rad, n): remain_xyz = atom_num_to_xyz(remainlist, df) match_xyz = atom_num_to_xyz(matchlist, df) center, _ = find_center(match_xyz) rads = [vdw_r(df.iloc[num]['symbol']) for num in remainlist] samples = get_randm_points(center, crit_rad, n) ct ...
def mol_conf(target_smi, xyz_path='', confmollst=''): if confmollst: target_mol = Chem.MolFromSmiles(target_smi) all_atom_list = Chem.MolToMolBlock(target_mol).split('\n')[4:] # remove heading atom_list = [] for item in all_atom_list: temp = item.split() if...
This function calculates the average critical percentage (cv) of molecular conformations matching a reaction template. It processes a mapped reaction, extracts a SMARTS template, and evaluates conformations from either generated data (if xyz_path is empty) or provided files. The result is the mean cv across all conform...
def sh_value(mapped_rxn, crit_rad, xyz_path='', confmollst='', n=None): reaction = { 'reactants': mapped_rxn.split('>>')[0], 'products': mapped_rxn.split('>>')[1], '_id': 1 } template = te.extract_from_reaction(reaction, keep_atom_mapping=True, r_radius=1, p_radius=0)['reaction_smar...
def mol_conf(target_smi, xyz_path='', confmollst=''): if confmollst: target_mol = Chem.MolFromSmiles(target_smi) all_atom_list = Chem.MolToMolBlock(target_mol).split('\n')[4:] # remove heading atom_list = [] for item in all_atom_list: temp = item.split() if...
The function calculates the 'sh_value' (ccv) for molecular conformations by analyzing substructure matches. It uses either generated (via mol_conf) or provided (xyz_path) coordinates to compute critical percentage values (get_crit_perct) for each match, averaging results across conformations. The output is an array of ...
def sh_value_sample(smiles, sub_smr, crit_rad, xyz_path='', confmollst='', n=None): if not xyz_path: dfdic, idx2am_map = mol_conf(target_smi=smiles, confmollst=confmollst) matchlists, remainlists = mol_match(smiles, sub_smr, idx2am_map, consider_am=False) ccv = np.zeros(len(matchlists)) ...
def mol_conf(target_smi, xyz_path='', confmollst=''): if confmollst: target_mol = Chem.MolFromSmiles(target_smi) all_atom_list = Chem.MolToMolBlock(target_mol).split('\n')[4:] # remove heading atom_list = [] for item in all_atom_list: temp = item.split() if...
This function calculates the sum of critical percentage values for reactant substructures in a chemical reaction. It processes mapped reaction SMARTS, matches substructures to reactants using molecular conformations (from XYZ paths or generated), and computes aggregated scores based on critical radius parameters. The r...
def sh_value_reactants(mapped_rxn, crit_rad, xyz_path='', confmollst='', n=None): reaction = { 'reactants': mapped_rxn.split('>>')[0], 'products': mapped_rxn.split('>>')[1], '_id': 1 } template = te.extract_from_reaction(reaction, keep_atom_mapping=True, r_radius=1, p_radius=0)['reac...
def sh_value(mapped_rxn, crit_rad, xyz_path='', confmollst='', n=None): reaction = { 'reactants': mapped_rxn.split('>>')[0], 'products': mapped_rxn.split('>>')[1], '_id': 1 } template = te.extract_from_reaction(reaction, keep_atom_mapping=True, r_radius=1, p_radius=0)['reaction_smar...
The function `master_sh` determines the calculation method from the input dictionary's 'method' key and executes the corresponding `sh_value` variant (e.g., `sh`, `shs`, `shr`, `shrs`). It extracts parameters like mapped reactions, SMILES, substructures, and configuration data, then routes them to the appropriate helpe...
def master_sh(adict): mapped_rxn=adict['mapped_rxn'] smiles=adict['smiles'] if 'smiles' in adict else '' sub_smr=adict['sub_smr'] if 'sub_smr' in adict else None sub_smrs=adict['sub_smrs'] if 'sub_smrs' in adict else [] crit_rad=adict['crit_rad'] xyz_path=adict['xyz_path'] confmollst=adict['...
def _get_job(self, name): return self._modify_url(self.jenkins.get_job(name)) def _modify_url(self, object_to_modify): if (object_to_modify.url.split('/')[2] == 'jenkins.rd2.thingworx.io'): object_to_modify.url = object_to_modify.url.replace( 'jenkins.rd2.thingworx.io', 'bitb...
The code's main task is to stop and remove builds associated with a specified job if they are running or pending. It retrieves the job and its builds, checks for existence, modifies URLs, and stops eligible builds while handling logging and exceptions. It returns whether any build was successfully stopped and removed.
def stop_and_remove(self, job_name): job = self._get_job(job_name) if not job: logging.info(f"Job is not found by name: {job_name}") return False builds = job.iter_builds() if not builds: logging.info("No builds for job") return False ...
def get_loader(file, batch_size = 64, shuffle = True): data_set = MySet(file) data_iter = DataLoader(dataset = data_set, batch_size = batch_size,num_workers = 4, shuffle = shuffle, pin_memory = True, collate_fn = collate_fn) return data_iter def to_var(var, device): if torch.is_tensor(var): var...
The main task of the code is to train a time-series imputation model (Brits_i) on traffic data using Adam optimization for a specified number of epochs, then generate and return prediction results. It initializes the model architecture, loads data, executes training via batch processing, and outputs the final imputed/p...
def imputation(self, epoch=200): self.model = Brits_i(108, 1, 0, self.length, self.device).to(self.device) self.optimizer = optim.Adam(self.model.parameters(), lr=0.01) self.data_iter = get_loader('./module/data/traffic.json', batch_size=64) for i in tqdm(range(epoch)): self....
def get_nucleosomes(rec): return get_start_length_tags(rec, start_tag="ns", length_tag="nl") def write_bed12(rec, starts, output, lengths=None, aligned_pairs=None): if starts is None: return strand = "-" if rec.is_reverse else "+" passes = round(rec.get_tag("ec")) rgb = "0,0,0" if align...
This function processes BAM alignment records to extract genomic features like nucleosomes, accessible regions, and modification sites (m6A, CpG). It filters unmapped reads if specified, retrieves aligned pairs, and writes results to BED12 files using parameters from `args`. Different modules handle feature detection a...
def extract(bam, args): for rec in tqdm.tqdm(bam.fetch(until_eof=True)): aligned_pairs = None if args.reference and rec.is_unmapped: continue if args.reference: aligned_pairs = np.array( rec.get_aligned_pairs(matches_only=True), dtype=D_TYPE ...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
This code tests the 'detect_rows' function by placing a horizontal sequence of 3 white pieces on a board and verifying if the function correctly identifies 1 such row with 0 other counts, ensuring accurate detection logic for game-winning conditions.
def test_detect_rows(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) if detect_rows(board, col,length) == (1,0): print("TEST CASE for detect_rows PASSED") else: print("TES...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
The code tests a board game's functionality by placing pieces on an 8x8 board, printing the board state, and analyzing open/semi-open rows for black and white stones. It verifies if sequences of stones are correctly detected and counted according to expected outputs, ensuring the game's logic for evaluating moves and g...
def some_tests(): board = make_empty_board(8) board[0][5] = "w" board[0][6] = "b" y = 5; x = 2; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_y, d_x, length, "w") print_board(board) analysis(board) # Expected output: # *0|1|2|3|4|5|6|7* # 0 | | | ...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def print_board(board): s = "*" for i in range(len(board[0])-1): s += str(i%10) + "|" s += str((len(board[0])-1)%10) s += "*\n" for i in range(len(board)): s += ...
The code simulates a Gomoku game where the computer and player alternate turns. The computer uses a search algorithm to select optimal moves, placing "b" (black) stones, while the player inputs "w" (white) coordinates. The game checks for wins/draws after each move and returns the result. The main task is to implement ...
def play_gomoku(board_size): board = make_empty_board(board_size) board_height = len(board) board_width = len(board[0]) while True: print_board(board) if is_empty(board): move_y = board_height // 2 move_x = board_width // 2 else: move_y, m...
def make_empty_board(sz): board = [] for i in range(sz): board.append([" "]*sz) return board def put_seq_on_board(board, y, x, d_y, d_x, length, col): for i in range(length): board[y][x] = col y += d_y x += d_x def print_board(board): s = "*" for i in...
The code tests the `search_max` function by setting up a board with two sequences of pieces (white and black), then verifying if `search_max` correctly returns the position (4,6) as the maximum score. It prints "PASSED" if the result matches, otherwise "FAILED".
def test_search_max(): board = make_empty_board(8) x = 5; y = 0; d_x = 0; d_y = 1; length = 4; col = 'w' put_seq_on_board(board, y, x, d_y, d_x, length, col) x = 6; y = 0; d_x = 0; d_y = 1; length = 4; col = 'b' put_seq_on_board(board, y, x, d_y, d_x, length, col) print_board(board) if searc...
def test_is_empty(): board = make_empty_board(8) if is_empty(board): print("TEST CASE for is_empty PASSED") else: print("TEST CASE for is_empty FAILED") def test_is_bounded(): board = make_empty_board(8) x = 5; y = 1; d_x = 0; d_y = 1; length = 3 put_seq_on_board(board, y, x, d_...
The code executes a series of unit tests for main functions, including checking emptiness, boundedness, row detection, and maximum value search, ensuring correctness and reliability of implementations.
def easy_testset_for_main_functions(): test_is_empty() test_is_bounded() test_detect_row() test_detect_rows() test_search_max()
def swap_position(s, x, y): lst = list(s) lst[x], lst[y] = lst[y], lst[x] return ''.join(lst) def swap_letter(s, x, y): return s.replace(x, '#').replace(y, x).replace('#', y) def rotate_right(s, steps): steps %= len(s) return s[-steps:] + s[:-steps] def rotate_left(s, steps): steps %= len(s)...
The code unscrambles a password by reversing the sequence of scrambling operations. It processes each operation in reverse order, applying inverse transformations (e.g., swapping positions, rotating, reversing ranges, or moving characters) to undo the original scrambling steps and restore the password to its initial st...
def unscramble(password, operations): for operation in reversed(operations): parts = operation.split() if parts[0] == 'swap' and parts[1] == 'position': x, y = int(parts[2]), int(parts[5]) password = swap_position(password, x, y) elif parts[0] == 'swap' and parts[1] =...
def tilt_north(rows): rows = transpose(rows) rows = tilt_rows(rows) rows = transpose(rows) return rows def tilt_west(rows): return tilt_rows(rows) def tilt_south(rows): rows = transpose(rows) rows = tilt_rows(rows, reverse=True) rows = transpose(rows) return rows def tilt_east(rows):...
This function calculates the load on a grid after a specified number of tilt cycles, detecting repeating patterns to optimize computation. It hashes grid states to identify cycles, then uses modular arithmetic to determine the effective cycle index, returning the corresponding load value. If no cycle is detected, it re...
def tilt_calculate_cycle(rows, cycles=1): seen = {} loads = {} prev = None next = None for i in range(cycles): rows = tilt_north(rows) rows = tilt_west(rows) rows = tilt_south(rows) rows = tilt_east(rows) h = hash_rows(rows) if h in seen: p...
def tilt_north(rows): rows = transpose(rows) rows = tilt_rows(rows) rows = transpose(rows) return rows def calculate_load(rows): n = len(rows) result = 0 for i, row in enumerate(rows): for char in row: if char == "O": result += n - i return result def ...
The code processes a grid of data from a file, tilts it north to simulate rock movement, calculates the resulting load, and then computes the load after a specified number of cycles (CYCLES) of tilting. The main tasks are reading input, simulating northward tilting, and calculating the load for both a single tilt and m...
def main(): with open("day14_input.txt") as f: rows = [line.strip() for line in f.readlines()] rows = tilt_north(deepcopy(rows)) print(calculate_load(rows)) load = tilt_calculate_cycle(rows, CYCLES) print(load)
def read_file(self): ''' This function will read a file and save it as string so we can add it to the leaer board This function will also try to read a file, if that file is not found then it will append to the error log about the error also if the error log is not there ...
The main task of the code is to draw a game board using turtle graphics, including a status board, play board, and leader board, and to create interactive buttons with GIFs for functionality like checking, deleting, and quitting. The function also retrieves player input, reads leaderboard data, and positions marbles an...
def board(self): ''' In this function we are going to draw the whole board starting with the status board then teleport down to the bottom to draw the play board, then teleport to the left to draw the leader board. Finally the buttons will be made and each button will have a gif ...
def capture_image(file_path): camera = 0 camera = PiCamera() camera.start_preview() camera.capture(FILE_PATH) camera.stop_preview() camera.close() def show_image(file_path): try: Image.open(file_path).show() # Displaying the image except IOError: pass def cv_imread(file_...
The code captures an image, converts it to HSV color space, detects the hue value of the top-left pixel, and identifies if it's orange or green. Based on the detected color, it controls motors via GPIO, updates an LCD display, increments counters, and prints results. If no match, it outputs "no fruit".
def main(): capture_image(FILE_PATH) show_image(FILE_PATH) img = cv_imread(FILE_PATH) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) hue = hsv[0][0][0] # cv2.imshow('HUE Image', hsv) # Displaying the image # cv2.waitKey(0) # cv2.destroyAllWindows() print('the fruit value is', hue) t...
def cmd(self, s, w=False): self.send_cmd(s) if w: s = self.waitokay() else: for i in range(50): s = self.recv_answer() if s != '': break return s def recv_answer(self): s = self.ser.readline() s = s.decode() if self.debug: print...
The function reads RAM data starting at `dumpstart` for `count` bytes, processes each record using `parseRecord`, and either writes the output to a file or prints it. It handles responses from `self.cmd`, looping until an 'OK' confirmation is received or raising an exception on 'ERR'. The loop increments the address an...
def read_ram(self, dumpstart, count, f): l = self.cmd("R%04x%04x" % (dumpstart, count)) while True: if l == '': l = self.recv_answer() if l.startswith('OK'): return l if l.startswith('ERR'): raise Exception(l) #if l == ':00000001FF': # ...
def calcwritelineHex(a, l): ck = len(l) + a + (a >> 8) s = ":" + ("%02x" % len(l)) + ("%04x" % a) + "00" for c in l: s = s + ("%02x" % c) ck = ck + c ck = (-ck) & 0xff s = s + ("%02x" % ck) return s.upper() def send_cmd(self, s): if self.debug: print('>', repr(s)) ...
This code writes data from a file to RAM by reading it in fixed-size blocks, converting each block to a command string with calcwritelineHex, and sending it via send_cmd. It handles EOF, updates the address, and sends a final termination command. Debug mode prints commands.
def write_ram(self, a, f): while True: l = f.read(RECSIZE) if len(l) == 0: break s = calcwritelineHex(a, l) if self.debug != True: print(s, "\n", end='') sys.stdout.flush() self.send_cmd(s) if len(l) != RECSIZE: break ...
def cmd(self, s, w=False): self.send_cmd(s) if w: s = self.waitokay() else: for i in range(50): s = self.recv_answer() if s != '': break return s def waitokay(self): bad = 0 while True: s = self.recv_answer() if s == "OK": ...
This function verifies RAM contents against a file by reading data in chunks, comparing each byte with expected values from a command response. It counts mismatches, prints error markers, and reports total errors. If mismatches occur, it highlights them and displays "MISMATCH!!" messages. The process continues until th...
def verify_ram(self, f, a): badcount = 0 while True: r = f.read(RECSIZE) if len(r) == 0: break okay = 1 l = self.cmd("R%04x%04x" % (a, RECSIZE)) self.waitokay() rom = parseRecord(l) print(l, "RAM", "\r", end='') if self.debug: ...
def _recv_raw(self, timeout): char = self.getc(1, timeout) if char == '': return TIMEOUT if char is not TIMEOUT: char = ord(char) return char def _recv_bin16_header(self, timeout): ''' Recieve a header with 16 bit CRC. ''' header = ...
This function receives and parses a header from a communication protocol using ZPAD and ZDLE control characters. It handles error retries, detects header format (ZBIN, ZHEX, ZBIN32), extracts header data, and returns the parsed header along with calculated file position information if the header type is ZDATA.
def _recv_header(self, timeout, errors=10): header_length = 0 error_count = 0 char = None while header_length == 0: # Frist ZPAD while char != ZPAD: char = self._recv_raw(timeout) if char is TIMEOUT: return TIMEO...
def _recv_16_data(self, timeout): char = 0 data = [] mine = 0 while char < 0x100: char = self._recv(timeout) if char is TIMEOUT: return TIMEOUT, '' elif char < 0x100: mine = self.calc_crc16(chr(char & 0xff), mine) ...
This function receives data frames of specified bit size (16/32), updates file positions, and returns status codes (FRAMEOK/ENDOFFRAME/TIMEOUT) along with data. It handles frame continuation/end scenarios, sends ZACK acknowledgments when required, and processes timeout conditions.
def _recv_data(self, ack_file_pos, timeout): zack_header = [ZACK, 0, 0, 0, 0] pos = ack_file_pos if self._recv_bits == 16: sub_frame_kind, data = self._recv_16_data(timeout) elif self._recv_bits == 32: sub_frame_kind, data = self._recv_32_data(timeout) el...
def _send_pos_header(self, kind, pos, timeout): header = [] header.append(kind) header.append(pos & 0xff) header.append((pos >> 0x08) & 0xff) header.append((pos >> 0x10) & 0xff) header.append((pos >> 0x20) & 0xff) self._send_hex_header(header, timeout) def _recv_h...
This function receives file data from a network stream by first verifying the correct block position, then repeatedly fetching data chunks and writing them to a file handle until the end of the frame. It handles timeouts and ensures data integrity by checking block positions before writing, returning the result status ...
def _recv_file_data(self, pos, fp, timeout): self._send_pos_header(ZRPOS, pos, timeout) kind = 0 dpos = -1 while dpos != pos: while kind != ZDATA: if kind is TIMEOUT: return TIMEOUT, '' else: header = sel...
def _recv_data(self, ack_file_pos, timeout): zack_header = [ZACK, 0, 0, 0, 0] pos = ack_file_pos if self._recv_bits == 16: sub_frame_kind, data = self._recv_16_data(timeout) elif self._recv_bits == 32: sub_frame_kind, data = self._recv_32_data(timeout) el...
The function receives a file over a network, parses its metadata (filename, size, timestamp), writes the content to disk, and updates the file's modification time. It handles data packets, checks for errors, and logs transfer details like speed. If metadata is corrupted, it aborts and returns False.
def _recv_file(self, basedir, timeout, retry): log.info('Abort to receive a file in %s' % (basedir,)) pos = 0 # Read the data subpacket containing the file information kind, data = self._recv_data(pos, timeout) pos += len(data) if kind not in [FRAMEOK, ENDOFFRAME]: ...
def can_move(self, obj, r, c, dr, dc): if (obj, r, c) in self.already_moved: return False new_r = r + dr new_c = c + dc if not self.in_bounds(new_r, new_c): return False #with separate rules, the edge contains the rules and is out of bounds if self.separate_rules and (new_r == 0 or new_r == self.rows-...
This function processes a movement action in a grid-based environment, updates the agent's position if valid, checks for game-ending conditions (victory/defeat), increments the timestep, and returns the new state, reward, and episode status.
def step(self, action): if action == 0: dr, dc = -1, 0 elif action == 1: dr, dc = 1, 0 elif action == 2: dr, dc = 0, -1 elif action == 3: dr, dc = 0, 1 else: print("invalid action") exit() did_move = False for r in range(self.rows): for c in range(self.cols): for obj in self.grid...
def get_percentage_of_swedish_products_per_category(): products_per_category = get_products_grouped_by_category() percentage_of_swedish_products_per_category = [] for product_group in products_per_category: number_of_products = 0 number_of_swedish_products = 0 for product in product_...
The function `export_data_to_files` exports three datasets to JSON files: the percentage of Swedish products per category, the number of products per category, and products with the highest CO₂ emissions. It retrieves these data using helper functions and writes them into structured JSON format with proper indentation ...
def export_data_to_files(): percentage_of_swedish_products = get_percentage_of_swedish_products_per_category() number_of_products_per_category = get_number_of_products_per_category() highest_co2_emission_products = get_products_with_highest_co2_emission() with open('percentage_of_swedish_products.json',...
def get_episode_path(episode_name, episode_type, data_path): episode_dir = unique_dir(Path(f"{data_path}/{episode_type}/{episode_name}").with_suffix('')) return episode_dir/'tmp'/('audio_og.mp3') def initialise_dirs(episode_path): episode_dir = episode_path.parent episode_dir.mkdir(parents=True, exist_o...
The main task of the code is to download a podcast or YouTube episode from a given URL, save it to a specified directory structure, and return the formatted audio file path. It handles different sources (podcast/youtube), creates necessary directories, performs the download, and processes the audio path for output.
def download_episode(url, episode_name, source, data_path): episode_path = get_episode_path(episode_name, source, data_path) initialise_dirs(episode_path) if source == "podcast": episode_path = wget.download(url, out=str(episode_path)) elif source == "youtube": episode_path = download_y...
def group_sentences(words, min_length=10): group_idxs = [0] for i, w in enumerate(words): w = w['word'].replace('?', '.') if (w.endswith('.') or w.endswith('. ')) and (i - (group_idxs[-1] + 1)) >= min_length: group_idxs.append(i+1) if len(group_idxs) > 1: group_idxs.pop(...
The function groups input words into structured segments (sentences) and applies split functions to categorize them into topics, speakers, and paragraphs. It standardizes input for processing, using predefined or user-specified functions to label and split text into organized parts, returning a labeled transcript split...
def group(words, n_topics=None, split_functions=None): sentences, _ = group_sentences(words) # functions standardised to take sentences as inputs, as this is what is required for topics & paragraphs split_functions = [wrapped_partial(group_topics, n_topics=n_topics), group_speakers, group_paragraphs] if not spl...
def whisper_transcribe(audio_file, language="en", batch_size=batch_size, compute_type=compute_type, device="cuda", save=True): model = load_model("large-v2", device, language=language, compute_type=compute_type) audio = load_audio(audio_file) transcript = model.transcribe(audio, language=language, batch_siz...
The code transcribes an audio file using Whisper, aligns the transcript with the audio, diarizes speakers based on the specified number, assigns speaker labels, processes the final transcript, and optionally saves it as a JSON file.
def transcribe(audio_file, n_speakers, device="cuda", save=True): transcript_whisper = whisper_transcribe(audio_file=audio_file, device=device) transcript_aligned = whisperx_align(transcript_whisper, audio_file, device=device) diarization = diarize(audio_file, n_speakers, device) transcript_diarized = a...
def add_speaker_id_fields(transcript): for topic in transcript['topics']: for speech in topic['groups']: speaker_number = speech['label'] if speaker_number in transcript['speaker_ids'].keys(): speech.update(transcript['speaker_ids'][speaker_number]) return transcr...
The code generates an HTML file by inserting transcript data into a template. It loads an HTML template, processes the transcript (adding speaker IDs if needed), appends generated transcript sections (overview and topics) to the template, saves the modified HTML to a specified path, and returns the updated document obj...
def create_html(transcript, episode_file, asset_path='./assets/html'): with open(asset_path+'/template.html', 'r') as f: doc = BeautifulSoup(f, 'html.parser') if 'speaker_ids' in transcript: transcript = add_speaker_id_fields(transcript) doc_transcript_div = doc.find_all('div', {'class': 'transcript-wrap...
def load_llm_pipeline(model="meta-llama/Llama-2-13b-chat-hf", cache_dir=None, **pipeline_args): repo_branch = "main" tokenizer = AutoTokenizer.from_pretrained(model, revision=repo_branch, cache_dir=cache_dir) model = AutoModelForCausalLM.from_pretrained(model, revision=repo_branch, cache_dir=cache_di...
The main task of the code is to generate a summary of a transcript, extract key topics, and optionally identify speaker IDs using a language model pipeline. It processes the input transcript to produce structured output containing the summarized transcript, identified topics, and, if enabled, speaker identification.
def summarise(transcript, id_speakers=True): llm = load_llm_pipeline(cache_dir="/home/steph/.cache/huggingface/os_models") summarised_topics = summarise_topics(transcript, llm) summarised_transcript = summarise_transcript(summarised_topics, llm) output = { 'summary': summarised_transcript, ...
def get_user_storage(username:str, db:Session) -> Storage: user = get_user_by_username(username=username, db=db) storage = db.query(Storage).filter(Storage.userid == user.userid).first() if storage is None: raise HTTPException(status_code=404, detail=f'No storage was found for: {username}') retu...
This function deletes a specific shoe item or all shoes from a user's storage based on the `deleteAllFlag`. If `deleteAllFlag` is True, it clears the 'Shoes' list and resets 'Stats'. If False, it removes the shoe with the given `shoe_id` from the 'Shoes' list, updates related stats, and commits changes. It returns the ...
def delete_item_by_shoeid(username: str ,shoe_id: str, deleteAllFlag: bool ,db:Session): storage = get_user_storage(username=username, db=db) if deleteAllFlag: storage.shoe_storage_space['Shoes'] = [] storage.shoe_storage_space['Stats'] = schemas.StorageBase.__dict__['__fields__']['shoe_storage_...
def get_user_storage(username:str, db:Session) -> Storage: user = get_user_by_username(username=username, db=db) storage = db.query(Storage).filter(Storage.userid == user.userid).first() if storage is None: raise HTTPException(status_code=404, detail=f'No storage was found for: {username}') retu...
This function deletes a specific item from a user's flips storage. If `deleteAllFlag` is True, it clears all items and resets stats. Otherwise, it removes the item matching `item_id`, updates related statistics, and commits changes to the database.
def delete_item_by_itemid(username:str ,item_id: str, deleteAllFlag: bool,db:Session): storage = get_user_storage(username=username, db=db) if deleteAllFlag: storage.flips_storage_space['Flips'] = [] storage.flips_storage_space['Stats'] = schemas.StorageBase.__dict__['__fields__']['flips_storage...
def get_user_storage(username:str, db:Session) -> Storage: user = get_user_by_username(username=username, db=db) storage = db.query(Storage).filter(Storage.userid == user.userid).first() if storage is None: raise HTTPException(status_code=404, detail=f'No storage was found for: {username}') retu...
This function deletes an Amazon FBA item associated with a specific ASIN from a user's storage. If `deleteAllFlag` is True, it clears all FBA items and resets stats. If False, it searches for the ASIN in the FBA list, removes the matching item, updates inventory statistics, and commits changes to the database. If the A...
def delete_item_by_asin(username: str ,asin: str, deleteAllFlag: bool ,db:Session): storage = get_user_storage(username=username, db=db) if deleteAllFlag: storage.amazon_storage_space['FBA'] = [] storage.amazon_storage_space['Stats'] = schemas.StorageBase.__dict__['__fields__']['fba_storage_spac...
def get_user_storage(username:str, db:Session) -> Storage: user = get_user_by_username(username=username, db=db) storage = db.query(Storage).filter(Storage.userid == user.userid).first() if storage is None: raise HTTPException(status_code=404, detail=f'No storage was found for: {username}') retu...
This function deletes an NFT item from a user's storage space by NFT ID. If `deleteAllFlag` is True, it clears all NFTs and resets stats. Otherwise, it removes the specific NFT, updates associated statistics, and commits changes. It returns the modified storage structure or raises a 404 error if the NFT isn't found.
def delete_item_by_nftid(username: str ,nft_id: str, deleteAllFlag: bool ,db:Session): storage = get_user_storage(username=username, db=db) if deleteAllFlag: storage.nft_storage_space['NFT'] = [] storage.nft_storage_space['Stats'] = schemas.StorageBase.__dict__['__fields__']['nft_storage_space']...
def print_board(): """ Prints the current state of the game board. """ print("-------------") for row in range(3): print("|", end=" ") for col in range(3): if board[row][col] == X: print("X", end=" | ") elif board[row][col] == O: ...
The code defines a function `play_game()` that runs a Tic Tac Toe game loop. It alternates between human and computer turns, updates the board with 'O' (human) and 'X' (computer), checks for a winner or draw after each move, and prints results. The loop continues until the game ends with a winner or a draw.
def play_game(): """ Runs the main game loop. """ print("Welcome to Tic Tac Toe!") print_board() while True: # Get the user's move row, col = get_user_move() board[row][col] = O print_board() # Check if the game is over winner = get_winner(board)...
def print_board(): """ Prints the current state of the game board. """ print("-------------") for row in range(3): print("|", end=" ") for col in range(3): if board[row][col] == X: print("X", end=" | ") elif board[row][col] == O: ...
The code defines a Tic Tac Toe game where a human player (O) and computer (X) alternate turns. It displays the board, takes user input, updates the board, checks for a winner after each move, and declares the result (win/loss/draw) once the game ends.
def play_game(): """ Runs a game of Tic Tac Toe. """ print("Welcome to Tic Tac Toe!") print_board() while True: # Human player's turn row, col = get_user_move() board[row][col] = O print_board() winner = get_winner() if winner is not None: ...
def reduce (x): "returns the reduced equilent form of any valid surreal representation" y = nil while not eq(y,x): y = (y[0],y) if le(x,y) else (y,y[1]) return y def add (x,y): """add two surreal numbers""" if x == nil : return y if y == nil : return x if x == nil : return y ...
This method defines custom addition behavior for instances of the class. It combines the 'form' of the current instance with the 'form' or value of another object 'o', using 'reduce' and 'add' to sum them. It then returns a new instance of the same class initialized with this summed result, enabling seamless addition o...
def __add__ (self,o): return type(self)(reduce(add( self.form(), o.form() if type(o) is type(self) else o )))
def lt (x,y): "less than comparison of two surreals" return not le(y,x) def absolute (x): "return the absolute value of a surreal as a surreal" return negate(x) if le(x,nil) else x def sub (x,y): "subtract two surreals in the order given" return add(x,negate(y))
The main task of the code is to determine if the absolute difference between two values `a` and `b` is less than a third value `c`, returning `True` if this condition holds. It calculates the absolute difference using `absolute(sub(a, b))` and compares it to `c` using a less-than check, though the code contains syntax ...
def within (a,b,c): "return True if a and b are less than c apart" return lt(absolute(sub(a,b)),c)
def negate(x): "return the negation of the given sureal representation" return (negate(x[1]), negate(x[0])) if x else x def sub (x,y): "subtract two surreals in the order given" return add(x,negate(y)) def add (x,y): """add two surreal numbers""" if x == nil : return y if y == nil : return ...
This function multiplies two surreal numbers by recursively handling special cases (nil, one, neg) and combining left/right sets using addition/subtraction. It constructs the product's left/right components through recursive calls, then returns the reduced surreal number formed by these sets.
def mult (x,y): """multiply two surreal numbers""" if x == nil : return nil if y == nil : return nil if x == one : return y if y == one : return x if x == neg : return negate(y) if y == neg : return negate(x) xl,xr,yl,yr = (),(),(),() if x and x[0]: xl = x[0] if x and x[1]: xr ...
def eq (x,y): "compare two surreal numbers and return True if they are equivelent forms" return le(x,y) and le(y,x) def within (a,b,c): "return True if a and b are less than c apart" return lt(absolute(sub(a,b)),c) def le (x,y,n=0): "less or equal comparison of two surreals" return n > max_recu...
The code converts a surreal number representation into a numeric float by iteratively approximating its value. It adjusts a form structure and scales increments/decrements based on comparisons between the input surreal number `s` and the evolving form, refining the approximation until convergence. The result is a float...
def distill (s): "return the numeric value of this surreal representation as a float" form = nil scale = 1 lone = None num = Fraction(0/1) while not eq(s,form): if not lone and within(s,form,one): lone = True if le(form,s): form = (form,form[1]) ...
def reduce (x): "returns the reduced equilent form of any valid surreal representation" y = nil while not eq(y,x): y = (y[0],y) if le(x,y) else (y,y[1]) return y def mult (x,y): """multiply two surreal numbers""" if x == nil : return nil if y == nil : return nil if x == one : r...
This code defines the multiplication operator (`__mul__`) for a class, combining the `form()` of the instance and another object `o` using a `mult` function. It then reduces the result into a new instance of the class, ensuring compatibility whether `o` is of the same type or not. The main task is to enable multiplicat...
def __mul__ (self,o): return type(self)(reduce(mult( self.form(), o.form() if type(o) is type(self) else o )))
def parse_custom_num_formats(self): """Read in custom numeric formatting rules from the shared style table""" custom_formats = {} num_fmts = self.root.findall('{%s}numFmts/{%s}numFmt' % (SHEET_MAIN_NS, SHEET_MAIN_NS)) for node in num_fmts: idx = int(node.get('numFmtId')) ...
The main task of the code is to parse and organize spreadsheet style elements, including custom number formats, color indices, fonts, fills, borders, DXFs, and cell styles. It structures these parsed components into indexed lists for efficient access and applies them to the style properties, preparing the data for use ...
def parse(self): self.parse_custom_num_formats() self.parse_color_index() self.style_prop['color_index'] = self.color_index self.font_list = IndexedList(self.parse_fonts()) self.fill_list = IndexedList(self.parse_fills()) self.border_list = IndexedList(self.parse_borders(...
def _init_centroids(self, X): """Initialize the centroids as k random samples from X""" return [X[random.randint(0, self.m - 1)] for _ in range(self.k)] def _create_clusters(self, X): """Assign the samples to the closest centroids to create clusters""" clusters = [[] for _ in range(self....
The code trains a K-Means algorithm by iteratively assigning data points to centroids, updating centroids based on cluster means, and checking for convergence. It initializes centroids, assigns data points to clusters, recalculates centroids, and stops early if centroids stabilize, returning final cluster assignments.
def fit(self, X): """Train the K-Means algorithm on the data X""" self.m, self.d = X.shape self.centroids = self._init_centroids(X) self.assignments = [-1 for _ in range(self.m)] for i in range(self.max_iter): self.clusters = self._create_clusters(X) old_...
def revokeUserAccessFromAllTables(module, name, host, port, certs_dir): databases = listDatabases(module, host, port, certs_dir) for database in databases: revoke_query = """REVOKE ALL ON TABLE {}.* FROM {};""".format(database, name) command = prepareCommandFormat(host, port, certs_dir).format(r...
The code's main task is to delete a database user by first revoking their access to all tables and databases, then constructing and executing a SQL command to drop the user if they exist, using provided connection details and certificate directory for secure execution.
def deleteUser(module, name, host, port, certs_dir): revokeUserAccessFromAllTables(module, name, host, port, certs_dir) revokeUserAccessFromAllDatabases(module, name, host, port, certs_dir) deletion_query = """DROP USER IF EXISTS {};""".format(name) command = prepareCommandFormat(host, port, certs_dir)....
def populate_all_stats(module, certs_dir, all_stats) : if (len(all_stats) == 6) : all_stats.pop(0) nodes_status = get_nodes_status(module, certs_dir, "csv"); all_stats.append(convert_csv_to_json(nodes_status)) else : all_stats = [] start_time = time.time() while (...
The code defines an Ansible module to monitor cluster health by periodically checking certificate statuses from a specified directory. It runs in a loop until all nodes are healthy or a timeout occurs, reporting success or timeout. The module supports check mode for simulation, exiting early if enabled. Results are ret...
def main(): module = AnsibleModule( argument_spec = dict( host = dict(required = False, default = 'localhost', type = 'str'), node_id = dict(required = False, type = 'int'), certs_dir = dict(required = True, default = None, type = 'str'), timeout = dict(requir...
def getSecrets(conn): return [{'id':s['name'], 'link':s['secret_ref']} for s in conn.key_manager.secrets()] def destroySecret(conn, secret_key, secrets = None): secrets = secrets or getSecrets(conn) found_secrets = filter(lambda s: s['id'] == secret_key, secrets) if len(found_secrets) == 0: ret...
This function modifies an existing secret by first verifying its existence, then deleting the old secret and creating a new one with the updated value. It uses the provided connection to interact with a secrets store, ensuring the specified secret key exists before proceeding. If the secret is not found, it raises an e...
def modifySecret(conn, secret_key, secret_value, secrets = None): secrets = secrets or getSecrets(conn) found_secrets = filter(lambda s: s['id'] == secret_key, secrets) if len(found_secrets) == 0: raise Exception('A secret with key "{}" does not exist.'.format(secret_key)) destroySecret(conn, ...
def deleteUser(module, name, host, port, certs_dir): revokeUserAccessFromAllTables(module, name, host, port, certs_dir) revokeUserAccessFromAllDatabases(module, name, host, port, certs_dir) deletion_query = """DROP USER IF EXISTS {};""".format(name) command = prepareCommandFormat(host, port, certs_dir)....
This Ansible module manages CockroachDB user accounts by creating or deleting users based on the 'state' parameter. It validates inputs like username, password, and permissions, then interacts with CockroachDB via helper functions. The module supports check mode for dry runs and returns status messages indicating user ...
def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, type='str'), password=dict(required=False, type='str', no_log=True, default=None), admin=dict(required=False, type='bool', default=False), grants=dict(required=False, type='list',...
def getSecrets(conn): return [{'id':s['name'], 'link':s['secret_ref']} for s in conn.key_manager.secrets()] def destroySecret(conn, secret_key, secrets = None): secrets = secrets or getSecrets(conn) found_secrets = filter(lambda s: s['id'] == secret_key, secrets) if len(found_secrets) == 0: ret...
(The main task of the code is to manage secrets in a cloud environment using Ansible, allowing users to create, modify, or delete secrets based on parameters like 'state' and 'overwrite_mode'. It interacts with OpenStack by default, checks for existing secrets, and handles overwrite scenarios by forcing changes, failin...
def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, type='str'), state=dict(choices=['present', 'absent'], required=False, default='present', type='str'), cloud=dict(required=False, default='openstack', type='str'), value=dict(requ...
def readImage(name): if name.endswith('.pfm') or name.endswith('.PFM'): data = readPFM(name) if len(data.shape)==3: return data[:,:,0:3] else: return data return imageio.imread(name) def add_occluders(self, rgbs, masks, trajs, visibles, valids, print_timings=False...
The function `getitem_helper` loads and processes video data (RGB images, trajectories, masks) for a neural network. It reads image paths, loads trajectory data, applies shuffling, occlusion, and augmentation, filters valid trajectories based on visibility and bounds, and constructs a structured sample with tensors for...
def getitem_helper(self, index, print_timings=False): sample = None gotit = False if print_timings: step_start_time = time.time() cur_rgb_path = self.rgb_paths[index] cur_traj_path = self.traj_paths[index] cur_mask_path = self.mask_paths[index] star...
def run_pips(pips, d, sw): metrics = {} file0 = str(d['file0']) rgbs = d['rgbs'].cuda().float() # B, S, C, H, W segs = d['segs'].cuda().float() # B, S, 1, H, W trajs_g = d['trajs'].cuda().float() # B, S, N, 2 visibles = d['visibles'].cuda().float() # B, S, N # print('file0', file0) if ...
The main task of the code is to evaluate keypoint propagation performance of models (PIPS, RAFT, DINO) on the BADJA dataset. It loads pre-trained models, processes test data in batches, computes metrics like PCK (Percentage of Correct Keypoints), logs results with TensorBoard, and prints evaluation statistics. The code...
def main( exp_name='badja', B=1, S=8, modeltype='pips', init_dir='reference_model', log_dir='logs_test_on_badja', data_dir='/data/badja_data', stride=4, max_iters=7, log_freq=99, # vis is very slow here shuffle=False, ): # the i...
def availablePositions(self): positions = [] for i in range(BRD_RWS): for j in range(BRD_CLS): if self.board[i, j] == 0: positions.append((i, j)) # need to be tuple return positions def updateState(self, position): self.board[position] = s...
This code simulates a two-player game over multiple rounds, alternating turns between players. It updates the game board, checks for a win/draw, and resets the game state when the game ends. Player actions are chosen based on available positions, and rewards are assigned upon termination. The loop tracks progress and r...
def play(self, rounds=100): for i in range(rounds): if i % 1000 == 0: print("Rounds {}".format(i)) while not self.isEnd: # For 1 Player positions = self.availablePositions() p1_action = self.p1.chooseAction(positions, self.b...
def get_description(self, description: str | None) -> str | None: return description def _build_extras(self, extras: list[Element] | None = None): if not extras: return with self.get_current_row(): for element in extras: element.move(self.get_current_row()...
This code initializes a UI component with customizable properties like title, icon, description, and buttons. It sets up rows for elements, manages expandability, drag functionality, and additional buttons (delete, clear, default). The class prepares the UI structure, including tooltips and layout settings, for renderi...
def __init__( self, elements_per_row: list[int] = SINGLE_ROW, title: str | None = None, description: str | None = None, icon: str | None = None, icon_size: str = "32px", draggable: bool = False, expandable: bool = False, add_delete_button: bool = F...
def prep_data(df_actions, df_prices_trade): df=df_prices_trade[['date','close','tic']] df['Date'] = pd.to_datetime(df['date']) df = df.set_index('Date') # set indices on both df to datetime idx = pd.to_datetime(df_actions.index, infer_datetime_format=True) df_actions.index=idx...
This function calculates trade performance metrics by processing aligned action and price data, computing profit/loss for each ticker, and deriving a specified trade metric (e.g., average win/loss ratio). It updates a metric history dictionary and returns the computed value for optimization or analysis.
def calc_trade_perf_metric(df_actions, df_prices_trade, tp_metric, tpm_hist, dbg=False): df_actions_p, df_prices_p, tics = prep_data(df_actions.copy(), df_p...
def prep_data(df_actions, df_prices_trade): df=df_prices_trade[['date','close','tic']] df['Date'] = pd.to_datetime(df['date']) df = df.set_index('Date') # set indices on both df to datetime idx = pd.to_datetime(df_actions.index, infer_datetime_format=True) df_actions.index=idx...
The function `calc_trade_perf_metric` evaluates trade performance using provided action and price data. It prepares, synchronizes, and analyzes portfolio data to compute profit/loss metrics. It calculates trade performance indicators, derives a specified trade metric (e.g., win/loss ratio), updates a historical metric ...
def calc_trade_perf_metric(df_actions, df_prices_trade, tp_metric, tpm_hist, dbg=False): df_actions_p, df_prices_p, tics = prep_data(df_actions.copy(), df_p...
def get_image_files(rootdir): image_file_map = Path("./image-files/geological_mapping_data.json") if image_file_map.is_file(): with open(image_file_map, 'r', encoding='utf-8') as f: image_files=json.load(f) else: rootdir = rootdir image_files = [] for subdir, dirs...
The main task of the code is to perform a k-nearest neighbor (kNN) similarity search on image embeddings. It loads test images and embeddings, retrieves random test samples, and computes cosine similarity to find the closest matches using the specified k value, returning the results as a DataFrame.
def main(): rootdir = args.rootdir TEST_IMAGE_PATH = args.testImagePath ENCODER_MODEL_PATH = args.encoderModelPath EMBEDDING_PATH = args.embeddingPath k = args.kNearest test_images = pd.read_csv("/Users/abhishekvaidyanathan/Desktop/Similarity_search_review/knn-results/cosine-results.csv") t...
def loss_dataset(model, dataset, loss_f): """Compute the loss of `model` on `dataset`""" loss=0 for idx,(features,labels) in enumerate(dataset): features = features.to(device) labels=labels.to(device) predictions= model(features) loss+=loss_f(predictions,labels) ...
The code implements the **FedProx federated learning algorithm**, where multiple clients train local models on their data and the server aggregates them into a global model. It uses a regularization term (`mu`) to handle non-IID data, tracks training/test loss/accuracy across iterations, and returns the final global mo...
def FedProx(model,optimizer, training_sets:list, n_iter:int, testing_sets:list, mu=0, file_name="test", epochs=5, lr=10**-2): """ all the clients are considered in this implementation of FedProx Parameters: - `model`: common structure used by the clients and the server - `training_sets`: l...
def download(self): if self._check_integrity(): print('Files already downloaded and verified') return download_and_extract_archive(self.url, self.root, **self.zipped) def _check_integrity(self) -> bool: return all(check_integrity(self._get_path(filename), md5) for filenam...
This code initializes the LISA dataset by downloading data if specified, verifying integrity, loading images and labels as tensors, and splitting data into training/test sets based on the 'train' flag.
def __init__(self, root, train: bool, download=False, transform=None, target_transform=None): super(LISA, self).__init__(root=root, transform=transform, target_transform=target_transform) if download: self.download() if not self._check_integrity(): raise RuntimeError('D...
def get_action_space(): """End effector position and gripper width relative displacement""" return spaces.Box(np.array([-1]*4), np.array([1]*4)) def get_observation_space(): """Return only position and gripper_width by default""" observation_space = {} observation_space["po...
This code initializes a simulated environment using PyBullet by configuring physics parameters, loading objects, and setting up GUI/direct mode based on input configurations. It establishes action/observation spaces, resets the simulation, and applies gravity, preparing the environment for interaction.
def __init__(self, cfg): """ Input: cfg contains the custom configuration of the environment cfg.tacto cfg.settings show_gui=False, dt=0.005, action_frequency=30, simulation_frequency=240, max_episode_steps=500, ""...
def get_active_nodes(self): active_nodes = [] for k in port_map.keys(): if self.id == k: active_nodes.append(k) else: if is_target_alive(k): active_nodes.append(k) return active_nodes def debug(par, flow="all"): if d...
The main task of the code is to create a chain of data stores from active nodes by collecting their stores, shuffling them, and constructing a `Chain` object with head, tail, and processes. It validates the chain by sending it to all nodes, ensuring acceptance. If any node rejects it, the chain is discarded, and an err...
def create_chain(self): if self.chain != None: print("Chain already created") return nodes = self.get_active_nodes() debug(f"Active nodes: {nodes}", flow="create_chain") stores = [] for node in nodes: nodes_stores = self.get_target_nodes_data_s...
def get_statistics(dataframe, period): ''' calculates basic statistics such sa mean,std,min and max for different blood pressure indicators :param dataframe: dataframe with blood pressure measurements :param period: parameter for choosing if statistics should be calculated for day, night or ...
The function `join_overall_statistics` combines blood pressure dataframes by merging basic statistics for day and night measurements with additional columns for morning surge and drop values, returning a concatenated dataframe containing all these metrics.
def join_overall_statistics(dataframe): ''' joins dataframes with basic statistics for day and night and appends columsn with morning surge and drop values :param dataframe: dataframe with blood pressure measurements for both day and night values :return: concated dataframe ''' df_statistics = g...
def join_overall_statistics(dataframe): ''' joins dataframes with basic statistics for day and night and appends columsn with morning surge and drop values :param dataframe: dataframe with blood pressure measurements for both day and night values :return: concated dataframe ''' df_statistics = g...
The code initializes an object by computing and storing statistical data from a DataFrame. It calculates overall statistics, separates day and night statistics, and generates a load dictionary. These attributes are derived using helper functions, enabling the object to hold aggregated data for analysis or further proce...
def __init__(self,df): self.basic_overall = join_overall_statistics(df) self.basic_day = get_statistics(df,'day') self.basic_night = get_statistics(df,'night') self.bp_load = bp_load_dictionary(df)
def get_tdu_index(self, tdu_select): if tdu_select == "TDU02": return 0 elif tdu_select == "TDU03": return 1 elif tdu_select == "TDU04": return 2 def read_weekly_performance_df(self, start_day, end_day): weekly_performance_df = {} ...
The code initializes a Streamlit dashboard for monitoring operational performance metrics (availability, throughput, tonnes processed) of TDU units. It configures page layout, allows user selection of TDU units and time ranges, captures performance targets, retrieves historical data, displays real-time metrics with dai...
def __init__(self, TDU_LIST): ##page configuration # with st.echo(code_location='below'): self.today = (datetime.date.today()) self.yesterday = (datetime.date.today() - datetime.timedelta(days = 1)) self.start_day = (datetime.date.today() - datetime.timedelta(days = 7...
def compute_e0_loss(self): self.model.train() disp_dict = {} progress_bar = tqdm.tqdm(total=len(self.train_loader), leave=True, desc='pre-training loss stat') with torch.no_grad(): for batch_idx, (inputs,calibs,coord_ranges, targets, info) in enumerate(self.train_load...
The main task of the code is to train a machine learning model using hierarchical task learning, dynamically adjusting loss weights across epochs, managing learning rate scheduling (including warmup), and periodically evaluating the model while saving checkpoints for later use. The training loop handles epoch iteration...
def train(self): start_epoch = self.epoch ei_loss = self.compute_e0_loss() loss_weightor = Hierarchical_Task_Learning(ei_loss) for epoch in range(start_epoch, self.cfg_train['max_epoch']): # train one epoch self.logger.info('------ TRAIN EPOCH %03d ------' %(epoch...
def make_eslash(self,): """ Make the slashed es.""" eslash = [g.mspin(self.grid) for mu in range(4)] for mu in range(4): eslash[mu][:] = 0 for mu in range(4): for a in range(4): eslash[mu] += g.gamma[a].tensor() * self.e[mu][a] return eslas...
The code computes the Riemann curvature tensor and its raised-index version using gauge field strengths, gamma matrices, and metric inverses. It initializes tensors, calculates field strength components, applies metric transformations, and computes tensor components via traces involving gamma matrices, ultimately retur...
def make_riemann(self,): """ Make the Riemann curvature tensor.""" eslash = self.make_eslash() einvslash = self.make_einvslash() Riemann = [[[[g.real(self.grid) for mu in range(4)] for nu in range(4)] for rho in range(4)] for sig in range(4)] Riemann_up = [[[[...
def make_riemann(self,): """ Make the Riemann curvature tensor.""" eslash = self.make_eslash() einvslash = self.make_einvslash() Riemann = [[[[g.real(self.grid) for mu in range(4)] for nu in range(4)] for rho in range(4)] for sig in range(4)] Riemann_up = [[[[...
This code computes the Ricci scalar $R$ in a curved spacetime by constructing and contracting Riemann tensor components, metric tensors, and inverse metrics. It verifies results through multiple methods (Rcheck, Rcheck2, Rcheck3), incorporates gamma matrices and field strengths, scales by the inverse determinant of the...
def check_R(self,): Rcheck = g.real(self.grid) Rcheck[:] = 0 Rcheck2 = g.real(self.grid) Rcheck2[:] = 0 Rcheck3 = g.real(self.grid) Rcheck3[:] = 0 R = g.real(self.grid) R[:] = 0 Riemann, Riemann_up = self.make_riemann() eslash = self.make_e...
def make_eslash(self,): """ Make the slashed es.""" eslash = [g.mspin(self.grid) for mu in range(4)] for mu in range(4): eslash[mu][:] = 0 for mu in range(4): for a in range(4): eslash[mu] += g.gamma[a].tensor() * self.e[mu][a] return eslas...
This function computes the total lattice QCD action by combining terms involving the Wilson loop, topological charge (R), volume (vol), determinant of the fermion matrix (dete), and additional coefficients (lam, kappa, alpha, etc.). It calculates field strengths, traces, and determinant-based contributions to form the ...
def compute_action(self,): """ Compute the gravity action site-wise.""" R = g.real(self.grid) R[:] = 0 Rsq = g.real(self.grid) Rsq[:] = 0 vol = g.real(self.grid) vol[:] = 0 eslash = self.make_eslash() wilson = g.real(self.grid) wilson[:] = ...
def parse_args(): # Initialise argparse ap = argparse.ArgumentParser() # command line parameters ap.add_argument("-f", "--file_input", required = True, help = "The filename or directory you want to work with") args = vars(ap.parse_args()) return args def load_vgg16(): model = V...
The code processes an input file or directory using a pre-trained VGG16 model to extract features. If the input is a file, it computes nearest neighbors for that single image. If the input is a directory, it processes all images, generating nearest neighbor results for each. The script handles both cases, ensuring feat...
def main(): # parse arguments args = parse_args() input_name = args['file_input'] # if path provided is a file: isFile = os.path.isfile(input_name) if isFile == True: model = load_vgg16() joined_paths, feature_list = list_features(model) nn_one_result(joined_path...
def parse_args(): # Initialise argparse ap = argparse.ArgumentParser() # command line parameters ap.add_argument("-f", "--file_input", required = True, help = "The filename or directory we want to work with") args = vars(ap.parse_args()) return args def calc_sim_scores(filename): ...
The main task of the code is to process an input file or directory by calculating similarity scores and generating histograms. If the input is a file, it computes scores and saves a histogram for that file. If the input is a directory, it processes all files within, generating histograms for each. The script checks the...
def main(): # parse arguments args = parse_args() input_name = args['file_input'] # if path provided is a file: isFile = os.path.isfile(input_name) if isFile == True: scores = calc_sim_scores(input_name) hist_result(input_name, scores) print('Input is a ...
def ensemble_text_guided_mask_proposal(self, image, object_phrase_list, filtered_phrase_list, object_max_area, object_min_area, bbox_score_thr, text_score_thr): size = image.shape[:2] H, W = size[0], size[1] ...
The main task of the code is to perform anomaly detection in images by combining object detection, defect region proposal, saliency analysis, and confidence scoring. It generates object masks, refines defect regions using prompts, computes similarity maps, and synthesizes an anomaly map through confidence prompting. Th...
def forward(self, image: np.ndarray): ####### Object TGMP for object detection object_masks, object_logits, object_area = self.ensemble_text_guided_mask_proposal( image, [self.object_prompt], ['PlaceHolder'], self.object_max_area, self.object_m...
def is_training_discriminator(self): return self.opts.w_discriminator_lambda > 0 def validate_discriminator(self, x, txt_embed, data_type="real"): with torch.no_grad(): loss_dict = {} real_w, fake_w = self.sample_real_and_fake_latents(x, txt_embed) real_pred = self.discriminator(real_w) fake_pred = self...
The code validates a model by evaluating real and generated images, computing losses, and logging metrics. It processes text embeddings, uses a discriminator for validation, performs forward passes on real and cycle-generated images, calculates real and cycle losses, combines them, and aggregates results for logging. I...
def validate(self): self.net.eval() agg_loss_dict = [] for batch_idx, batch in enumerate(self.test_dataloader): x, y, txt = batch text_original = clip.tokenize(txt).to(self.device) with torch.no_grad(): txt_embed_original = self.clip_model.encode_text(text_original) txt_embed_original = txt_embed...
def check_for_progressive_training_update(self, is_resume_from_ckpt=False): for i in range(len(self.opts.progressive_steps)): if is_resume_from_ckpt and self.global_step >= self.opts.progressive_steps[i]: # Case checkpoint self.net.encoder.set_progressive_stage(ProgressiveStage(i)) if self.global_step == s...
The code trains a neural network with a discriminator, performing forward passes on real and generated images while computing losses. It incorporates text embeddings via CLIP, handles cyclic consistency, and logs metrics. The loop runs until max steps, with validation, checkpointing, and progressive training updates.
def train(self): self.net.train() if self.opts.progressive_steps: self.check_for_progressive_training_update() while self.global_step < self.opts.max_steps: for batch_idx, batch in enumerate(self.train_dataloader): x, y, txt = batch x, y = x.to(self.device).float(), y.to(self.device).float() tex...
def set_options( self ): self.inputFile = cmds.textField( self.FILE_INPUT_TEXT, query=True, text=True ).encode( 'utf8' ) self.outputFile = cmds.textField( self.FILE_OUTPUT_TEXT, query=True, text=True ).encode( 'utf8' ) self.outputChannel = cmds.textField( self.OUTPUT_CHANNEL_TEXT, query=True, te...
The function generates sticky channels from input files to output files using specified parameters, after validating files and output channels. It executes a command to create channels, deletes a UI window, and handles errors by displaying a critical dialog with the error message if exceptions occur during execution.
def generate_birth_channels( self, arg=None ): self.set_options() if self.check_files() != 0: return if self.check_output_channel() != 0: return try: cmds.GenerateStickyChannels( self.inputFile, self.outputFile, self.inputChannel, sel...
def check_final(node): vehicle = node.stage.vehicles[0] vehicle = vehicle.split(" ") size = int(vehicle[1]) # auto ma velkost 2 a tych colums je vzdy ako keby o 1 viac (realne pocitam od 0) cize mi staci dat columns-size fin = str(map_columns-size) if vehicle[3] == fin: return True r...
This code implements a search algorithm that processes nodes from a queue, generates child nodes, and tracks processed nodes. It returns the end node when child generation fails or the first valid node if found, while logging performance metrics like node count and processing time.
def search(que_l, search_type): counter = 0 processed_nodes = {} global time_no_idea depth = 0 if check_final(que_l[0]): return que_l[0] add_to_created(que_l[0], processed_nodes) while que_l: node = que_l.pop(0) if search_type == 1: if depth < node.depth: ...
def PrintException(): exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line....
(The main task of the code is to execute a SQL request with retry logic. It handles specific PostgreSQL errors by disconnecting/reconnecting to the database or re-raising exceptions, then retries after a 5-second delay if execution fails. The loop continues until the request successfully executes, ensuring resilience a...
def executeRequest_(self, request, parameters=None, connectToDatabase=True): while True: try: self.cursor_.execute(request, parameters) return except psycopg2.Warning as err: PrintException() except psycopg2.InterfaceError as er...
def disconnect(self): if self.connection_ is None: return try: self.cursor_.close() del self.cursor_ self.connection_.close() del self.connection_ except: PrintException() def connect_(self, connectToDatabase=True): ...
The main task of the code is to create a new database using the specified name and grant full access permissions to a user and the public schema. It disconnects, reconnects, executes the database creation, then reconnects again to apply schema-level grants before disconnecting.
def createDatabase(self): request = "CREATE DATABASE " + self.dbname_ + ";" self.disconnect() self.connect_(connectToDatabase=False) self.executeRequest_(request, parameters=None, connectToDatabase=False) self.disconnect() grantRequest = "GRANT ALL ON SCHEMA public TO " ...
def disconnect(self): if self.connection_ is None: return try: self.cursor_.close() del self.cursor_ self.connection_.close() del self.connection_ except: PrintException() def connect_(self, connectToDatabase=True): ...
The main task of the code is to drop a specified database by executing the SQL command "DROP DATABASE [dbname];". It disconnects from the current database, reconnects without connecting to a database, executes the drop command, and disconnects again to ensure proper execution and avoid connection conflicts.
def dropDatabase(self): request = "DROP DATABASE " + self.dbname_ + ";" self.disconnect() self.connect_(connectToDatabase=False) self.executeRequest_(request, parameters=None, connectToDatabase=False) self.disconnect()
def find_food(self, ants): ant_dist = [] for food_loc in ants.food(): for ant_loc in ants.my_ants(): dist = ants.distance(ant_loc, food_loc) ant_dist.append((dist, ant_loc, food_loc)) ant_dist.sort() for dist, ant_loc, food_loc in ant_dist: if food_loc not in self.targets and...
The main task of the code is to manage a game turn by initializing orders, processing food and hill locations, exploring new territory, unblocking hills, and executing random movement strategies for ants. It coordinates multiple strategies to direct ant behavior toward resource gathering, territorial expansion, and hil...
def do_turn(self, ants): self.orders = {} self.targets = {} for hill_loc in ants.my_hills(): self.orders[hill_loc] = None logging.error("Start turn") self.find_food(ants) self.find_hills(ants) self.find_new_territory(ants) self.unblock_hills(ants) self.wander_like_a_drunk(ants...