dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_ticker_dataFrame(tick, period='1y', interval='1d'): data_ohlc = yf.Ticker(tick) # Get the ticker data from yfinance dataFrame = data_ohlc.history(period=period, interval=interval) # dataFrame = dataFrame.iloc[:-49 , :] to analyze previous day # Check whether the data can be retrieved if (...
The function evaluates a stock's score using momentum burst and high tight flag (HTF) indicators. It retrieves stock data, computes a linear momentum score, and if valid, calculates HTF scores. It returns HTF data, the linear score, and a final HTF day score, with optional plotting.
def stock_score(ticker): is_data_valid, dataFrame = get_ticker_dataFrame(ticker) df_htf = pd.DataFrame() ticker_lin_score = np.NaN htf_final_day_score = np.NaN if is_data_valid: # Check whether the data can be retrieved df_mbs, region_indexes, ticker_lin_score = momentum_burst_score(dataFra...
def f_ml(self, s_new, a_new): """Machine learning prediction. Args: s_new (numpy.ndarray): categorical sensitive training attributes of shape (*, 1) or one-hot encoded attributes of shape (*, c). a_new (numpy.ndarray): non-sensitive training attributes, shape ...
This function acts as a wrapper to dispatch input parameters to specific methods based on the 'method' argument. It converts the method to uppercase, validates inputs (e.g., ensuring s_new is provided for certain methods), and calls corresponding internal functions like f_ml, f_ftu, or f_1/f_2 with appropriate argument...
def f_wrapper(self, method, a_new, s_new=None, **kwargs): method = method.upper() if method == 'ML': assert s_new is not None return self.f_ml(s_new, a_new) if method == 'FTU': return self.f_ftu(a_new) if method == 'FL': return self.f_fl(s_...
def get_num_users(): return len(login_and_get_users().json()['users']) def create_user(user_data, check_status=True, json=True): if json: response = requests.post(f'{BASE_URL}/users', json=user_data) else: response = requests.post(f'{BASE_URL}/users', data=user_data) if check_status: ...
This test verifies user creation, login/logout functionality, and access control. It checks successful user creation, duplicate email rejection, login failures for invalid users, authentication requirements for user retrieval, and session invalidation after logout. The test ensures only authenticated users (including a...
def test_0001_create_users_login_logout(): assert get_num_users() == 1 # Admin is already here create_user(USER_DATA_1) assert get_num_users() == 2 create_user(USER_DATA_2, json=True) assert get_num_users() == 3 check_failed_to_create_a_user_with_existing_email(USER_DATA_1) assert get_nu...
def read_itp(file): contents = [] with open(file, 'r') as f: for line in f.readlines(): line_content = line.split(';')[0].split() if len(line_content) > 0: contents.append(line_content) return contents def process_itp_contents(itp_contents): # SPLITS CONTENTS INTO SECTIO...
This code provides a command-line interface to interact with atom types and nonbond parameters from an ITP file, allowing users to view, modify, copy, and save Lennard-Jones parameters, bonds, and atom types through various commands like 'a', 'b', 'c', 'lj', and 'w'
def run(itp_file): contents = read_itp(itp_file) atom_types, nonbond_params = process_itp_contents(contents) quit = False while quit == False: cmd = input(' >> ').split() # QUIT if len(cmd) == 1 and cmd[0] == 'q': quit = True # BEADS elif len(cmd) == 1...
def K_val_from_H(H): K_vals = [] for i in range(len(H)): for j in range(len(H[0])): if i!=j: K_vals += [[i, j, H[i][j]]] return K_vals def create_A_val(bs): ''' Create the transcription information input, A_val, for nondelay_wrapper. Args: bs (lis...
The function performs Markovian simulations of an Ising model to generate cellular state samples, using parameters like interaction strengths (k_ons/k_off), energy terms (bs/ds), and simulation settings. It constructs a Hamiltonian, derives interaction values, initializes states, and runs the simulation to output time-...
def create_samples(k_ons, k_off, bs, ds, epsilon, number_of_cells, simulation_time): ''' Use Markovian simulation to return simulated cells according to an Ising model. ''' n = len(bs) N = 2**n H = construct_H(k_ons, k_off, epsilon, periodic=False) K_val = K_val_from_H(H) beta_val =...
def generate_file_idates(self,ddt_start,ddt_end): yvec = range(int(self.get_ddt_yr(ddt_start)),int(self.get_ddt_yr(ddt_end))) dvec = ["31","30","30","31"] mvec = ["03","06","09","12"] qvec = ["0331","0630","0930","1231"] yvec = range(int(self.ddt_start[0:4]),int(self.ddt_end[0:4]...
The main task of the code is to aggregate and merge data from multiple schedules and dates into a unified dataset. It generates file IDs/dates, iterates through schedules and dates, retrieves data, merges them on "IDRSSD", appends a date column, and concatenates all results into `self.all_data` for comprehensive analys...
def create_full_data_set(self): self.all_data = None self.generate_file_idates(self.ddt_start,self.ddt_end) self.generate_file_ddates(self.ddt_start,self.ddt_end) for i in range(0,len(self.the_idates)): df_date = None for j in range(0,len(self.cr_schedules)): ...
def hours_format(num: int) -> str: updated_time = num / 3600 updated_time = handle_truncate(updated_time) return str(updated_time) + " hours" def minutes_format(num: int) -> str: updated_time = num / 60 updated_time = handle_truncate(updated_time) return str(updated_time) + " minutes" def second...
The main task of the code is to convert a given number of seconds into a formatted time string by determining whether it represents hours, minutes, or seconds based on its magnitude, and returning the corresponding formatted value.
def full_format(num: int) -> str: updated_time = 0 if num >= 3600: updated_time = hours_format(num) elif num >= 60: updated_time = minutes_format(num) else: updated_time = seconds_format(num) return updated_time
def full_format(num: int) -> str: updated_time = 0 if num >= 3600: updated_time = hours_format(num) elif num >= 60: updated_time = minutes_format(num) else: updated_time = seconds_format(num) return updated_time def seconds_format(num: int) -> str: return str(int(num)) + ...
The main task of the code is to convert a given number of seconds into a formatted time string based on the specified format in `args.time_format`, which can be 'f' (full format), 's' (seconds), 'm' (minutes), or 'h' (hours). The function selects the appropriate formatting method and returns the formatted time string.
def scale_time(time_seconds: int) -> str: updated_time = 0 if args.time_format == 'f': updated_time = full_format(time_seconds) elif args.time_format == 's': updated_time = seconds_format(time_seconds) elif args.time_format == 'm': updated_time = minutes_format(time_seconds) ...
def get_time_formatted(time_lst: list) -> int: dt_obj = datetime.strptime(time_lst, args.date_format) return dt_obj.timestamp() def scale_time(time_seconds: int) -> str: updated_time = 0 if args.time_format == 'f': updated_time = full_format(time_seconds) elif args.time_format == 's': ...
The function `full_print` calculates and summarizes the time spent on individual processes compared to the total process duration. It tracks start and end times of processes, computes their durations, sums these to get a total time, and compares it with the full process time. It outputs a formatted string listing each ...
def full_print(process_lst: str, time_lst: str, full_process_time: str) -> int: start_table = {} final_table = {} out_string = "" total_time = 0 for i in range(len(process_lst)): individual_process = process_lst[i].split() if cue_end_startword in individual_process: # g...
def normalize_interface_names(non_norm_int): tmp = split_interface(non_norm_int) interface_type = tmp[0].lower() port = tmp[1] interfaces = [ [["ethernet", "eth"], "Eth"], [["fastethernet", " fastethernet", "fa", "interface fastethernet"], "Fa"], [["gi", "gigabitethernet", "gigab...
The code connects to network devices using Netmiko, retrieves interface status, MAC address tables, ARP tables, and neighbor information via CDP/LDTP. It parses outputs with TextFSM templates, processes device-specific configurations, and writes structured interface/mac/neighbor data to output files for documentation o...
def update_documentation(device_type, ip, username, password, secret, global_delay, oui_dict=None): print("Attempting to connect...") if device_type != 'cisco_s300': if username != '' and secret == '': conn = netmiko.ConnectHandler(device_type=device_type, ip=ip, username=username, password=...
def get_oui_dict(pkgdir): import os f_in = open(os.path.join(pkgdir, "templates/wireshark_oui.txt"), "r") oui = filter(None, (line.partition("#")[0].rstrip() for line in f_in)) oui_dict = dict() for line in oui: part = line.partition("\t") if "IEEE Registration Authority" not in par...
The main task of the code is to automate Cisco switch documentation by fetching device information (config, interfaces, ARP), parsing it into structured formats (CSV/Excel), and updating Excel templates with network data, including SSH credential handling, OUI lookups, and parallelized device info collection.
def main(): cisco_documentation_description = textwrap.dedent( """ Steps to use: - Create your switch-list.txt. switch-list.txt: " switch,driver,transport 192.168.1.1,ios,ssh " - If you have a large number of switches, create a file with credentials. credentials: " ...
def graph_v(v): fig = plt.figure() ax = fig.add_subplot(projection="3d") #every 3 points is a face, remap to v[f] verts = [] temp = [] while len(v) > 0: temp.append(v.pop(0)) if len(temp) >= 3: verts.append(temp.copy()) temp = [] #Poly3D...
The main task of the code is to visualize a graph generated from a mesh structure, which is constructed using a sampled dataset. The function `main()` triggers this process by passing a sampled version of `sample_10` through `construct_mesh()` to create a mesh, then passing the result to `graph_v()` for graphical repre...
def main(): graph_v(construct_mesh(sample(sample_10)))
def register_shapes(self): ''' function: adds the required gifs/imgs to the screen object to add later. params: none returns: none ''' try: self.wn.register_shape('./assets/xbutton.gif') self.wn.register_shape('./assets/checkbutton.gif'...
The main task of the code is to initialize a game screen and HUD elements for a Mastermind game. It sets up a Screen object, configures the window size and title, creates a hidden Turtle for drawing HUD components, registers shapes, and triggers drawing functions for the game board, pegs, leaderboard, and GIFs. This pr...
def init_game(self): ''' function: initializes the screen and the turtle drawing the hud boxes. ''' # initializing the turtle objects self.wn = Screen() self.wn.setup(500, 500) self.wn.title('CS5001: Mastermind') self.hud = Turtle() self.hud.speed(...
def check_code(self, player_guess): ''' function: checks the list player_guess compared to the generated correct color code. passes the amount of black first, then red into a dictionary for later retrieval when updating pegs. params: list player_guess containing the playe...
This function confirms a player's guess by validating its length, evaluating the guess against the code, updating the game state (win/loss), adjusting the board display, and resetting for the next guess if applicable.
def confirm_guess(self): ''' function: if list player_guess length is 4 (a full guess), checks the code, adds one to the guess if in valid, moves the to-be-drawn line down one on the board, and then resets the guess to zero params: none returns: none ''' ...
def init_game(self): ''' function: initializes the screen and the turtle drawing the hud boxes. ''' # initializing the turtle objects self.wn = Screen() self.wn.setup(500, 500) self.wn.title('CS5001: Mastermind') self.hud = Turtle() self.hud.speed(...
The code initializes a game by setting up logging, initializing game components (game, marbles, gameplay), retrieving the player's name, and starting a graphical interface with click event handling to begin or interact with the game.
def __init__(self): logging.basicConfig(filename='./logs/mastermind_errors.err', encoding='utf8', level=logging.DEBUG, format='%(asctime)s %(message)s') logging.info('init game...') self.init_game() ...
def update_guess(self, marble): ''' function: appends list player_guess to add color, empties given marble, and then updates the board to show selection params: marble object that was clicked returns: none ''' if (len(self.player_guess) < 4) and \ (...
The main task of the code is to handle screen click events by checking if a marble was clicked to update the guess or if a button (check, cancel, quit) was clicked to trigger corresponding actions, using coordinate ranges to determine the clicked element.
def on_click(self, x, y): ''' function: passes when a click occurs on screen. checks if marbles were clicked first, then within the separate clickable spaces. params: x, y as the coordinates that were clicked returns: none ''' # tests if a marble was clicked ...
def countVectors(A): numVectors = 0 if isinstance(A[0],list) == False: numVectors = 1 else: for row in A: numVectors += 1 return numVectors def projection(v, u): dot = dotProduct(u, v) distance = distanceOfSquared(u) w = vectorMultiplyScalar((dot / distance), u) ...
The code performs the Gram-Schmidt orthogonalization process on a set of vectors in 'span', iteratively subtracting projections of each vector onto previously computed orthogonal vectors to generate an orthogonal set. It returns the orthogonalized vectors in 'orthog'
def gramSchmidt2(span): m = countVectors(span) orthog = [] orthog.append(span[0]) counter = 0 for i in range(m-1): counter += 1 total = [] for j in range(counter): u = orthog[j] v = span[counter] proj = projection(v,u) total.app...
def countrows(A): numRows = 0 if isinstance(A[0],list) == False: numRows = 1 else: for row in A: numRows += 1 return numRows def countcolumns(A): numColumns = len(A[0]) return numColumns def ech(A): #turns column into all 0's except top row make...
This function transforms a matrix into its echelon form by iteratively applying row operations using a helper function 'ech', updating a copy of the original matrix at each step, and returning the modified matrix in echelon form.
def echelonform(A): copyA = copy.deepcopy(A) loopy = True counter = 1 m = countrows(A) n = countcolumns(A) A = ech(A) copyA[0] = A[0] while loopy == True: A = ech(A[1:]) copyA[counter]=A[0] counter += 1 if len(A) == 1: loopy = False ...
def countRows(A): numRows = 0 if isinstance(A[0],list) == False: numRows = 1 else: for row in A: numRows += 1 return numRows def countColumns(A): numColumns = len(A[0]) return numColumns def transpose(A): n = countColumns(A) m = countRows(A) B = [] C =...
This function calculates the determinant of a 4x4 matrix using cofactor expansion along the first row. It checks if the input is a valid 4x4 matrix, then iteratively constructs 3x3 submatrices by excluding rows and columns, computes their determinants recursively, and accumulates the result with alternating signs to ac...
def determinant4x4(A): if (countRows(A) != countColumns(A)) or (countRows(A) != 4): return "Must be a 4x4 matrix" else: counter = 1 B = [] total = 0 k = 0 At = transpose(A) for i in range(countRows(A)): co = A[0][i] k = 0 ...
def countrows(A): numRows = 0 if isinstance(A[0],list) == False: numRows = 1 else: for row in A: numRows += 1 return numRows def countcolumns(A): numColumns = len(A[0]) return numColumns def ech(A): #turns column into all 0's except top row make...
The code computes the echelon form of a matrix by iteratively applying a row reduction function ('ech') to each row, storing intermediate results in a copy of the original matrix. It processes rows sequentially, updating the matrix and saving each transformed row into the copy until only one row remains, ultimately ret...
def echelonform(A): copyA = copy.deepcopy(A) loopy = True counter = 1 m = countrows(A) n = countcolumns(A) A = ech(A) copyA[0] = A[0] while loopy == True: A = ech(A[1:]) copyA[counter]=A[0] counter += 1 if len(A) == 1: loopy = False ...
def echelonform(A): copyA = copy.deepcopy(A) loopy = True counter = 1 m = countrows(A) n = countcolumns(A) A = ech(A) copyA[0] = A[0] while loopy == True: A = ech(A[1:]) copyA[counter]=A[0] counter += 1 if len(A) == 1: loopy = False ...
The main task of the code is to transform a given matrix into its reduced echelon form by iteratively applying the REF function, updating rows in a copied matrix, and printing the final result. It first converts the matrix to echelon form, then performs row operations to achieve reduced echelon form, storing intermedia...
def reducedEchelonForm(A): #*MAIN FUNCTION TAKES MATRIX AND TURNS IT INTO REDUCED ECHELON FORM* A = echelonform(A) copyA = copy.deepcopy(A) A = REF(A) copyA[-1] = A[-1] loopy = True counter = countrows(A) - 2 while loopy == True: A = REF(A[:-1]) copyA[counter]=A[-1] c...
def countRows(A): numRows = 0 if isinstance(A[0],list) == False: numRows = 1 else: for row in A: numRows += 1 return numRows def determinant3x3(A): if countRows(A) != countColumns(A): return "Must be a square matrix" if countRows(A) == 2: ad = A[0][0] ...
The function calculates the determinant of a square matrix using cofactor expansion. For 3x3 or smaller matrices, it directly computes the determinant. For 4x4 matrices, it uses a specific 4x4 determinant method. For larger matrices, it recursively applies cofactor expansion by iterating through the first row, construc...
def determinantMxN(A): #Main function that takes a square matrix and gets the det(A) if countRows(A) <= 3: return determinant3x3(A) elif countRows(A) == 4: return determinant4x4(A) else: counter = 1 B = [] total = 0 k = 0 At = transpose(A) fo...
def echelonform(A): copyA = copy.deepcopy(A) loopy = True counter = 1 m = countrows(A) n = countcolumns(A) A = ech(A) copyA[0] = A[0] while loopy == True: A = ech(A[1:]) copyA[counter]=A[0] counter += 1 if len(A) == 1: loopy = False ...
The main task of the code is to convert a given matrix into its reduced echelon form. It first transforms the matrix into echelon form using `echelonform()`, then iteratively applies the `REF()` function to refine each row from the bottom up. The process ensures leading ones and zeros are correctly positioned, updating...
def reducedEchelonForm(A): #*MAIN FUNCTION TAKES MATRIX AND TURNS IT INTO REDUCED ECHELON FORM* A = echelonform(A) copyA = copy.deepcopy(A) A = REF(A) copyA[-1] = A[-1] loopy = True counter = countrows(A) - 2 while loopy == True: A = REF(A[:-1]) copyA[counter]=A[-1] c...
def getb(A): B = [] C = [] m = countRows(A) for row in A: B.append(row[1]) C.append(B) C = transpose(C) return C def getA(A): B = [] C = [] m = countRows(A) for i in range(m): B.append(1) C.append(B) B = [] for row in A: B.append(row[0]) ...
The code computes the least squares solution for a linear regression model by forming the normal equations (A^T A x = A^T b), performing matrix operations to construct the augmented system, and solving it via reduced row echelon form to extract the intercept (b) and slope (m) parameters of the best-fit line.
def getFormula(A): b = getb(A) A = getA(A) aT = transpose(A) aTA = matrixMultiplication(aT, A) aTb = matrixMultiplication(aT, b) finalA = [] for i in range(len(aTb)): aTA[i].append(aTb[i][0]) REF = reducedEchelonForm(aTA) b = REF[0][len(REF[0]) - 1] m = REF[1][len(REF[1])...
def record_signal(alert_type): global signal if alert_type == "supertrend_buy": signal["supertrend"] = "BUY" if alert_type == "supertrend_sell": signal["supertrend"] = "SELL" if alert_type == "larsi_moveup": signal["larsi"] = "MOVEUP" if alert_type == "larsi_movedown": signal["larsi"] = "MOVED...
The function processes incoming alerts by reading request data, parsing JSON to extract alert type and price, recording signals, and managing trade orders (entering/exiting LONG/SHORT positions) based on alert type and current order status.
def process_alert(): global signal global current_order #Read the body from request body = request.body.read() req_val = request.body.getvalue() print(req_val) return #The request will be in string, convert it to json val = json.loads(req_val) print(val) return #Handle...
def createDatasetDir(datasetPath, imagesPath, labelsPath, imagesTrainPath, imagesValPath, labelsTrainPath, labelsValPath): if not os.path.exists(datasetPath): os.makedirs(datasetPath) os.makedirs(imagesPath) os.makedirs(labelsPath) os.makedirs(imagesTrainPath) os.makedirs(imagesValPath) os.makedirs(labelsT...
The main task of the code is to perform data augmentation on a geospatial dataset by copying and pasting detected objects from images into new images, using YOLOv5 for object detection. It generates augmented images with transformed objects, creates background images, and saves them in YOLOv5 format with corresponding ...
def main(): #random.seed(1) datasetPath = filedialog.askdirectory(title = "Select the original dataset") if not os.path.isfile(datasetPath + "/paths.txt"): sys.exit("Paths to TIF images are missing.") print("Path to save the augmented dataset.") print("<If you want to save in a existing dataset, select that ...
def _best_split(self, X: np.ndarray, y: np.ndarray) -> tuple[int, float]: """Find the best split for a node.""" feature_errors = [] for feature in range(X.shape[1]): errors = [] thresholds = sorted([x for x in set(X[:, feature])])[:-1] for threshold in thresho...
This function recursively splits a decision tree node by finding the best feature and threshold to partition the data. It creates left and right child nodes, storing metrics like sample count, mean value, and MSE. Splitting stops if minimum samples or maximum depth limits are reached, returning None otherwise. The node...
def _split_node(self, X: np.ndarray, y: np.ndarray, depth: int = 0) -> Node: """Split a node and return the resulting left and right child nodes.""" if len(y) < self.min_samples_split or depth > self.max_depth: return None node = Node() try: node.feature, node.th...
def open_csv(): try: csv_database = pd.read_csv(csv_file) csv_names = list(csv_database['Name']) return csv_database, csv_names except: # Exception as e # print(e) print('Error: Failed to Open Csv') def csv_names_casefold(csv_names): # Changed To pandas array instead...
The function checks if a product name exists in a CSV database. If it exists, it displays the entry; if not, it prompts the user to add the new product. It uses helper functions for database operations and user confirmation.
def usr_compare_database(name, using): csv_database, csv_names = open_csv() # Dont Need to declare value or date just put straight into function! if name.casefold() in csv_names_casefold(csv_names): exist_in_database(name, None, None) print(csv_database.loc[[csv_names.index(name)], :]) e...
def open_csv(): try: csv_database = pd.read_csv(csv_file) csv_names = list(csv_database['Name']) return csv_database, csv_names except: # Exception as e # print(e) print('Error: Failed to Open Csv') def create_date_column(date): csv_database, _ = open_csv() date ...
The code compares daily log data against a database by checking if product keys exist in CSV files. It handles recorded date values, identifies new products, and prompts user input to add them to the database. It also verifies product existence, sends low-stock notifications, and manages errors for missing data or inva...
def log_compare_database(): _, csv_names = open_csv() print(daily_log_dic) for key, value in daily_log_dic.items(): if value is None: print(f'Error: No Value Found For Key: {key}') elif key.startswith('Recorded'): print(f'{key} : {value}') # Print Recorded Keys and V...
def open_csv(): try: csv_database = pd.read_csv(csv_file) csv_names = list(csv_database['Name']) return csv_database, csv_names except: # Exception as e # print(e) print('Error: Failed to Open Csv') def usr_input_boolean(prompt): while True: bool_in = input(p...
The main task of the code is to allow a user to search a database by inputting a product name and specifying its usage status (in-use or not). The function retrieves available product names from a CSV file, prompts the user for input, and attempts to compare the input against the database using the `usr_compare_databas...
def main_usr_search_database_input(): _, csv_names = open_csv() print(f'Available Products:\n {csv_names} \n') name = input('-Input Name of Product: ') is_using = usr_input_boolean('-Currently InUse? True or False: ') try: usr_compare_database(name, is_using) except: # print(e)...
def open_log(log_file): try: # List Comprehensioned, Make tuple pairs from log file if data doesnt start with # with open(log_file, "r") as daily_log: products = [tuple(line.strip().split(':')) for line in daily_log if not line.startswith('#')] global ...
The function processes a single log file by first attempting to open it. If successful, it moves the file to old logs and initiates a comparison with a database, likely for analysis or updates. The main task is handling log file archiving and database synchronization.
def process_single_log(log_file): if open_log(log_file): # If True move_to_old_logs(log_file) log_compare_database()
def display_log_files(): print('Available Log Files:') try: # Scan for files in root, if is file, get file name, if file starts with Log, add to list log_names = [log.name for log in os.scandir( '.') if log.is_file() and log.name.startswith('Log')] log_names.sort() for item ...
The main task of the code is to process log files by either handling multiple logs (if available) based on user confirmation or processing a single specified log file. It checks for multiple log files, prompts user input for bulk processing, and executes the processing function accordingly, ensuring single-file handlin...
def main_process_logs(): log_names = display_log_files() usr_multiple_logs = False if len(log_names) > 1: usr_multiple_logs = yes_no_check('\n-Open Multiple Log Files Y/N: ') if usr_multiple_logs: # If True for log_file in log_names: process_single_log(log_file...
def cls(): os.system('cls' if os.name == 'nt' else 'clear') def display_menu_options(): print(""" Inventory Manager Options: Process Log File = (1) Linear Regression Forecast (3 Logs Required) = (2) Search/Add Database = (3) Add Product to Order = ...
The code defines a menu-driven application that repeatedly displays options for users to interact with a system. It processes user inputs to execute tasks like viewing logs, forecasting, searching databases, adding products to orders, displaying database content, or resetting the system. The loop continues until the us...
def main(): while True: cls() display_menu_options() usr_choice = usr_input_num('-Input a Number: ') match usr_choice: case 1: cls() main_process_logs() case 2: cls() main_usr_forecast() ...
def get_cleaner(): cleaner = { 'name' : lambda x: x.strip('*'), 'school' : None, 'none' : None, 'height' : lambda x: (int(x.split('-')[0]) * 12) + int(x.split('-')[1]), 'weight' : lambda x: int(x.strip()...
The main task of the code is to scrape and organize NFL player data from HTML tables for the year 2017. It initializes a dictionary structured by player positions (e.g., QB, RB), iterates through HTML pages in chunks (itemnum steps of 10), extracts player statistics using `get_player`, and populates the dictionary with...
def main(): # Dictionary the scraper will fill out player_dict = { 'QB' : {}, 'RB' : {}, 'FB' : {}, 'TE' : {}, 'WR' : {}, 'C' : {}, 'OT' : {}, ...
def _downloads_db_connection( downloads_dir: pathlib.Path, ) -> sqlite3.Connection: db_path = downloads_dir / ".downloads.sqlite3" with sqlite3.connect(db_path) as connection: _init_db(connection) return sqlite3.connect(db_path) def _convert_osf_url_to_download(url: str) -> str: match = re.m...
This function retrieves the local path of a downloaded archive from a database if it exists for the given URL; otherwise, it converts the URL and downloads the archive, returning its path.
def _get_archive( url: str, downloads_dir: Union[str, pathlib.Path] ) -> pathlib.Path: downloads_dir = pathlib.Path(downloads_dir) with _downloads_db_connection(downloads_dir) as connection: result = connection.execute( "SELECT local_path FROM downloads WHERE url=?", (url,) ).fet...
def _insert_project( connection: sqlite3.Connection, project_dir: pathlib.Path ) -> None: with connection: connection.execute( "insert into project (name) values (?)", (project_dir.name,) ) def _insert_project_documents( connection: sqlite3.Connection, project_dir: pathlib.Path )...
The function `_fill_database` populates an SQLite database by connecting to the specified path, enabling foreign keys, and iterating through project directories. For each project, it inserts project details, documents, labels, and annotations using helper functions, organizing data systematically into the database.
def _fill_database(db_path: pathlib.Path): with contextlib.closing(sqlite3.connect(db_path)) as connection: connection.execute("pragma foreign_keys = on") projects_root_dir = repo.repo_root() / "projects" for project_dir in sorted(projects_root_dir.glob("*")): if not project_dir....
def _get_tokens(annotations: pd.DataFrame) -> pd.DataFrame: annotation_stacks = annotations.groupby(["start_char", "end_char"]) tokens = [] for position, anno_stack in annotation_stacks: tokens.append(_token_from_annotations(anno_stack, *position)) return pd.DataFrame(tokens) def _build_group_tr...
The function processes annotations to extract participant information by building a hierarchical group tree, adding relevant details, pruning empty groups, and summarizing the structured data into a dictionary.
def _get_participants_info(annotations: pd.DataFrame) -> Dict: tokens = _get_tokens(annotations) root = _build_group_tree(tokens) _add_info(tokens, root) _prune_empty_groups(root) summary = _summarize(root) return summary
def _get_labelbuddy_file( project_name: str, annotator_name: str ) -> pathlib.Path: return pathlib.Path( "projects", project_name, "annotations", f"{annotator_name}.labelbuddy", ) def _get_doc_positions_in_db(db_path: pathlib.Path) -> Dict: full_db_path = repo.repo_root()...
The function processes annotations from multiple annotators across projects to generate structured document summaries. It extracts metadata, checks for data integrity (e.g., missing diagnoses, counts), and handles errors. Each summary includes document position info, participant details, warnings, and error handling fo...
def _get_document_summaries(all_annotations: pd.DataFrame) -> List[Dict]: if not all_annotations.shape[0]: return [] all_docs = [] positions = {} for project_name, annotator_name in ( all_annotations.loc[:, ["project_name", "annotator_name"]] .drop_duplicates() .values ...
def select_participants_annotations( annotator_name: Optional[str] = None, project_name: Optional[str] = None, pmcid: Optional[int] = None, ) -> pd.DataFrame: demo_labels = ", ".join(map("'{}'".format, _DEMOGRAPHICS_LABELS)) annotator_query = ( "" if annotator_name is None else "and annotato...
The function `get_report` generates an HTML report by retrieving and sorting annotations/data based on input parameters (annotator, project, PMCID), then rendering them using a Jinja template. It handles dynamic sorting logic, merges metadata, and returns the rendered report.
def get_report( annotator_name: Optional[str] = None, project_name: Optional[str] = None, pmcid: Optional[int] = None, standalone: bool = False, ) -> str: all_anno = select_participants_annotations( annotator_name=annotator_name, project_name=project_name, pmcid=pmcid ) all_docs = _g...
def initialize_parameters_deep(layer_dims): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (...
The function `L_layer_model` trains an L-layer neural network with [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID architecture. It initializes parameters, iteratively performs forward propagation, computes cost, backpropagates gradients, and updates parameters using gradient descent. It tracks and optionally plots the cost over...
def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False): #lr was 0.009 """ L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID. Arguments: X -- data, numpy array of shape (number of examples, num_px * num_px * 3) Y -- true "label" vector (cont...
def update_modules(repository): repository_hashes = get_tree_hashes_per_repo(repository) for repository_hash in repository_hashes: try: gittree_element = repository.get_git_tree(repository_hash) except GithubException: pass try: for type_tree in gittr...
This function updates repository data in a database by syncing information from an external source. It checks if each repository exists, updates its description if present, or adds it as a new entry. It then triggers updates for modules, counts modules per version, and fetches documentation (readme) for each repository...
def update_repositories(): counter = 0 repositories = get_oca_repositories() for repository in repositories: # start: update repository if Repository.query.filter(Repository.repository == repository.name).first(): repo = Repository.query.filter(Repository.repository == repository...
def update_modules(repository): repository_hashes = get_tree_hashes_per_repo(repository) for repository_hash in repository_hashes: try: gittree_element = repository.get_git_tree(repository_hash) except GithubException: pass try: for type_tree in gittr...
The main task of the code is to update a repository's description in the database and trigger subsequent operations like module updates, module counting, and fetching documentation (installable info, README) for the given repository. The function retrieves the repository, updates its description, commits changes, and e...
def update_single_repository(repository1): repository = get_one_repository(repository1) repository1 = Repository.query.filter(Repository.repository == repository.name).first() repository1.description = repository.description db.session.commit() update_modules(repository) count_modules(repository...
def getTweets(self): stuff = [] tweets = api.user_timeline(screen_name=self.getUName(), count=200) for twee in tweets: stuff.append(noSillyTrump(twee._json["text"])) return stuff def getJSON(self, tweet): return { "platform": 1, "username": str...
The main task of the code is to retrieve tweets using `getTweets()`, convert each tweet to JSON format with `getJSON()`, and send them via a push service using `push.send()`. A 0.07-second delay is introduced to prevent overloading, followed by a "yay" confirmation and a call to `getIdDump()` for further processing or ...
def pushAllTweets(self): sleep(0.07) tweets = self.getTweets() for tweet in tweets: push.send(self.getJSON(tweet)) print("yay") self.getIdDump()
def get_raw_team_stats(raw_match, team_id): for raw_team_stats in raw_match["teams"]: if raw_team_stats["teamId"] == team_id: return raw_team_stats raise ValueError("Raw team with id " + team_id + " not found") def get_team_bans(raw_bans): bans = [] for raw_ban in raw_bans: b...
The function `get_team_stats` extracts and processes team-specific statistics from a raw match data structure. It retrieves base stats via `get_raw_team_stats`, then constructs a dictionary with transformed values: whether the team won, counts of dragons, heralds, barons, and towers, processed bans, and performance met...
def get_team_stats(raw_match, team_id): stats = get_raw_team_stats(raw_match, team_id) return { "won": stats["win"] == "Win", "dragons": stats["dragonKills"], "heralds": stats["riftHeraldKills"], "barons": stats["baronKills"], "towers": stats["towerKills"], "bans"...
def get_date(raw_match): date = datetime.datetime.fromtimestamp(raw_match["gameCreation"] / 1000.0) return date.strftime('%Y-%m-%d %H:%M:%S.%f') def get_minutes_played(raw_match): minutes = raw_match["gameDuration"] // 60 if raw_match["gameDuration"] % 60 >= 30: minutes += 1 return minutes d...
The main task of the code is to transform raw match data into a structured dictionary. It extracts and processes fields like game ID, date, duration, and team statistics (blue/red) from the input `raw_match`, incorporating an optional `serverIdentity` parameter. The function organizes this data into a standardized form...
def parse_raw_match(raw_match, serverIdentity=None): return { "id": str(raw_match["gameId"]), "date": get_date(raw_match), "minutesPlayed": get_minutes_played(raw_match), "serverIdentity": serverIdentity, "blue": get_team_stats(raw_match, 100), "red": get_team_stats(r...
def get_text(filename): with open('Data/shakespeare.txt', 'r', encoding = 'utf8') as t: text = t.read() return text def prep_data(text, model): encoded_text = np.array([model.encoder[char] for char in text]) num_char = max(encoded_text) + 1 train_ind = int(len(encoded_text) * (train_per...
This code trains a Character-Level Recurrent Neural Network (CharRNN) with LSTM for text generation. It initializes the model, prepares training/test data, trains over epochs using batches, applies gradient clipping, validates periodically, saves the trained model, and generates text. The model learns to predict next c...
def main(): # Initialise text = get_text(filename) all_char = set(text) model = CharRNN(all_chars = all_char, num_hidden = 512, num_layers = 3, drop_prob = 0.5) train_data, test_data, num_char = prep_data(text, model) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model....
def _most_common_label(self,y): counter = Counter(y) value = counter.most_common(1)[0][0] return value def _best_split(self, X,y,feat_indxs): best_gain = -1 split_idx, split_threshold = None, None for feat_indx in feat_indxs: X_column = X[:, feat_indx] ...
This function recursively builds a decision tree by selecting random features, finding the best split, and creating child nodes. It checks stopping criteria like maximum depth, single class, or minimum samples to return a leaf node. If not, it splits data, grows subtrees, and returns a node with the best feature, thres...
def _grow_tree(self, X, y, depth = 0): n_samples,n_feats = X.shape n_labels = len(np.unique(y)) #check stopping criteria if (depth >= self.max_depth or n_labels == 1 or n_samples < self.min_samples_split): leaf_value = self._most_common_label(y) return Node(value ...
def handle_login_message(conn: socket.socket, data: str): """ Gets socket and message data of login message. Checks user and pass exists and match. If not - sends error and finished. If all ok, sends OK message and adds user and address to logged_users Recieves: socket, message code and data Return...
This function processes incoming client messages by routing them to appropriate handlers based on the command type and user login status. It checks if the user is logged in, then directs commands like login, signup, logout, score retrieval, user lists, questions, and answers to their respective handling functions, send...
def handle_client_message(conn: socket.socket, cmd: str, data: str): """ Gets message code and data and calls the right function to handle command Recieves: socket, message code and data Returns: None """ global logged_users # To be used later if conn not in logged_users: if cmd == ...
def get_questions(): """ get from api the trivia questions :return: a list of 50 questions """ global questions response = requests.get("https://opentdb.com/api.php?amount=50&type=multiple") return response.json() def setup_socket(): """ Creates new listening socket and returns it ...
This code runs a trivia game server that initializes question data, manages client connections via sockets, processes incoming messages, and sends responses. It uses select.select for asynchronous communication, handles HTML unescaping for questions, and maintains a list of messages to send to clients.
def main(): # Initializes global users and questions dicionaries using load functions, will be used later global users global questions global messages_to_send questions = get_questions()["results"] for question in questions: question["question"] = html.unescape(question["question"]) ...
def connect(): """ Establishing a connection with the server :return: A socket of the established connection between the client and server. """ client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((SERVER_IP, SERVER_PORT)) return client_socket def auth_user...
The main task of the code is to provide a menu-driven interface for a trivia game, allowing users to retrieve their score, view high scores, play trivia questions, check logged users, and quit. It maintains a database connection, handles user authentication, executes chosen actions, and ensures proper logout and connec...
def main(): try: conn = connect() auth_user(conn) while True: action = input("Please enter your choice:\n" "s Get my score\n" "h Get high score\n" "p Play a ...
def getTags(self, title: str) -> list: return self.getPost(title)[1].split(",") def getCreationDate(self, title: str) -> str: return self.getPost(title)[3] def getTitles(self) -> list: titles = self.run("SELECT title FROM blogs ORDER BY i_date_created DESC").fetchall() return [title[0] f...
This code generates a list of posts, each represented as a tuple containing the post title, a list of colored tags (using util.colorGen), and the post's creation date. It processes all titles retrieved by self.getTitles(), formats tags with dynamic colors, and compiles structured data for directory display.
def getDirectoryPosts(self) -> list: return [(title, [(tag, util.colorGen(tag)) for tag in self.getTags(title)], self.getCreationDate(title)) for title in self.getTitles()]
def read(self, filename): with open(filename) as f: return f.read() def findAllIndicesWithin(self, l: list, symbol): index = [] i=0 append = False while i < len(l): if l[i]== symbol: append = not append if append: ...
The code parses a file's content to extract dates, tags, title, and body, then saves a blog post to a database, handling special formatting like code blocks and date/timestamps.
def populate(self, filename: str) -> None: content = self.read(filename).split("\n") blockLines = self.findAllIndicesWithin(content, "```") lines = [content[i] for i in range(len(content)) if content[i]!="" or i in blockLines] dates = [] while lines[0][0] == "(...
def update_avail_actions(self): activated_idx = np.array(list(self.seed_nodes.keys())) self.action_mask = np.array([1] * self.max_avail_actions) ## all actions are available if len(activated_idx) > 0: self.action_mask[activated_idx] = 0 disable_node = np.where(self.out_degre...
This function processes a level-2 agent's action in a reinforcement learning environment, updating the state by appending repeated elements based on a degree-based probability. It calculates influence rewards, manages seed node tracking, and returns observations, rewards, and termination status for level-1 and level-2 ...
def _step_level2(self, action): if self.validation: if len(self.seed_nodes) >= self.MAX_TIME_STEP: print("DONE HERE", len(self.seed_nodes), self.MAX_TIME_STEP) self.done = self.current_t if not (self.validation and self.done): self.seed_no...
def length(s): """Select the length of a side.""" return label(s) def total_weight(m): """Return the total weight of m, a weight or mobile. >>> t, u, v = examples() >>> total_weight(t) 3 >>> total_weight(u) 6 >>> total_weight(v) 9 """ if is_weight(m): return size...
The code calculates torque by multiplying the length of a given side with the total weight at its end, returning the product as the resulting torque value.
def torque(side): return length(side) * total_weight(end(side))
def tree(label, branches=[]): """Construct a tree with the given label value and a list of branches.""" for branch in branches: assert is_tree(branch), 'branches must be trees' return [label] + list(branches) def total_weight(m): """Return the total weight of m, a weight or mobile. >>> t, u...
The function `with_totals` returns a new mobile where each node's label is replaced with the total weight of its corresponding subtree, computed recursively. It preserves the original mobile's structure without modifying it. For each side of the mobile, it recursively applies `with_totals` to compute subtree totals, th...
def with_totals(m): """Return a mobile with total weights stored as the label of each mobile. >>> t, _, v = examples() >>> label(with_totals(t)) 3 >>> print(label(t)) # t should not change None >>> label(with_totals(v)) 9 >>> [label(end(s)) for s in sides(w...
def mobile(left, right): """Construct a mobile from a left side and a right side.""" return tree(None, [left, right]) def side(length, mobile_or_weight): """Construct a side: a length of rod with a mobile or weight at the end.""" return tree(length, [mobile_or_weight]) def weight(size): """Construct...
The code defines three nested mobile structures (t, u, v) with recursive side-weight configurations, returning them as a tuple. Each mobile consists of sides with lengths and weights or sub-mobiles, demonstrating hierarchical data construction.
def examples(): t = mobile(side(1, weight(2)), side(2, weight(1))) u = mobile(side(5, weight(1)), side(1, mobile(side(2, weight(3)), side(3, weight(2))))) v = mobile(side(4, t), side(2, u)) return (t, u, v)
def is_weight(w): """Whether w is a weight, not a mobile.""" return label(w) != None def torque(side): return length(side) * total_weight(end(side)) def left_side(m): return sides(m)[0] def right_side(m): return sides(m)[1] def end(s): """Select the mobile or weight hanging at the end of a side....
The function `balanced(m)` checks if a mobile structure is balanced by verifying two conditions: (1) the torque (length × weight) of the left and right sides are equal, and (2) both sides themselves are balanced. It recursively ensures all sub-components (weights and sub-mobiles) meet the balance criteria. If `m` is a ...
def balanced(m): """Return whether m is balanced. >>> t, u, v = examples() >>> balanced(t) True >>> balanced(v) True >>> w = mobile(side(3, t), side(2, u)) >>> balanced(w) False >>> balanced(mobile(side(1, v), side(1, w))) False >>> balanced(mobile(side(1, w), side(1, v)...
def forward_box(self, positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict): all_center_embeddings, all_offset_embeddings, all_idxs = [], [], [] all_union_center_embeddings, all_union_offset_embeddings, all_union_idxs = [], [], [] for query_structure in batch...
The main task of the code is to route the forward pass of a neural network based on the geometry type specified in `self.geo`, delegating computation to specialized methods like `forward_box`, `forward_vec`, etc., which handle different geometric interpretations (e.g., box, vector, beta distribution, cone, logic). It p...
def forward(self, positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict): if self.geo == 'box': return self.forward_box(positive_sample, negative_sample, subsampling_weight, batch_queries_dict, batch_idxs_dict) elif self.geo == 'vec': return se...
def left_left_case(self, node: Node) -> Node: """The tree is heavily unbalanced to the left (left-left case). Performed when the node is inserted into the right subtree leading to an unbalanced tree. This is a single left rotation to make the tree balanced again. Args: ...
The main task of the code is to rebalance an AVL tree by checking a node's balance factor and applying rotations (left-left, left-right, right-right, right-left cases) to restore balance. It returns the new root node after adjustments, ensuring the tree maintains its balance property with rotations when the balance fac...
def balance(self, node: Node) -> Node: """Rebalances the tree if any balancing is needed at all. There are. four cases to consider: 1. The tree is heavily unbalanced to the left (left-left case). Performed when the node is inserted into the right subtree leading to an unbalanced...
def update(self, node: Node) -> None: """Update the height and balance factor for the current node. Retrieve the left subtree height and the right subtree height. Then the height of the current node will be the maximum between the two subtree heights + 1 (we still have to consider the cu...
This function inserts a value into a binary tree recursively, updating node heights and rebalancing the tree through rotations if necessary. It handles base cases by creating new nodes at empty spots, then backtracks to update heights and ensure balance, returning the root node after potential rotations.
def __add(self, node: Node, value: int) -> Node: """Adds the queried value to the binary tree. It calls itself recursively to determine where in the binary should the value be inserted. The base case is if we have reached an empty or null node, that means we have found the correct subtre...
def find_maximum(self, node: Node) -> int: """Find the node with the maximum value in the binary tree. Args: node (Node): The current node. Returns: int: The greatest value of the binary tree. """ while node.right: node = node.right ...
This method removes a node with the specified value from an AVL tree using a recursive approach. It handles cases where the node has 0, 1, or 2 children, employing a height-based heuristic to select the successor (max from left subtree if taller, min from right subtree otherwise). After updating node heights, it rebala...
def __remove(self, node: Node, value: int) -> None: """Implement the remove method using the standard recursive implementation of remove for a normal BST. The only difference here is that the AVL tree utilizes a height heuristic to determine the successor node. The successor node will be...
def IGRF_coef(year, table=IGRF_COEFS_TABLE): if (year < 1900.0) or (year >= 2025.0): raise Exception('Invalid year, should be in [1900, 2025)') delta_year = year % 5 year_5 = year - delta_year G = np.zeros((14, 14)) H = np.zeros((14, 14)) if year_5 < 2020: col_num = int(year_...
The code computes the Earth's magnetic field components (B_r, B_θ, B_φ) in spherical coordinates using IGRF model coefficients, taking inputs of year, radial distance (r), polar angle (θ), azimuthal angle (φ), and a coefficient table. It calculates derivatives of the IGRF coefficients to determine the field components,...
def magn_field(year, r, theta, phi, table=IGRF_COEFS_TABLE): a = 6371200 # [m] G, H = IGRF_coef(year, table=table) B_r = - r_deriv_full(a, G, H, r, theta, phi) B_theta = - theta_deriv_full(a, G, H, r, theta, phi) / r B_phi = - phi_deriv_full(a, G, H, r, theta, phi) / (r * np.sin(theta)) retu...
def X_CIP(JC, tables=X_CIP_COEFS_TABLES): """ X-coordinate of the CIP in [rad] """ UARCSEC2RAD = np.pi / 180 / 3600 / 1000000 return (X_polynom(JC) + X_non_polynom(JC, tables=tables)) * UARCSEC2RAD def Y_CIP(JC, tables=Y_CIP_COEFS_TABLES): """ Y-coordinate of the CIP in [rad] """ ...
The function computes a transformation matrix by combining a rotation matrix R with a coefficient matrix A, derived from input parameters JC and tables. Matrix A is constructed using X, Y values (from X_CIP/Y_CIP) and their quadratic terms, while R represents a rotation around the z-axis. The result is a 3D transformat...
def nut_prec(JC, tables_X=X_CIP_COEFS_TABLES, tables_Y=Y_CIP_COEFS_TABLES, tables_sXY=sXY_CIO_COEFS_TABLES): X = X_CIP(JC, tables=tables_X) Y = Y_CIP(JC, tables=tables_Y) s = sXY(JC, tables=tables_sXY) - X * Y / 2 X2Y2 = X ** 2 + Y ** 2 XY = X * Y a = 0.5 + X2Y2 / 8 A = np.array([[1 - a *...
def JD_add_seconds(seconds): return seconds / 24 / 3600 def jul_cent(JD): """ Julian Centuries, starting from 2000 Jan 1d 12h, in UTC """ return (JD - 2451545) / 36525 def TIP_coords(JD, table=TIP_AND_DUT1_TABLE): """ returns: x_p in [rad] y_p in [rad] dU...
The main task of the code is to compute the Direction Cosine Matrix (DCM) transforming coordinates from Earth-Centered, Earth-Fixed (ECEF) to Earth-Centered Inertial (ECI) frames. It combines three transformation matrices: nutation/precession (Q), Earth rotation (R), and polar motion (W), using time conversions, celest...
def DCM_ECEF_to_ECI(JD_UTC, tables_X=X_CIP_COEFS_TABLES, tables_Y=Y_CIP_COEFS_TABLES, tables_sXY=sXY_CIO_COEFS_TABLES, table_TIP_and_DUT1=TIP_AND_DUT1_TABLE): JD_TT = JD_UTC + JD_add_seconds(37 + 32.184) JC_UTC = jul_cent(JD_UTC) JC_TT = jul_cent(JD_TT) x_p, y_p, DUT1 = TIP_coords(JD...
def julian_to_year_frac(JD): year, month, day, hour, min, sec = julian_to_greg(JD) if year % 4 == 0: DAYS = {0: 0, 1: 31, 2: 60, 3: 91, 4: 121, 5: 152, 6: 182, 7: 213, 8: 244, 9: 274, 10: 305, 11: 335, 12: 366} else: DAYS = {0: 0, 1: 31, 2: 59, 3: 90, 4: 120, 5: 151, 6: 181, 7: 212, 8: 243,...
This function computes the geomagnetic field in Earth-Centered Inertial (ECI) coordinates by first calculating the magnetic field in Earth-Centered Earth-Fixed (ECEF) coordinates using IGRF models, then applying a rotation matrix derived from celestial ephemeris data to convert the field from ECEF to ECI frames.
def magn_field_ECI(JD_UTC, r, theta, phi, table_IGRF=IGRF_COEFS_TABLE, tables_X=X_CIP_COEFS_TABLES, tables_Y=Y_CIP_COEFS_TABLES, tables_sXY=sXY_CIO_COEFS_TABLES, table_TIP_and_DUT1=TIP_AND_DUT1_TABLE): year = julian_to_year_frac(JD_UTC) B = magn_field_ECEF(year, r, theta, phi, table=table_IGR...
def pkt_departure_generator(self): for i in range(0, self.ctlNum): pktLeaveTime = [] while len(pktLeaveTime) == 0: logging.info("Packets' leaving time is generated from ctl") pktLeaveTime = sample_possion(self.set.ctlRate[i], self.set.timeStep) ...
This code simulates packet scheduling in a network with controllers and schedulers. It dequeues packets, calculates communication delays, enqueues packets into controller queues, updates reward based on response times, processes packets in controllers, and generates observations for reinforcement learning. It tracks pa...
def step(self, action): if type(action).__module__ == np.__name__: schDecision = action[0] else: schDecision = action done = False # Take Action: distribute the first packet from scheduler to controller pkt = self.sch_queues[self.sch].dequeue() sel...
def isGameOver(board, checkWinner): return checkWinner(board, "X") or checkWinner(board, "O") or checkDraw(board, checkWinner) def getValidMoves(board, current_player): valid_moves = [] for i in range(3): for j in range(3): if board[i][j] == "": valid_moves.append(Move(cu...
The code simulates a Tic-Tac-Toe game where two players take turns making random moves on a board until a win or draw is determined. It initializes players with alternating symbols ('X' and 'O'), updates the board state, checks for game-ending conditions, and alternates turns. The loop continues until the game conclude...
def main(): player1 = Player(choice(["X", "O"]), "Player 1") player2 = Player("X" if player1.symbol == "O" else "O", "Player 2") board = Board() print(board.board) players = [player1, player2] print(player1.symbol, player2.symbol) current_player = players[0] while not isGameOver(boar...
def createIndexWidget(self): self.indexWidget = QWidget() self.indexLayout = QHBoxLayout() self.indexWidget.setLayout(self.indexLayout) self.indexWidget.setStyleSheet("border: 3px solid black;\ font-weight: bold;\ ...
The code initializes a stock GUI application by setting up a main window with a fixed size and title. It creates a central widget with a grid layout and a background image, adds an error message box, and initializes three sub-widgets (index, left, right). It also prepares variables for handling mouse interactions to en...
def __init__(self): super().__init__() self.setWindowTitle('StockGUI') self.setFixedSize(1260, 680) # set central widget and general layout # we will use a grid layout for the general layout self.generalLayout = QGridLayout() self.centralWidget = QWidget(self) ...
def prepareInsert(tableName, data, isReset = False): if not isReset: data = data.replace("'", '"') # data = ConvertNameValue(json.loads(data)[0]) data = json.loads(data)[0] for c in CHECKBOXES: data = ConvertCheckBox(data, c); for d in data: if not data[d] and d not in CHECK...
The main task of the code is to insert data into a database table specified by `status`, after preparing fields and validating insertion conditions. If `isReset` is True, it bypasses validation and inserts directly. Otherwise, it checks if the data meets conditions using `CanInsert`, constructs an SQL INSERT query, exe...
def create(status, data, isReset = False): tableName = status.replace("CREATE", "") fieldLi, data = prepareInsert(tableName, data, isReset) if isReset: canInsert = True else: itemNameMetCondi = GetItemNameMetCondi(data, tableName) canInsert, insertMsg = CanInsert(data, itemNameMetCondi, ...
def prepareInsert(tableName, data, isReset = False): if not isReset: data = data.replace("'", '"') # data = ConvertNameValue(json.loads(data)[0]) data = json.loads(data)[0] for c in CHECKBOXES: data = ConvertCheckBox(data, c); for d in data: if not data[d] and d not in CHECK...
The code updates a database table based on the 'status' and 'data' parameters. If 'all' is in 'status', it prepares insert data, checks conditions, and executes an UPDATE query. Otherwise, it converts data to JSON, handles datetime fields, constructs an update query, and executes it with the provided data.
def update(status, data): tableName = status.replace("UPDATE", "") if 'all' in status: tableName = tableName.replace("all", "") fieldLi, data = prepareInsert(tableName, data, False) pwTrue = GetPWTrue(tableName, data) itemNameMetCondi = GetItemNameMetCondi(data, tableName) ...
def read(status, data): filterField, filterData = SplitLi(ConvertLi(data)) tableName = status.replace("READ", "") if MRS in tableName: dtField = "start_dt" elif QS_FURNACE in tableName: dtField = "inspection_dt" else: dtField = "input_dt" if 'X' in filterData: del filterField[filterDat...
The main task of the code is to process operations based on the 'status' value in the 'linked' input. It routes data to corresponding functions (read, create, delete, update, etc.) depending on the status, then commits the database transaction.
def main(linked): if not linked: return status, data = linked # linked = [status, data] if 'READ' in status: read(status, data) elif 'CREATE' in status: create(status, data) elif 'DELETE' in status: delete(status, data) elif 'UPDATE' in status: update(status, data) elif 'input_tpn' in status...
def get_hovered_partial_move(game: Game) -> Union[PartialMove, None]: mouse = Vector(*pygame.mouse.get_pos()) hover_tile: Union[Tile, None] = None hover_factory: Union[int, None] = None for factory_index in [*range(FACTORY_COUNT), -1]: for tile in TILE_TYPES: if factory_index == -1:...
This function renders a game's UI using Pygame, drawing borders, player stats, factories, tiles, and interaction highlights. It updates the canvas with game state elements like player wins, ties, and hovered/tile selections, adjusting cursors and visual feedback based on user interactions and partial moves.
def render_game( game: Game, graphics_info: GraphicsInfo, *, player1_wins=-1, player2_wins=-1, ties=-1, no_tiles_but_wall=False, player_choice: Literal["tile", "line", None] = None, partial_tile_move: Union[PartialMove, None] = None, ) -> None: graphics_info.canvas.fill(COLOR_WHI...
def correct_offset(self): structure_residue_positions = { row["residue_number"]: row["residue_name"] for _, row in self.residue_characteristics.iterrows() } offset = self.determine_residue_offset(structure_residue_positions, self.uniprot_residue_positions) if offset != 0: ...
This code initializes a protein structure analyzer by loading a PDB file, extracting residue data, converting residue names to single-letter codes, and calculating structural features like buriedness, contact counts, active site proximity, and secondary structure. It then binarizes these characteristics for analysis.
def __init__( self, filename: str, active_site_residues: List[int], uniprot_residue_positions: dict, ): self.filename = filename self.uniprot_residue_positions = uniprot_residue_positions self.active_site_residues = active_site_residues self.structure ...
def _is_negated(tok): parts = list(tok.lefts) + list(tok.rights) for dep in parts: if dep.dep_ in BREAKER_POS: break if dep.lower_ in NEGATIONS: return True return False def _get_subs_from_conjunctions(subs): more_subs = [] for sub in subs: # rights is...
This function identifies all subject tokens related to a given verb node in a dependency parse, checking for negation and handling conjunctions. It first collects direct subjects, then extends them with conjuncts if needed. If no direct subjects are found, it uses an alternative method to locate subjects. Returns a lis...
def _get_all_subs(v): verb_negated = _is_negated(v) subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != "DET"] if len(subs) > 0: subs.extend(_get_subs_from_conjunctions(subs)) else: foundSubs, verb_negated = _find_subs(v) subs.extend(foundSubs) return subs,...
def _is_non_aux_verb(tok): return tok.pos_ == "VERB" and (tok.dep_ != "aux" and tok.dep_ != "auxpass" and tok.dep_ != "amod" and tok.dep_ != "prep" and tok.dep_ != "acl") def _is_passive(tokens): for tok in tokens: if tok.dep_ == "auxpass" or (tok.pos_ == "AUX" and tok.dep_ not in {"xcomp","ROOT"}) or t...
The main task of the code is to extract subject-verb-object (SVO) triples from text, handling passive voice, negation, and conjunctions. It processes input tokens (text or spaCy doc), identifies verbs, retrieves subjects and objects, adjusts for passive voice by swapping subject/object roles, applies negation markers (...
def findSVOs(tokens): if isinstance(tokens, str): tokens = nlp(tokens) svos = [] verbs = [tok for tok in tokens if _is_non_aux_verb(tok)] if not verbs: verbs = [tok for tok in tokens if (tok.pos_ == "AUX" and tok.dep_ == "xcomp")] visited = set() # recursion detection for v in v...
def newDatabaseConnection() -> None: while True: # create the config file information = databaseInfoGUI() serverConfiguration = information[0] newDB = information[1] newTB = information[2] password = information[3] mysql_management.write_yaml_to_file(serverCon...
The main task of the code is to create a GUI application for managing financial transaction data via a MySQL database. It handles database setup, CSV import, data modification, deletion, manual entry, and visualization. The program checks for a configuration file, establishes a database connection, updates the GUI tabl...
def main() -> None: # set the pysimplegui initial theme colour_theme = 'DarkGrey13' # set the initial font size pg.set_options(font=("Arial", 11)) # setup the server with the config file configFile = Path("server_configuration.yaml") serverConfiguration = dict() # if the config file e...
def set_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def save_image(tensor, filename): tensor = tensor.cpu().numpy() # Move to CPU tensor = ten...
This code generates video content from text prompts using a diffusion model, with optional conditioning on initial images, multi-frame generation, and upscaling. It initializes pipelines, processes prompts, runs diffusion steps, and decodes latent representations into videos, supporting parameters like resolution, guid...
def inference( model: str, prompt: str, negative_prompt: Optional[str] = None, width: int = 512, height: int = 512, image_width: int = None, image_height: int = None, model_2d: str = None, num_frames: int = 24, vae_batch_size: int = 8, vae_scale: float = 1.0, num_steps: i...
def getValidMonthAndYearTbwes(self,currentMonth): """ data should be mapped between 1.11.2023 to 29.02.2024. """ x = int(((currentMonth-0.1)//2)) x1 = (((currentMonth + 1-0.1)//2)) if x % 2 == 0 and x == x1: validMonth = 1 validYear = 2024 ...
The main task of the code is to retrieve and process time-series data from specified units, calculate a 5-minute time window around the current time, fetch associated tag metadata, and update Redis with the latest values. It constructs start/end timestamps, retrieves data via `dataExachangeTbwes`, and stores results in...
def mainFuncTbwes(self,unitsId,client,destUnitId): self.destUnitId = destUnitId currentTimeStamp = int(time.time()*1000) currentTime = datetime.datetime.now() currentMonth = currentTime.month currentQuarter = (currentMonth-1)//3 + 1 currentDay = currentTime.day ...
def getValidMonthAndYearTbwes(self,currentMonth): """ data should be mapped between 1.11.2023 to 29.02.2024. """ x = int(((currentMonth-0.1)//2)) x1 = (((currentMonth + 1-0.1)//2)) if x % 2 == 0 and x == x1: validMonth = 1 validYear = 2024 ...
The main task of the code is to backfill historical data into a system by iterating backward in time (6 minutes per step) for 10 iterations. It processes tags in batches, deletes existing data from Kairos, and exchanges new data using `dataExachangeTbwes`, adjusting timestamps and validating time ranges. The goal is to...
def mainFuncTbwesBackFill(self,unitsId,client,destUnitId): print("Back filling") self.destUnitId = destUnitId currentTimeStamp = int(time.time()*1000) currentTime = datetime.datetime(2024, 5, 7,11,28,00) - datetime.timedelta(hours = 5,minutes=30) currentTime = datetime...
def getTagmeta(self,unitsId): query = {"unitsId":unitsId} url = config["api"]["meta"] + '/tagmeta?filter={"where":' + json.dumps(query) + '}' print(url) # response = requests.get(url,headers={"Authorization": self.token}) response = requests.get(url) if(response.status_co...
The function `mainFuncPower` generates a time frame for power data exchange between source and destination units. It calculates adjusted start/end timestamps, retrieves tag metadata, and triggers data transfer via `dataExachangePower` based on timestamp validity. It also updates Redis with the last update value for the...
def mainFuncPower(self,sourceUnitId,destUnitId,client,sourcePrefix,destPrefix): try: self.sourceUnitId = sourceUnitId self.destUnitId = destUnitId self.sourcePrefix = sourcePrefix self.destPrefix = destPrefix currentTimeStamp = self.now = int(time.tim...
def getTagmeta(self,unitsId): query = {"unitsId":unitsId} url = config["api"]["meta"] + '/tagmeta?filter={"where":' + json.dumps(query) + '}' print(url) # response = requests.get(url,headers={"Authorization": self.token}) response = requests.get(url) if(response.status_co...
The main task of the code is to execute data exchange between source and destination units over a dynamically calculated time frame. It generates start/end timestamps, handles date parsing errors, retrieves data tags, and invokes data transfer with adjusted time ranges if needed. The function manages time logic, timest...
def mainFuncETP(self,sourceUnitId,destUnitId,client,sourcePrefix,destPrefix): try: self.sourceUnitId = sourceUnitId self.destUnitId = destUnitId self.sourcePrefix = sourcePrefix self.destPrefix = destPrefix currentTimeStamp = self.now = int(time.time(...
def getTagmeta(self,unitsId): query = {"unitsId":unitsId} url = config["api"]["meta"] + '/tagmeta?filter={"where":' + json.dumps(query) + '}' print(url) # response = requests.get(url,headers={"Authorization": self.token}) response = requests.get(url) if(response.status_co...
The main task of the code is to generate a time frame for data exchange between source and destination units by manipulating current timestamps, adjusting dates and times dynamically, retrieving tag metadata, and invoking data transfer functions with calculated start/end timestamps. It handles edge cases for date forma...
def mainFuncWRS(self,sourceUnitId,destUnitId,client,sourcePrefix,destPrefix): try: self.sourceUnitId = sourceUnitId self.destUnitId = destUnitId self.sourcePrefix = sourcePrefix self.destPrefix = destPrefix currentTimeStamp = self.now = int(time.time(...
def create_unpack_parameters(subparsers): unpack_parser = subparsers.add_parser('unpack', description='Unpacks zip resources to projects resources with current ' 'profile', help=...
The code defines a command-line interface to either profile or unpack PNG resources from a ZIP file. It uses argparse to handle subcommands ('profile' and 'unpack'), parsing arguments and executing corresponding functions based on user input. The main task is to distribute PNG resources within a project by unpacking ZI...
def main(): parser = argparse.ArgumentParser( description="Unpacks png resources from zip file and distributes it among your project" ) subparsers = parser.add_subparsers(title='commands', dest="mode") create_unpack_parameters(subparsers) create_profile_parameters(subparsers) args, _ ...
def preprocess_file(data_path, track_number): # Read dataset tracks_csv = track_number+"_tracks.csv" meta_csv = track_number+"_tracksMeta.csv" df = pd.read_csv(data_path+tracks_csv, sep=',') df_meta = pd.read_csv(data_path+meta_csv, sep=',') # Concat meta + tracks df_meta = df_meta['class...
The main task of the code is to preprocess multiple files by concatenating their data, generating synthetic IDs, filtering relevant features, standardizing columns, and saving the processed dataset as a joblib file with a specified split name. It aggregates data from input files, applies transformations, and stores the...
def create_split(files, split_name, reload_scaler): data = pd.DataFrame() for f in files: df = preprocess_file(data_path, f) data = pd.concat([data, df], ignore_index=True) print(f"{f} file preprocessed ...") # Create a unique id for the .csv data = create_synthetic_id(data) ...
def _fetch_moderators(client, subreddit): """Fetch and save the moderators for the subreddit.""" mods = [ get_or_create_user(mod.name) for mod in client.subreddit(subreddit.name).moderator()] subreddit.moderators = mods def _fetch_posts(client, subreddit): """Fetch all posts from today a...
The main task of the code is to fetch Reddit data by iterating over subreddits, retrieving moderators, posts, and their associated comments using a Reddit API client. It aggregates this data for each subreddit through helper functions, likely for analysis, storage, or processing.
def fetch_data(): client = reddit() for subreddit in Subreddit.objects.iterator(): _fetch_moderators(client, subreddit) for post, api_post in _fetch_posts(client, subreddit): _fetch_comments(post, api_post)
def _update_args(self, args): utils.set_matching_attr_of_object(self, args) def _stop_capture(self): self.cap.release() self.cap = None def _process_video(self): self.cap = cv2.VideoCapture(self.INPUT_FILE) success, image = self.cap.read() count = 0 max_count = in...
The main task of the code is to initialize and manage video processing by updating arguments, stopping existing capture, setting preview mode, initializing tracking data structures, processing the video, and saving notes if not in preview mode. It handles video capture setup, state management, and result storage based ...
def start(self, args, preview=False): self._update_args(args) if self.cap: self._stop_capture() self.preview = preview self.notes = [] self.tracked_keys = {} self._process_video() if not preview: self._save_notes()
def _update_args(self, args): utils.set_matching_attr_of_object(self, args) def start(self, args, preview=False): self._update_args(args) if self.cap: self._stop_capture() self.preview = preview self.notes = [] self.tracked_keys = {} self._process_vide...
The main task of the code is to either start a video preview or capture a series of frames for previewing. It updates arguments, initializes the video capture if not already active, reads up to PREVIEW_STEP_SIZE frames, handles capture failures by stopping, and processes the final frame for tracking notes and preview d...
def preview_step(self, args): self._update_args(args) if not self.cap: self.start(args, preview=True) return image = None for i in range(self.PREVIEW_STEP_SIZE): success, image = self.cap.read() if not success: self._stop_ca...
def Lege(n,x): e=[] if n%2 == 0: #even m=int(n/2) else : #odd m = int((n-1)/2) s = np.arange(0,m+1,1) for i in s: polyn = ( (-1)**i*gamma_(2*n-2*i+1)*(x**(n-2*i)))/(2**n*gamma_(i+1)*gamma_(n-i+1)*gamma_(n-2*i+1)) e.append(polyn) return (sum(e)...
The code validates inputs (x in [-1,1], n≥0), computes Legendre polynomial and its derivative at given x & n using a custom function and an inbuilt function, then prints both results for comparison.
def check(n,x): if x<-1 or x>1 or n<0 : print("Check your values . x should lie in [-1,1] and n>=0") else: print("Legendre polynomial & its derivative value at given x & n using my function = ",(Lege(n,x),DLege(n,x))) print("Legendre polynomial & its derivative value at given x & n usi...
def _validate_args(f, type_hints): all_vars = set(f.__code__.co_varnames).difference(set(["self", "f"])) if not set(type_hints.keys()).difference(all_vars) == set(): raise Exception("Please provide type hints for all variables") def _set_args( arg_to_generator_map, type_hints, generators, ...
The code defines a wrapper function that validates function arguments using type hints, maps parameters to generators, and drives test execution. It processes input parameters, checks type annotations, configures argument generators, and initiates test runs with specified constraints and hypotheses, likely for property...
def wrapper(*args, **kwargs): self_ref = None if len(args) > 0: self_ref = args[0] type_hints = typing.get_type_hints(f) if "return" in type_hints: del type_hints["return"] _validate_args(f, type_hints) arg_to_generator_map = {} _set_arg...
def start_conversing(self): Thread(target=self.receive).start() self.send() def Join_room(self): self.server.send(b"0x01234") # Requests all rooms from client msg = self.server.recv(1024).decode("utf-8") # Recives either a either a number of bits or the rooms names code = str(msg...
The main task of the code is to display a persistent main menu with options for handling messages, changing rooms, and modifying the user's name. It continuously prompts the user for input, clears the screen, and executes corresponding methods based on their selection, enabling interactive navigation within an applicat...
def main_menu(self): while True: options = input(f"Main Menu: \n1. Messages \n2. Change Room (Current: {self.current_room}) \n3. Change Name (Current: {self.name}) \n") os.system("cls") if options == "1": self.start_conversing() elif options == "2"...
def getTop3DPS(): sortedDPS = getTopDPS() #for i in range(0, 2): # top3DPS.append(str(i+1) +") "+ str(sortedDPS[i][0].capitalize())) top3DPSMsg = "" for i in range(0, 3): top3DPSMsg = top3DPSMsg + str(i+1) + ") "+ str(sortedDPS[i][0].capitalize()) + "\n" return top3DPSMsg def ...
The main task of the code is to generate a Discord embed displaying a player's profile, including their rank, level, and top 3 characters in DPS, Tank, and Support roles, along with icons. It aggregates data from helper functions, structures it into a formatted message, and returns the embed for display.
def sendOverall(): top3DPS = getTop3DPS() top3Tanks = getTop3Tanks() top3Support = getTop3Support() #have 9 characters to display playerRank = getRank() playerLevel = getLevel() playerName = getName() playerIcon = getUserIcon() playerRankIcon = getRankIcon() #*, name, value,...
def is_done(self): return self.game_status() != 'nothing' def get_legal_actions(state, player): state = np.array(json.loads(state)) actions = [] for xpos in range(state.shape[0]): for ypos in range(state.shape[1]): if state[xpos][ypos] == '.': actions.append(json....
The code processes a player's action in a game by validating the move, updating the game field, determining the game status, assigning a reward if a winner is detected, and returning the updated game state, reward, and completion status.
def step(self, action): assert not self.is_done() player, xpos, ypos = json.loads(action) assert action in get_legal_actions(self._str_field, player) self._field[xpos][ypos] = player status = self.game_status() done = self.is_done() if status == 'winner': ...
def get_qvalue(self, state, action): return self._qvalues[state][action] def get_value(self, state): possible_actions = self.get_legal_actions(state) #If there are no legal actions, return 0.0 if len(possible_actions) == 0: return 0.0 best_action = self.get_best_act...
This code updates the Q-value for a given state-action pair using the Q-learning algorithm. It applies the learning rate (alpha) and discount factor (gamma) to adjust the Q-value based on the received reward and the estimated value of the next state. The formula combines the current Q-value with a weighted sum of the i...
def update(self, state, action, reward, next_state): """ Q(s,a) := (1 - alpha) * Q(s,a) + alpha * (r + gamma * V(s')) """ #agent parameters gamma = self.discount learning_rate = self.alpha new_q = (1 - learning_rate) * self.get_qvalue(state, action) + learning_r...
def backup_chat(conf, chat, name=None, prompt_name=None): if len(chat) == 0: return # Always backup chat first, even if we are prompting for a name with ensure_extension(conf.chat_backup_file, ".json").open("w") as f: json.dump(chat, f, indent=4) if prompt_name: try: ...
The main task of the code is to edit a chat history by processing user input, updating the chat with new metadata, executing a command, parsing its output, and reconstructing the chat with updated content and metadata. It backs up the original chat, writes temporary metadata/content to a file, runs the command, reads t...
def edit_chat(conf, chat, user_input): backup_chat(conf, chat) meta_data_prefix = f"###>>>" with (conf.chat_dir / 'temp').open("w") as f: for m in chat: meta_data = json.dumps({k: v for k, v in m.items() if k != 'content'}) f.write(f"{meta_data_prefix}{meta_data}\n{m['content...
def greedy(points): dist=distance_matrix(points) no_of_cities=len(points) min_path=sys.maxsize sol=[] for i in range(no_of_cities): start=i path_length=0 visited=[] visited.append(start) counter=1 #print(counter) #print(dist[start]) #pr...
The code solves the Traveling Salesman Problem (TSP) by parsing input data, applying a greedy algorithm with 2-opt improvement for smaller instances (under 500 nodes), and using random sampling for larger instances (over 1500 nodes), returning the tour length and node order. Your return
def solve_it(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') nodeCount = int(lines[0]) points = [] for i in range(1, nodeCount+1): line = lines[i] parts = line.split() points.append(Point(float(parts[0...
def CreateNewPopulation(size,citySize,points): population = [] for x in range(size): newGenome = Genome() newGenome.chromosomes = random.sample(range(0, citySize), citySize) #newGenome.chromosomes.insert(0, 0) f_city=newGenome.chromosomes[0] newGenome.chromosomes.append(f...
The code implements a Genetic Algorithm (GA) to solve the Traveling Salesman Problem (TSP). It evolves a population of potential paths (chromosomes) over generations, using reproduction (crossover) to generate offspring and pruning weak individuals based on fitness thresholds. The algorithm tracks the best solution's f...
def GA_TSP(points,popSize,maxGeneration): allBestFitness = [] citySize=len(points) population = CreateNewPopulation(popSize,citySize,points) generation = 0 if citySize<100: WEAKNESS_THRESHOLD = 800 elif citySize<200: WEAKNESS_THRESHOLD = 30000 elif citySize<300: WEAKN...
def RegularPfc(N,L,m): Nl=int(np.sqrt(N)) grid=np.zeros((m,N,2)) tempgrid=np.zeros((N,2)) for i in range(Nl): for j in range(Nl): tempgrid[i+Nl*j][0]=i*float(L)/float(Nl) tempgrid[i+Nl*j][1]=j*float(L)/float(Nl) for j in range(m): ...
The code runs simulations to compute and save retrieval overlaps in a neural network model. It iterates over varying parameters (m, gamma) and multiple samples, generating grid structures, interaction matrices (J), and final states (Vfinal). Overlaps between these states and the original grid are calculated and stored ...
def main(): SimulationName="L10" nl=40 N=nl*nl ms=np.linspace(2,30,15) gammas=np.linspace(0,2,11) samples=10 #iterations for each gamma and m L=10.0 f=0.03 #CREATE SIMULATION FOLDER if not os.path.exists(SimulationName): os.makedirs(SimulationName) ...
def findutilde(g): x=1.0/(2.0*g) utilde=norm.ppf(x) return utilde def samesign(a, b): return a * b > 0 def U1(x,g,w): return 2*g*N(x)-x+w
The code performs a root-finding algorithm using a modified binary search to locate the maximum of a utility function U1. It iteratively adjusts bounds (low, high) to ensure a sign change in U1, then narrows the interval until the function's value at the midpoint falls below a specified precision threshold, returning t...
def findumax(g,w,precision): low=-100 high=findutilde(g) while samesign(U1(low,g,w), U1(high,g,w)): low=2*low converged=False while not converged: midpoint = (low + high) / 2.0 if samesign(U1(low,g,w),U1(midpoint,g,w)): low = midpoint else: ...
def findutilde(g): x=1.0/(2.0*g) utilde=norm.ppf(x) return utilde def samesign(a, b): return a * b > 0 def U1(x,g,w): return 2*g*N(x)-x+w
This function uses a modified bisection method to find the root of the function U1(g, w, x) by iteratively narrowing an interval [low, high] where the sign of U1 changes. It first expands the lower bound until a sign change is detected, then converges by halving the interval until the function value at the midpoint fal...
def findmin(g,w,precision): low=findutilde(g) high=100 while samesign(U1(low,g,w), U1(high,g,w)): low=2*low converged=False while not converged: midpoint = (low + high) / 2.0 if samesign(U1(low,g,w),U1(midpoint,g,w)): low = midpoint else: hi...
def findutilde(g): x=1.0/(2.0*g) utilde=norm.ppf(x) return utilde def findumax(g,w,precision): low=-100 high=findutilde(g) while samesign(U1(low,g,w), U1(high,g,w)): low=2*low converged=False while not converged: midpoint = (low + high) / 2.0 if samesign(U1(low...
This code performs a binary search to find the value of 'u' (midpoint) where the function U(u, g, w) equals a target value y, calculated from umax. It first expands the search range exponentially and then narrows it using binary search until the difference between U(midpoint) and y is below the specified precision. The...
def findustar(g,w,precision): low=findutilde(g) high=100 umax=findumax(g,w,precision) y=U(umax,g,w) while samesign(U(low,g,w)-y, U(high,g,w)-y): high=2*high converged=False while not converged: midpoint = (low + high) / 2.0 if samesign(U(low,g,w)-y, U(midpoint,g,w)...