dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def initialize_parameters(features): w=np.zeros((1,features)) b=0 return w,b def hypothesis(X,w,b): Z=np.dot(w,X)+b return Z def activation(Z): return sigmoid(Z) def gradient_descent(X,Y,Z,A,w,b): #number of samples m=X.shape[1] Y=Y.reshape(A.shape) #this dL/dA where L is the cost function dA= -(np.divide(Y...
The code implements logistic regression training using gradient descent. It initializes parameters, iteratively computes predictions, gradients, and updates weights/bias with a decaying learning rate. Costs are recorded every 100 iterations and returned alongside optimized parameters.
def logistic_regression(X,Y,learning_rate=0.05,num_iterations=1000): #number of features n=X.shape[0] #number of samples m=X.shape[1] w,b=initialize_parameters(n) costs=[] for i in range(num_iterations): Z=hypothesis(X,w,b) A=activation(Z) dw,db=gradient_descent(X,Y,Z,A,w,b) w,b=update_parameters(dw,d...
def load_wine_dataset(filename): df=pd.read_csv(filename) np.random.seed(5) random_no=np.random.randint(df.shape[0]-20) test_data= df[random_no:random_no+20] train_data=df.drop(range(random_no,random_no+20)) train_output=train_data['quality'] train_output=train_output.replace("bad",0) train_output=train_outpu...
The main task of the code is to perform logistic regression on different datasets (wine, heart, or boolean). It loads and preprocesses the dataset, normalizes features, trains a logistic regression model using specified hyperparameters (learning rate, iterations), evaluates model performance on training/test data, and ...
def main(dataset,hyperparameters): learning_rate,num_iterations = hyperparameters if dataset=="wine.csv": X_train,Y_train,X_test,Y_test = load_wine_dataset(dataset) last = "quality" test_data = X_test elif dataset=="heart.csv": X_train,Y_train,X_test,Y_test= load_heart_dataset(dataset) last = "target" ...
def initialize_parameters(layers): np.random.seed(2) parameters={} m=len(layers) for l in range(1,m): parameters["w"+str(l)]=np.random.randn(layers[l],layers[l-1])/(np.sqrt(layers[l-1])) #0.01 parameters["b"+str(l)]=np.zeros((layers[l],1)) return parameters def forward_propagation_m...
This function trains a deep neural network by iteratively performing forward and backward propagation. It initializes parameters, computes costs during training (printed every 100 iterations, stored every 50), updates parameters via backpropagation with a decaying learning rate, and returns the optimized parameters and...
def deep_neural_network(layers,learning_rate,num_iterations,X,Y,input_activation="relu",output_activation="sigmoid"): parameters=initialize_parameters(layers) assert(parameters!=None) costs=[] for i in range(num_iterations): A,forward_backups,backward_backups=forward_propagation_model(X,par...
def load_cat_noncat_dataset(): f1="test_catvnoncat.h5" f2="train_catvnoncat.h5" #X_test=Y_test=X_train=Y_train=np.empty(1) with h5py.File(f1,"r") as test: X_test=np.array(test["test_set_x"][:]) Y_test=np.array(test["test_set_y"][:]) test_classes=test["list_classes"][:] ...
The code trains a deep neural network (DNN) on various datasets (e.g., cat/non-cat, wine, heart, cat/dog, boolean) using specified hyperparameters (layers, learning rate, iterations). It loads and preprocesses the dataset (normalization, reshaping), initializes a DNN with ReLU activation and sigmoid output, trains the ...
def main(dataset,hyperparameters): layers,learning_rate,iterations = hyperparameters #deep neural network for can vs non cat classification if dataset=="catvnoncat": X_train_orig,Y_train_orig,X_test_orig,Y_test_orig=load_cat_noncat_dataset() test_data = X_test_orig last = "catego...
def request_order(payload={}): order_request = send_signed_request('POST', '/api/v3/order', payload) try: now = convert_time(time.time()) logger.info( f"Creating {payload['symbol'].upper()} {payload['type'].replace('_', ' ')} {payload['side'].upper()} order at {now} ({normalize_time(...
The main task of the code is to execute a market buy order for a specified trading symbol, recording the trade details in a log file. It determines the desired quantity, sends the buy request, handles potential errors (e.g., missing order ID), and returns the order ID along with the calculated profit quantity. The func...
def buy_trade(symbol: str, quote_quantity: float = 0, quantity: float = 0): desired_quantity = get_desired_quantity( symbol=symbol, set_price=quote_quantity) if (not quantity) else quantity buy_payload = { 'symbol': symbol, 'side': 'BUY', 'type': 'MA...
def request_order(payload={}): order_request = send_signed_request('POST', '/api/v3/order', payload) try: now = convert_time(time.time()) logger.info( f"Creating {payload['symbol'].upper()} {payload['type'].replace('_', ' ')} {payload['side'].upper()} order at {now} ({normalize_time(...
The function `sell_trade` executes a market sell order for a given symbol, determining the quantity either directly or via a helper function. It logs the trade details, handles potential errors, and returns the order ID and calculated profit quantity.
def sell_trade(symbol: str, quote_quantity: float = 0, quantity: float = 0): desired_quantity = quantity if (not quote_quantity) else \ get_desired_quantity(symbol=symbol, set_price=quote_quantity) sell_payload = { 'symbol': symbol, 'side': 'SELL', 'type': '...
def get_current_price(symbol): response = send_public_request('/api/v3/ticker/price', {"symbol": symbol}) try: current_price = float(response["price"]) except KeyError: logger.warning( f"Key Error: Could not retrieve current price. Retrying in 60s.\n{pformat(response)}") ...
The main task of the code is to validate if a desired trade quantity is affordable based on the account balance. It calculates the required payment, checks against the available balance, logs an error if insufficient funds exist, and returns a validated quantity if sufficient. If funds are insufficient, it returns -1.
def get_hardcoded_quantity(symbol, trade_quote_qty): price = float(get_current_price(symbol=symbol)) payment_symbol = get_payment_symbol(symbol) payment = float(account_info([payment_symbol])[payment_symbol]) if trade_quote_qty > payment: logger.error( f"ERROR {symbol} Desired quote ...
def greedy_cycle(data, node_index: int, weight: float = 1): distances = calculate_cost(data) visited, edges = [], [] limit = len(data) // 2 cost = data[node_index][-1] all_nodes = set(range(len(data))) value = cost edges.append([node_index, node_index]) visited.append(node_index) whi...
This function performs a local search using a steepest descent heuristic to optimize a path's order by iteratively evaluating neighborhood moves (swaps, reversals) and selecting the best improvement in terms of distance reduction, aiming to minimize the total travel cost in a combinatorial optimization problem like the...
def local_search_steepest_heuristic(data, distances, i): _, path = greedy_cycle(data, i, weight=0.5) order = create_order(extract_path(data,path)) best_score = 1 while best_score: neighborhood = create_neighborhood(order, len(data)) best_move = None best_score = 0 for mov...
def greedy_cycle(data, node_index: int, weight: float = 1): distances = calculate_cost(data) visited, edges = [], [] limit = len(data) // 2 cost = data[node_index][-1] all_nodes = set(range(len(data))) value = cost edges.append([node_index, node_index]) visited.append(node_index) whi...
This function performs a greedy local search on a path to minimize travel distance. It starts with a greedy cycle solution, then iteratively applies random neighborhood moves (swaps, reversals) to improve the path. Each move is evaluated by comparing old and new total distances, applying changes if they reduce the cost...
def local_search_greedy_heuristic(data, distances, i: int): _, path = greedy_cycle(data, i, weight=0.5) order = create_order(extract_path(data,path)) change = True while change: change = False neighborhood = create_neighborhood(order, len(data)) for move in random.sample(neighbor...
def init(depth): """ Write the depth and set up the turtle so it is at the initial state. :param depth: the detail of the shape to draw :pre turtle is at the center, down and facing east :post turtle is at the center, down and facing east """ turtle.pensize(4) turtle.speed(1) turtle....
The main task of the code is to prompt the user for a depth value, initialize a drawing environment, and render a specific fractal pattern using a depth-dependent drawing function. The program restricts depth inputs to 1-4, each triggering a unique recursive shape-drawing routine (draw_shapes_1 to draw_shapes_4) with a...
def main(): """ The main program prompts for the depth and then calls the appropriate top level function to draw the image. """ depth = int(input('Enter depth: ')) init(depth) # can only handle depths 1-4 if depth == 1: draw_shapes_1(200) elif depth == 2: draw_shapes...
def isName(self): return True if self.name is not None else False def search_novel(self, name): link = self.get_royalroad_link() + '/fictions/search?title=' link += name.replace(' ', '+') page = self.init_request(link) return self.get_novel_url_and_name(page) def isURL(self): ...
The main task of the code is to retrieve and verify novel information by checking existing data, searching by name if needed, or fetching details from a URL. It ensures required fields (name/URL) are present, handles missing data gracefully, and returns the novel info dictionary or None if retrieval fails.
def get_novel_info(self): if self.novel_info: # If dict has something, return it (assuming it's already filled with the right entries) return self.novel_info if not self.novel_info and (self.isName() or self.url is None): print(f"You haven't provided the following: {'a n...
def setDesktopSource(self, api): self.searchURL = self.URL_ANIMETOON_SEARCH if api == self.API_ANIMETOON else self.URL_ANIMEPLUS_SEARCH self.session.headers.pop('App-LandingPage', None) # Delete these app header items, just for safety. self.session.headers.pop('App-Name', None) self.sess...
The code performs a website search for entries matching the input text, handles pagination to retrieve all results, extracts entry IDs, titles, and descriptions from HTML elements, and returns them as a tuple.
def nameSearchEntries(self, api, text): ''' This name search is done with their own website search. :returns: A string with a comma-separated list entry IDs found in the search. ''' self.setDesktopSource(api) # Desktop browser spoofing. self.delayBegin() r = self....
def build(self): self.current_time = 0 self.tugboat_state = 3 self.tugboat_scort = False self.dock_avaliability = [0 for i in range (0,self.dock_count)] self.docked_ships = [0 for i in range (0,self.dock_count)] self.docked_times = [0 for i in range (0,s...
The code's main task is to execute a simulation for a specified duration (default 10,000 units), initializing the environment, scheduling ship arrival events, and processing them through a main loop to model dynamic system behavior over time.
def run (self, time = 10000): self.build() self.time_lapse = time self.generate_ship_arrival_events() self.main_loop()
def process_image(pathogen, color, input_dir, output_dir): input_image_path = join(input_dir, pathogen["image"]["file"]) output_image_path = join(output_dir, "pathogens", pathogen["name"], "image.png") image_url = posixpath.join("pathogens", pathogen["name"], "image.png") image = Image.open(input_image...
The main task of this code is to process a pathogen's data by generating a color-coded image, analyzing its CSV dataset to extract temporal ranges, geographical regions, countries, and variants, and saving structured metadata (including dates, counts, and visual assets) into JSON files within a specified output directo...
def process_one_pathogen(pathogen: dict, input_dir: str, output_dir: str): color = colorhash(pathogen["name"], reverse=True, prefix="321") image_url = process_image(pathogen, color, input_dir, output_dir) l.info(f"Processing {pathogen['name']}") min_date = '' max_date = '' n_regions = 0 n_...
def json_read(filepath: str): with open(filepath, "r") as f: return json.load(f) def process_one_pathogen(pathogen: dict, input_dir: str, output_dir: str): color = colorhash(pathogen["name"], reverse=True, prefix="321") image_url = process_image(pathogen, color, input_dir, output_dir) l.info(f"...
The main task of the code is to process pathogen data from a JSON file, generate structured web-compatible output files (index.json, global_geography.json), and update internationalization keys. It filters visible pathogens, extracts regions/countries, creates metadata with timestamps, maps country codes to names, and ...
def main(): parser = argparse.ArgumentParser() parser.add_argument("--input-pathogens-json", type=str, help="Path to pathogens.json file containing a list of pathogen descriptions") parser.add_argument("--output-dir", type=str, help="Path to directory to output data in web format") ...
def initializeCheckoutWindow(self): """ Initializes the checkout window with necessary components. This method sets up various components of the checkout window, such as combo boxes, line edits, buttons, and table widget, and connects them to their respective event handlers. Ar...
This code initializes a GUI application by loading the 'easy-cheese.ui' interface and setting up core components like checkout, inventory, product tables, customer management, manager functions, login system, and invoice tracking. It prepares the application's structure and functionality through multiple initialization...
def __init__(self): super().__init__() uic.loadUi('easy-cheese.ui', self) self.initializeCheckoutWindow() self.initializeInventory() self.initializeAllProductsTable() self.initializeCustomers() self.initializeManager() self.intializeLogin() self.in...
def check_target_dir(self): if not os.path.exists(self.ROOT_FILE_PATH): os.makedirs(self.ROOT_FILE_PATH, mode=0o777) os.chdir(self.ROOT_FILE_PATH) def pull_repo(self): folder_name = self.FOLDER_WS_PATH.split("/")[-1] gtoken = b64decode(self.GITLAB_TOKEN).decode("utf-8") repo_url_wtoken = f"//g...
The code performs Git operations: checks target directory, pulls repository, switches to a branch, creates a new branch, lists branches, updates workspace status, and removes specified folders to clean the workspace.
def action_branch(self): self.check_target_dir() self.pull_repo() self.checkout_branch() ###### self.create_branch() self.list_branches() print("Updated workspace", end='\x1b \r') rmtree(self.ROOT_FILE_PATH) print("Removed Folders", end='\x1b \r')
def action_commit(self): self.check_target_dir() self.pull_repo() if self.parse_current_branch(): self.checkout_branch() self.pull_from_workspace() self.check_gitignore() self.commit_push() self.list_branches() rmtree(self.ROOT_FILE_PATH) def action_status(self): self.c...
The `run` method executes different Git-related actions based on the `self.action` value, dispatching to methods like `action_commit`, `action_status`, etc., for tasks such as committing changes, checking status, pulling updates, creating branches, or switching branches. It returns `self` to allow method chaining or fu...
def run(self): if self.action == "commit": self.action_commit() elif self.action == "status": self.action_status() elif self.action == "pull": self.action_pull() elif self.action == "new branch": self.action_branch() elif self.action == "change branch": self.action_chec...
def move_tray_state_five(self): """[Move tray to state five] """ self.sendMessage("1150000") self.ser.reset_input_buffer() waiting_for_finish = self.messageRecieved() while not waiting_for_finish: return_data = self.readMessage() waiting_for_finish...
This function executes a sequential state machine to move a tray through predefined positions (states 5 to 1) with pauses, opens the tray at each step, resets the tray, increments a counter, and marks the tray as ready. It uses serial communication, sleep intervals, and status updates to control mechanical movements, l...
def state_machine_two(self): """[State machine from left to right side] """ print(colored("State machine 2", "red")) self.ser.reset_input_buffer() self.move_tray_state_five() time.sleep(0.1) self.open_tray() time.sleep(0.1) self.move_tray_state_fou...
def move_tray_state_one(self): """[Move tray to state one] """ self.sendMessage("1110000") self.ser.reset_input_buffer() waiting_for_finish = self.messageRecieved() while not waiting_for_finish: return_data = self.readMessage() waiting_for_finish =...
This code implements a state machine to control a tray's movement from right to left through predefined states (1–5), opening the tray after each step. It resets serial input, executes sequential motion commands, waits between actions, transitions to restocking, pauses for 10 seconds, increments a counter, and marks th...
def state_machine(self): """[State machine from right to left side] """ print(colored("State machine 2", "green")) self.ser.reset_input_buffer() self.move_tray_state_one() time.sleep(0.1) self.open_tray() time.sleep(0.1) self.move_tray_state_two() ...
def move_tray_state_five(self): """[Move tray to state five] """ if DEBUG: print("state five") else: pass self.sendMessage("1150000") self.ser.reset_input_buffer() waiting_for_finish = self.messageRecieved() while not waiting_for_fi...
The main task of the code is to execute a predefined sequence of tray movements and openings in a state machine. It resets the serial input buffer, sequentially moves the tray through states 5 to 1 with 0.1s delays between each action, and opens the tray after each movement, concluding with an initialization move. This...
def state_machine_two(self): """[State machine from left to right side] """ print(colored("State machine 2", "red")) self.ser.reset_input_buffer() self.move_tray_state_five() time.sleep(0.1) self.open_tray() time.sleep(0.1) self.move_tray_state_fou...
def move_tray_state_one(self): """[Move tray to state one] """ if DEBUG: print("state one") else: pass self.sendMessage("1110000") self.ser.reset_input_buffer() waiting_for_finish = self.messageRecieved() while not waiting_for_finis...
This function orchestrates a state machine to control a tray's movement from right to left through predefined states. It sequentially calls methods to move the tray to specific positions (state one to five), opens the tray after each movement with delays, and finally moves it to a restock position, likely for automated...
def state_machine(self): """[State machine from right to left side] """ print(colored("State machine 1", "green")) self.ser.reset_input_buffer() self.move_tray_state_one() time.sleep(0.1) self.open_tray() time.sleep(0.1) self.move_tray_state_two() ...
def createCSV(filename): global csv_file, writer try: csv_file = open(f"{filename}.csv", "w", newline='') writer = csv.writer(csv_file) except Exception as e: sys.exit(f"Error: {e}") def writeQeexoV2CSV(args, data, meta_data): interval = args.interval normalize = args.normal...
The main task of the code is to convert SDS sensor data into a specified output format (CSV or WAV) using YAML metadata. It parses command-line arguments for input files, processes sensor data, and generates formatted output files, with options for timestamp normalization and data segmentation.
def main(): formatter = lambda prog: argparse.HelpFormatter(prog,max_help_position=60) parser = argparse.ArgumentParser(description="Convert SDS data to selected format", formatter_class=formatter) required = parser.add_argument_group("required") required.add_argume...
def getMarketPrice(self): return self.prices['Price'][self.time] def tryToBuy(self, percentageDiff): if percentageDiff >= self.UPWARD_TREND_THRESHOLD or percentageDiff <= self.DIP_THRESHOLD: self.lastOpPrice = self.placeBuyOrder() self.nextOperationBuy = False print("...
The code calculates the percentage difference between the current market price and the last operation's price. Based on the `nextOperationBuy` flag, it either attempts to buy or sell, using the calculated percentage difference to inform the trade decision. The main task is to determine and execute a buy/sell action bas...
def attemptToMakeTrade(self): currentPrice = self.getMarketPrice() percentageDiff = (currentPrice - self.lastOpPrice)/self.lastOpPrice*100 if self.nextOperationBuy: self.tryToBuy(percentageDiff) else: self.tryToSell(percentageDiff)
def find_user(hash, id): if not is_valid_key(cache[hash]['main'], id): return {'code':500} cache[hash]['time'] = time.time() data = decrypt_data_fast(cache[hash]['main'],id) if data[0] == None: return {'code':500} return {'code':200, 'data':data} def is_json_serialized(obj): try:...
The function saves user data by validating input, processing JSON, updating location information, and modifying user records. It checks for cache user existence, ensures data is JSON-serializable, verifies location input, and updates user details. Errors return specific codes (423, 420, 417) for invalid states, while s...
def save_data(data): user_from_cache = find_user(data['hash'], data['id']) if user_from_cache['code'] == 500: return {'code':423} if not is_json_serialized(data['data']): return {'code':420, 'data':data['data'], 'error':'Object is not json serialized'} data_from_request = json.loads(data...
def find_user(hash, id): if not is_valid_key(cache[hash]['main'], id): return {'code':500} cache[hash]['time'] = time.time() data = decrypt_data_fast(cache[hash]['main'],id) if data[0] == None: return {'code':500} return {'code':200, 'data':data} def update_user(hash, id, dbdat): ...
The main task of the code is to delete or update user data based on a provided hash and ID. It checks if the user exists, handles empty location data by replacing a data element, or deletes a specified location from the user's data structure and updates the user entry accordingly, returning success or lock codes depend...
def delete_data(data): user_from_cache = find_user(data['hash'], data['id']) if user_from_cache['code'] == 500: return {'code':423} if data['location'] == '': update_user(data['hash'], data['id'], [{}, user_from_cache['data'][1]]) return {'code':200} delete_location(user_from_cac...
def find_user(hash, id): if not is_valid_key(cache[hash]['main'], id): return {'code':500} cache[hash]['time'] = time.time() data = decrypt_data_fast(cache[hash]['main'],id) if data[0] == None: return {'code':500} return {'code':200, 'data':data} def verify_password_hash(hash, passwo...
The code logs out a user by verifying their credentials, encrypting their data, and updating the database. It checks if the user exists, validates the password, encrypts the user's data with an IV, stores the IV in a cache, updates the encrypted data in the database, and clears the user's session data. The function ret...
def log_out(database, data): user_from_cache = find_user(data['hash'], data['id']) if user_from_cache['code'] == 500: return {'code':200} user_from_database = database['conn'].execute(database['users'].select().where(database['users'].c.username == user_from_cache['data'][1][0])).fetchone() if n...
def find_user(hash, id): if not is_valid_key(cache[hash]['main'], id): return {'code':500} cache[hash]['time'] = time.time() data = decrypt_data_fast(cache[hash]['main'],id) if data[0] == None: return {'code':500} return {'code':200, 'data':data} def verify_password_hash(hash, passwo...
The main task of the code is to remove a user account from a database after verifying the user's credentials through cached data and database queries. It checks for user existence, validates the password hash, deletes the user record, updates cached data, and removes associated entries from a dictionary. The function r...
def remove_account(database, data): user_from_cache = find_user(data['hash'], data['id']) if user_from_cache['code'] == 500: return{'code':423} user_from_database = database['conn'].execute(database['users'].select().where(database['users'].c.username == user_from_cache['data'][1][0])).fetchone() ...
def verify_password_hash(hash, password): return bcrypt.checkpw(password.encode('utf-8'), bytes.fromhex(hash)) def decrypt_data(data, password, salt, iv): backend = default_backend() kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt.encode(), iterations=100000...
This function authenticates a user by validating the username format, checking database existence, verifying the password, decrypting user data, and updating the user's cached information. It returns specific HTTP status codes (406, 404, 401, 423) for validation errors, missing users, incorrect passwords, or update fai...
def log_in(database, data): if data['username'] == '': return {'code':406} if data['username'].isalnum() == False: return {'code':406} user_from_database = database['conn'].execute(database['users'].select().where(database['users'].c.username == data['username'])).fetchone() if not user_...
def create_session(data): user_hash = add_user(data['id'])['hash'] return {'code':201, 'hash':user_hash} def sign_up(database, data): if data['username'] == '': return {'code':406} if data['username'].isalnum() == False: return {'code':406} user_from_database = database['conn'].execu...
This function routes session operations based on the 'code' value in input data, dispatching to specific handlers like creating sessions, user registration, data management, authentication, and encryption updates. It acts as a dispatcher for session-related tasks, returning appropriate responses or performing database ...
def session(**data): if data['code'] == 301: return create_session(data) elif data['code'] == 302: return sign_up(database, data) elif data['code'] == 303: return save_data(data) elif data['code'] == 304: return delete_data(data) el...
def get_flag_arguments(): global DIR_SOURCE_ARG global NAMES_FILES_TO_PARSE_ARG global ISSUES_ARG parser = argparse.ArgumentParser() parser.add_argument("-d", "--directory", type=str, help="directory in which to parse all files found") parser.add_argument("-f", "--files"...
The main task of the code is to handle log copying and issue extraction from specified log files. It processes command-line arguments, sets source/destination directories, filters relevant log files, applies regex patterns to extract issues, and manages directory cleanup. The routine ensures non-existent files are remo...
def main(): """Routine responsible for handling log copying, issue extraction""" global DIR_DEST global FILES_LOGS_PATHS global NAMES_FILES_TO_PARSE global ISSUES_REGEX get_flag_arguments() _set_source_dir() _set_issue_keywords() _set_files_to_parse() _create_dest_dir(DIR_DEST) ...
def initial_fill(self): for i in range(20): state = self.reset() done = False while not done: # Epsilon greedy action = DQNAgent.get_action(state) next_state, reward, done = self.step(action, 'X') DQNAgent.fill...
This function implements a DQN agent for the 'X' player in a game. It initializes the agent, runs multiple episodes, and in each episode, uses epsilon-greedy policy to select actions, interacts with the environment, stores experiences in a replay memory, and performs learning via batch updates to improve the neural net...
def x_agent(self): self.initial_fill() for episode in range(self.episodes): state = self.reset() done = False while not done: # Epsilon greedy action = DQNAgent.get_action(state) next_state, reward, done = self.step(ac...
def chunk(self, it, size): """List will be chunked into equal size for request Since request size is only 1000 Args: it (list): will be the iterable of the list size (int): describes the number of chunks based on size per chunk Returns: iter : iterable objec...
The main task of the code is to perform miRNA interaction analysis by processing gene lists from various data structures (DataFrame, list, or dict), chunking them, executing searches, applying a threshold for interaction selection, and compiling results into a pandas DataFrame. It validates inputs, handles data formatt...
def run_miRNA_analysis(self, threshold: float = None) -> pd.DataFrame: """_summary_: runs the analysi by adding the miRNAs to the input in the webside and starting the search as well as removing unidentified childs Args: threshold (float, optional): Cutoff to select interactions. De...
def get_user_tokens(session_id): user_tokens = SpotifyToken.objects.filter(user=session_id) print(user_tokens) if user_tokens.exists(): return user_tokens[0] else: return None def get_spotify_id(session_id): endpoint = "" response = execute_spotify_api_request(session_id=session_...
The main task of the code is to create a Spotify playlist with a given name and add songs recommended based on selected mood, energy, and valence parameters. It uses Spotify's API to authenticate, generate a playlist, fetch mood-based song recommendations, extract song IDs, and add them to the playlist.
def add_songs(session_id,pl_name:str, mood:list, energy:float, valence:float): tokens = get_user_tokens(session_id) sp = spotipy.Spotify(auth = tokens) create = sp.user_playlist_create(get_spotify_id(), pl_name) moods = random_selector(list= mood) mood_songs = get_recommendations(mood = moods, e...
def dedup_spaces(text): """ Deduplicate spaces i.e., "the lazy fox jumped" -> "the lazy fox jumped" """ return re.sub(r'[^\S\n]+', ' ', text) def remove_line_break(text, wordset): """ Remove line break i.e., "the lazy\nfox jumped" -> "the lazy fox jumped" """ text = remove_spac...
The main task of the code is to clean text extracted from PDFs by removing trailing whitespace, deduplicating spaces, merging unnecessary line breaks, and combining hyphenated terms into single words using a provided wordset to ensure accurate text normalization and readability.
def clean(text, wordset): """ Clean text copied and pasted from PDFs """ # step 0: remove trailing whitespace text = text.strip() # step 1: clean spaces clean_text = dedup_spaces(text) # step 2: dedup line breaks clean_text = remove_line_break(clean_text, wordset) # step 3: com...
def concat_tile(im_list_2d): return cv2.vconcat([cv2.hconcat(im_list_h) for im_list_h in im_list_2d]) def make_imagename(tile_ids, selected): img_code = repr_tile_ids_selected(tile_ids, selected) return f"cache/m{img_code}.png" def guess_imagename(tile_ids): img_code = repr_array(tile_ids) return f"cache/g{...
The function generates an image by combining tiles from specified IDs, highlights selected tiles with green borders, arranges them into a grid defined by 'shape', saves the composite image with a filename derived from tile IDs and selections, and returns the filename.
def generate_image(tile_ids, shape, selected=None): if selected is None: selected = tuple() tiles = [cv2.imread('tiles/cwt%03d.png' % n) for n in tile_ids] p1, p2 = 1, TILE_WIDTH-2 # if len(selected) == 0: # for i, tile in enumerate(tiles): # cv2.putText(tile, str(i+1), (TILE_WIDTH-25,30), # ...
def bblSort(array): start_time = datetime.now() for i in range(len(array)-1): exchange = False for j in range(len(array) - 1 -i): if array[j] > array[j+1]: exchange = True t = array[j] array[j]=array[j+1] array[j+1] = t ...
Your return The code handles a POST request to execute selected sorting algorithms (Bubble, Selection, Insertion, Merge, Heap, QuickSort variants) on a randomly generated array. It captures user inputs for algorithm choice and array size, applies the chosen sort, measures execution time, and renders the sorted data a...
def index(): data = None qtime = None if request.method == "POST": input1 = request.form['input1'] input2 = request.form['input2'] if input1 and input2: rand_number = lambda x:[random.randint(1,5000) for i in range(x)] array = rand_number(int(input2)) ...
def score_x(self, from_instance, to_instances): return 1 - self.gower_distance(from_instance, to_instances) def score_y(self, predictions_to_calculate): if self._target.target_type() == Target.TYPE_CLASSIFICATION: return self.calculate_classification_score_y(predictions_to_calculate) ...
The function calculates a combined fitness score for counterfactual instances by multiplying three components: (1) closeness to the initial instance (`score_x`), (2) prediction accuracy (`score_y`), and (3) feasibility of the instance (`score_f`). It ensures all scores are non-negative, combines them via multiplication...
def fitness_score(self, instances, predictions): # calculate closeness of the potential counterfactual to the initial instance. score_x = self.score_x(self._initial_instance, instances) score_y = self.score_y(predictions) score_f = self.score_f(instances) assert (score_x >= 0).al...
def read_accounts(): try: with open("accounts.json", "r") as saved_accounts: return json.load(saved_accounts) except FileNotFoundError: return {} except json.decoder.JSONDecodeError: return {} def write_accounts(new_accounts): with open("accounts.json", "w") as saved_...
The code creates a new user account by verifying the username is unique and passwords match. If valid, it saves the account details and switches screens; otherwise, it displays error messages for duplicate usernames or mismatched passwords.
def create_account(): accounts = read_accounts() username = win.getEntry("New Username: ") new_pass = win.getEntry("New Password: ") confirm_pass = win.getEntry("Confirm Password: ") if username not in accounts and new_pass == confirm_pass: win.infoBox("acs", "Account created successfully!")...
def extract_blackhat(image): # Here we want cheque image (h, w,) = image.shape[:2] delta = int(h - (h * 0.15)) bottom = image[delta:h, 0:w] gray = np.copy(bottom) cv2.imwrite('bottom.jpg', gray) blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, rectKernel) return blackhat, gray, delta d...
This code extracts MICR (Magnetic Ink Character Recognition) data from an image, such as bank check numbers. It processes the image to identify and group regions containing MICR characters, isolates individual characters using contour detection, resizes them, and matches them against reference MICR templates via templa...
def extract_micr(image): blackhat, gray, delta = extract_blackhat(image=image) groupLocs = group_locations(image=image) chars = find_ref_micr_data() output = [] # loop over the group locations for (gX, gY, gW, gH) in groupLocs: # initialize the group output of characters groupOut...
def home(self): return self._home def repos(self): gh = github.Github(self._public()) repos = gh.get_user().get_repos() wanted = self._repos() repoList = {} for repo in repos: if (repo.fork): continue if (repo.owner.login != self._account): conti...
The main task of the code is to list tracked repositories by displaying their names, aliases, and SSH URLs with aligned formatting. It navigates to the home directory, retrieves repository data, calculates maximum name length for alignment, and prints each repository's details in a structured, readable format.
def listRepos(self): print(c.g + "Tracked Repositories:", c.reset) self.home().goto() repos = self.repos() mr = self._maxNameLen() for repo in repos.values(): print(repo.name.ljust(mr, ' '), "Alias ->", self.repoBaseName(repo).lju...
def repos(self): gh = github.Github(self._public()) repos = gh.get_user().get_repos() wanted = self._repos() repoList = {} for repo in repos: if (repo.fork): continue if (repo.owner.login != self._account): continue if repo.name in wanted: ...
The main task of the code is to filter repositories by checking if their base name meets a condition via `findOpt`. It collects qualifying repositories into a list and returns it, or `None` if no matches are found.
def _filterClones(self): li = [] cloneList = self.repos() for repo in cloneList.values(): rn = self.repoBaseName(repo) if self.findOpt(rn): li.append(repo) if len(li) > 0: return li else: return None
def home(self): return self._home def cloneList(self): specific = self._filterClones() li = None if specific != None: li = specific else: li = self.repos().values() return li def repoBaseName(self, repo): name = repo.name loc = name...
This method clones multiple repositories from their SSH URLs into a 'repos' directory within the home directory. It navigates to the home, creates the 'repos' folder, iterates through a list of repositories, prints status messages for each, and executes clone commands using the SSH URLs and repository names.
def clone(self): self.home().goto() repos = self.home().create("repos") repos.goto() print("") print(c.y + "Cloning into", c.reset, self.home()) print("") print("") for repo in self.cloneList(): rn = self.repoBaseName(repo) print...
def home(self): return self._home def cloneList(self): specific = self._filterClones() li = None if specific != None: li = specific else: li = self.repos().values() return li def repoBaseName(self, repo): name = repo.name loc = name...
The code clones multiple repositories by iterating through a list, executes a clone command for each, navigates into each cloned repository directory, runs 'git pull' to update the repo, executes a Python script (gitupdate.py), and returns to the main repos directory. The process includes logging steps with colored tex...
def pull(self): self.home().goto() repos = self.home().create("repos") repos.goto() for repo in self.cloneList(): rn = self.repoBaseName(repo) print("") print(c.y + " Pulling repository ", c.g0, repo.ssh_url, c.reset) print("") ...
def clean(self): self.home().goto() print("") print(c.y + "Cleaning repos/ directory", c.reset) self.home().run("ls -x repos") repos = self.home().create("repos") repos.remove() self.home().goto() def home(self): return self._home def cloneList(self): ...
The code synchronizes multiple repositories by cloning them, updating submodules via 'gitupdate.py', committing changes with a predefined message, and pushing updates. It iterates through a list of repositories, clones each, executes updates, and ensures changes are committed and pushed to the remote repository.
def sync(self): self.clean() self.home().goto() repos = self.home().create("repos") repos.goto() for repo in self.cloneList(): rn = self.repoBaseName(repo) repos.run(self.CLONE_CMD % (repo.ssh_url, rn)) rd = repos.subdir(rn).goto() ...
def home(self): return self._home def cloneList(self): specific = self._filterClones() li = None if specific != None: li = specific else: li = self.repos().values() return li def repoBaseName(self, repo): name = repo.name loc = name...
The main task of the code is to automate building multiple repositories by cloning them into a "repos" directory, navigating to each repository's subdirectory, and executing a CMake build command ("cmake --build Build") for each, with progress indicated by printed status messages.
def build(self): self.home().goto() repos = self.home().create("repos") repos.goto() for repo in self.cloneList(): rn = self.repoBaseName(repo) print("") print(c.r + " Building repository ", c.g0, repo.ssh_url, c.reset) print("") ...
def home(self): return self._home def cloneList(self): specific = self._filterClones() li = None if specific != None: li = specific else: li = self.repos().values() return li def repoBaseName(self, repo): name = repo.name loc = name...
This code configures multiple repositories by cloning them into a 'repos' directory, then using CMake to set up each repository's build system with options to enable and automatically run tests. The main task is to automate the configuration and test setup for a list of repositories.
def config(self): self.home().goto() repos = self.home().create("repos") repos.goto() for repo in self.cloneList(): rn = self.repoBaseName(repo) sd = repos.subdir(rn).goto() print("") print(c.r + " Configuring repository ", c.g0, repo.ss...
def update_bvc(x, y, environment): bvc_cartesian_array = np.zeros((BVC_PER_ROW, BVC_PER_COL)) sensory_map = generate_sensory_map(x, y, environment) min_rad, max_rad = 0, int(np.max(sensory_map)) #int(np.min(sensory_map)), int(np.max(sensory_map)) # Range cannot handle floats so we iterate by whole numbers and divid...
This function assesses a location's novelty by comparing sensory input (via BVC array) to short-term (STM) and long-term memory (LTM). It calculates a prediction score; if low, it checks if the current BVC matches existing LTM entries. If not, the location is added to LTM as "new." STM is updated with new data, and the...
def make_judgement_on_location(x, y, environment, stm, ltm, curr_stm_size, curr_ltm_size): bvc_array = update_bvc(x, y, environment) stm_avg = create_mov_avg_from_stm(stm, curr_stm_size) pred_score = create_pred_score(stm_avg, bvc_array) stm, curr_stm_size = add_memory_to_stm(bvc_array, stm, curr_stm_size) if pred...
def add_empty_cells(self): for row in range(self.get_num_rows()): self.__cells.append([]) for col in range(self.get_num_cols()): self.__cells[row].append(Cell(self, Coordinate(row, col))) def add_obstacles(self): for i in range(self.get_num_obstacles()): ...
The code initializes a grid environment by adding empty cells, obstacles, predators, and prey, establishing the foundational structure for interactions in a simulation or game.
def init_cells(self): self.add_empty_cells() self.add_obstacles() self.add_predators() self.add_prey()
def compute_mean_mles(train_data, train_labels): ''' Compute the mean estimate for each digit class Should return a numpy array of size (10,64) The ith row will correspond to the mean estimate for digit class i ''' means = np.zeros((10, 64)) # Compute means for i in range(10): d...
The main task of the code is to train a probabilistic model using Gaussian MLEs on training data, compute average log-likelihoods for training and test sets, classify data using the model, evaluate classification accuracy on both sets, and visualize covariance matrix eigens. It performs data loading, statistical parame...
def main(): train_data, train_labels, test_data, test_labels = data.load_all_data('data') # Fit the model means = compute_mean_mles(train_data, train_labels) covariances = compute_sigma_mles(train_data, train_labels) avg_log_train = avg_conditional_likelihood(train_data, train_labels, means, covari...
def get_initalize_inputs(self) -> None: """ Get and validate user input (targest_score, player_count) from standard input. The result is directly assigned to the attributes. """ # get target_score while True: try: input_score = int(in...
The code's main task is to initialize a game by gathering user inputs, setting up attributes, generating players, and starting the game loop. It initializes the round counter and triggers the execution of game rounds, orchestrating the game's setup and progression.
def __init__(self) -> None: """ Get user input, initialise attributes and execute the game. """ # initalise the arributes self.get_initalize_inputs() self.generate_players() self.round_number = 1 # run the game self.execute_rounds()
def cts(limits: Iterable[float]) -> np.array: """Converts constraints into the coodinates of a constraints simplex""" return __cts(np.asarray(limits, dtype=DTYPE)) def cm_matrix_det_ns(vertices: np.ndarray) -> float: """This computes the Cayley-Megner Matrix determinant, and then normalises its sign bas...
The function performs rescaling of coordinates using a simplex-based method. It checks if the volume of the input simplex is smaller than the standard simplex. If so, it applies transformations to adjust the limits, rescales the coordinates, and inverts the transformation. If not, it directly rescales. The task involve...
def __ssr(limits: np.array, coord: np.array) -> Tuple[Union[float, int], Optional[np.array]]: """Implementation of the smallest simplex first rescale""" limits_simplex = cts(limits) try: limits_simplex_vol = cm_matrix_det_ns(limits_simplex) except ValueError: limits_simplex_vol = 0 e...
def printLog(mString): # display cards # print(mString) return def check(): global totalWin # print(len(deck)) if sumTotal == 21: # print("21! You win") totalWin += 1 return elif sumTotal > 21: # print("Bust! You went over 21") return def _PolicySelect...
The main task of the code is to simulate a card game turn by dealing two unique cards to a player and two to a dealer, removing them from the deck, checking for wins/busts, and updating the win counter based on hand comparisons. It handles Ace logic, dealer hitting rules, and ensures no duplicate card selections during...
def deal(): global sumTotal global deck global totalWin # global index1,index2,index3,index4 # print(len(deck)) # Random index for player pick1 = random.randint(0, len(deck)-1) pick2 = random.randint(0, len(deck)-1) # Checks if the same card index is chosen again. Avoids selecting...
def showImg(img, frame): global photoImage, state_img resize_img = resizeImg(img) image = Image.fromarray(resize_img) photoImage = ImageTk.PhotoImage(image) # set Stage image for save method state_img = img #Displays images as specified position. tk.Label(frame, image=photoImage...
This code creates an image editor GUI using Tkinter, allowing users to apply transformations (rotate, edge detection, sepia, invert, red filter) and save edited images. It loads an image via OpenCV, displays it, and provides buttons for real-time edits. Global variables track rotation angle and filter state. The interf...
def image_console(): global G_rotation_angle, G_filter_state , filePath if not filePath: messagebox.showwarning("Error", "No image selected!") return # Create GUI to make Top level of that window (default = root) # Using only 'tk.Tk()' the program cannot find the image #*******...
def buy(self): self.number = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:") if self.number == "1": self.w = 250 self.mi = 0 self.b = 16 self.mo = 4 self.check() if self.number == "2": ...
The code processes user commands to perform actions (buy, fill, take, check remaining resources) on a coffee machine simulation until the user inputs "exit". It continuously prompts for input, executes corresponding methods, and maintains the machine's state.
def work(self): while self.action != "exit": self.action = input("Write an action (buy, fill, take, remaining, exit):") if self.action == "buy": self.buy() if self.action == "fill": self.fill() if self.action == "take": ...
def get_splits(self): data_collector = DataCollector(self.path) train, test = data_collector.get_splits_for_mode(self.mode) return train, test def get_interplay_for_split(self, split): df = pd.DataFrame() for path in tqdm(split): if 'non_delta' in path: ...
The main task of the code is to generate training and test feature dataframes by selecting either interplay-based or length-based feature extraction methods, depending on the specified type, and returning both resulting dataframes.
def get_features(self): train_paths, test_paths = self.get_splits() if self.type == 'interplay': df_train = self.get_interplay_for_split(train_paths) df_test = self.get_interplay_for_split(test_paths) elif self.type == 'length': df_train = self.get_num_turns(t...
def u_func(x,t): """ The example function u(x,t) from the report """ u_vals = (np.sin(2 * np.pi * x) / (2 * np.pi)) * (np.sin(2 * np.pi * t) / (2 * np.pi)) return u_vals def w_func(x,t): """ The example function w(x,t) from the report """ w_vals = (np.sin(2 * np.pi * x) / (2 * np.pi)...
The function computes and plots numerical solutions of the wave equation over multiple timesteps using a solver, comparing them with exact solutions. It discretizes the spatial and temporal domains, initializes conditions, solves the equation iteratively, and visualizes results at specified intervals alongside exact an...
def plot_timesteps(M, N, delx, delt, alpha, u_func, w_func): """ Function that computes and plots a number of timesteps of the wave equation :param M: number of space steps required :param N: number of time steps required :param delx: space steps :param delt: time steps :param ...
def find_event_index(self, event): """ Match the event to index in the list of events and return the index of the match """ element = 0 event_reference = -1 while element < len(self.events_data): if event == self.events_data[element][ED_EVNO]: even...
The main task of the code is to process raw results data by enriching each record with event details, swimmer information, and additional fields like time and validity. It loops through each result, retrieves associated event and swimmer data, constructs an expanded record, and appends it to a list. Errors are raised i...
def process_results(self): """ For each raw result, expand to full information """ # # Steps to take for each record [source]: # Add event number # Add event category # Add event # Add swimmer name # Add swimmer number # Add club ...
def get_swimmer_number_and_event(): """ Get the swimmer number and the event number from the entry fields """ swimmer_number = swimmer_number_entry.get() event_number = event_var.get() parts = event_number.split(",") if len(parts) > 1: event_number = parts[0] else: event_number =...
This function updates a record in the results database by confirming user intent, retrieving swimmer/event data, deleting the existing entry, and resaving results. It prevents updates unless a record is first retrieved, using dialog boxes for confirmation and error handling.
def cb_update_results_entry(event): """ Update an entry from the results database """ if save_entry_button["state"] != "disabled": tkMessageBox.showinfo("Error", "Retrieve record first", parent=master) else: response = tkMessageBox.askyesno("Update", "Update this entry?", parent=master) ...
def get_next_available_swimmer_number_for_club(club): """ Find the location in the database for a new swimmer for a club """ # scan swimmer database for club # we want to track two values: free swimmer number and # where to put that swimmer in the database (to keep clubs together) index = 1...
(The function `save_swimmer` adds a new swimmer to a database or updates an existing record. It validates input fields, checks for duplicate swimmer numbers, and either updates the existing entry or inserts a new one. If the swimmer's class is "team," it appends to the end; otherwise, it finds the next available number...
def save_swimmer(): """ Add a new swimmer to the list of participants Or update the swimmer information if record already exists """ missing_field = ( not swimmer_number_entry.get() or not swimmer_name_entry.get() or not club_var.get() or not age_category_var.get() ...
def change_mode_to_free_relay_entry(): """ Put points table into free relay entry mode """ idx = CLASS_LIST.index("T") class_var.set(CLASS_LIST[idx]) if event_var.get() != "": # get category parts = event_var.get().split(",") if len(parts) == 3: category = par...
This function handles mode setup for data entry based on the event type. It switches to 'Free Relay' or 'Clubs' entry modes, resets UI fields (swimmer number, class, club, age), sets focus on the swimmer number entry, and displays the next available swimmer number to prepare for new data input.
def cb_ready_entry_mode(event): """ set up for data entry mode change """ if event == "Free Relays": change_mode_to_free_relay_entry() elif event == "Clubs": change_mode_to_clubs_entry() # This mode may have been selected or may have been forced from another mode if entry_mode_var.ge...
def update_from_event_number(): """ update cursor from event number entry """ if master.focus_get() == event_entry: event_no = event_entry.get().upper() if event_no != "": # update the event displayed match = event_no + "," found = False for item i...
This function repositions the input cursor between fields in a GUI application based on user focus. It sequentially updates data (e.g., event → club → swimmer number → lane → time) and triggers actions like saving results. In "Free Relays" mode, it auto-populates the next swimmer number and adjusts focus, ensuring stru...
def cb_reposition_cursor(event): """ Move cursor based on field of focus """ # event number if master.focus_get() == event_entry: update_from_event_number() # club elif master.focus_get() == club_entry: update_from_club() # swimmer number --> lane elif master.focus_get() == s...
def cat_assign(): with open("files/new_cats.csv") as f: payee_dict = csv.DictReader(f) for payee in payee_dict: if payee["cat"]: db_add("categories", values={"cat_name": payee["cat"], "tracking": payee["tracking"]}) cat_id = id_get("categories", payee["cat...
The main task of the code is to process CSV files from the "files" directory by identifying transaction data, mapping headers to rows, determining payee columns based on account numbers, inserting parsed transactions into a database, and deleting processed files. It handles date checks, header normalization, and catego...
def read_files(): exp_files = [f for f in os.listdir("files") if os.path.isfile(os.path.join("files", f))] for fle in exp_files: if fle == "new_cats.csv": cat_assign() else: heads = None with open("files/{0}".format(fle)) as f: exp_reader = csv...
def cat_sum(): t_by_cats = cat_trans() sum_by_cat = {} for cat in t_by_cats: cat_sum = 0 for t in t_by_cats[cat]: cat_sum += t[1] sum_by_cat[cat[1]] = cat_sum return sum_by_cat def cat_sum_by_year(): t_by_cats = cat_trans() sum_by_cat = {} for cat in t_by_...
The main task of the code is to generate multiple pie charts from aggregated categorical data across different time frames (all-time, yearly, and monthly). It constructs a dictionary of graph titles and corresponding data, processes values to ensure positivity, removes non-positive entries, and finally calls a pie char...
def g_make(): graphs = {} g_count = 0 all_title = "{0:02}: All Time".format(g_count) graphs[all_title] = cat_sum() g_count += 1 yearly = cat_sum_by_year() for y in yearly: title = "{0:02}: {1}".format(g_count, y) g_count += 1 graphs[title] = yearly[y] monthly = ca...
def read_id_mapping(self, path): mapping = {} count = 0 with open(path, 'r') as f: for line in f: line = line.strip() if line not in mapping: mapping[line] = count count += 1 return mapping def build_vali...
The code initializes a Steam dataset loader by setting paths for user/app data, loading or preprocessing graph data, and building a dataloader. It reads ID mappings, constructs validation/test data, checks for preprocessed graphs, processes data if missing, and saves the graph. Finally, it creates a dataloader for grap...
def __init__(self, args, root_path, user_id_path, app_id_path, app_info_path, friends_path, developer_path, publisher_path, genres_path, device = 'cpu', name = 'steam'): logging.info("steam dataloader init") self.args = args self.root_path = root_path self.user_id_path = user_id_path ...
def heuristic(a, b): # Calculates heuristic values for A* Path Planning return np.sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown(heap, 0, len(heap)-1) def heappop(heap): """Pop the smalle...
This function implements the A* algorithm to find the shortest path on a 12x12 grid between given start and goal coordinates, avoiding obstacles marked as '1'. It uses eight possible movement directions, including diagonals, and calculates path costs with a heuristic. The path is reconstructed by backtracking from the ...
def shortest_path(start, goal): """ Purpose: --- This function should be used to find the shortest path on the given floor between the destination and source co-ordinates. """ array = np.zeros((12, 12)) array[3][3] = 1 array[3][4] = 1 possible_directions = [(0, 1), (0, -1), (1, 0),...
def shortest_path(start, goal): """ Purpose: --- This function should be used to find the shortest path on the given floor between the destination and source co-ordinates. """ array = np.zeros((12, 12)) array[3][3] = 1 array[3][4] = 1 possible_directions = [(0, 1), (0, -1), (1, 0),...
The function navigates a robot from a start position to each target point in sequence using a shortest path algorithm. It adjusts movement based on detected QR codes, updating the robot's position and stopping when the target QR code is reached, while iterating through each target point in the list.
def nav_logic(client_id, qr_code, wheel_joints, start, target_points, transformed_image): """ Purpose: --- This function should implement your navigation logic. """ global curr_cords if qr_code != 'hi': curr_cords = qr_code for point in target_points: route = shortest_pa...
def init_setup(client_id): """ Purpose: --- This function will get the object handles of all the four joints in the bot, store them in a list and return the list Input Arguments: --- `client_id` : [ integer ] the client id of the communication thread returned by in...
Your return The main task of the code is to navigate a robot through a series of target coordinates using vision sensor data and QR code detection. It initializes the robot's setup, captures and processes visual data to detect QR codes, then employs navigation logic to guide the robot along the specified path, ensuring...
def task_3_primary(client_id, target_points): """ Purpose: --- # NOTE:This is the only function that is called from the main function and from the executable. Make sure to call all the necessary functions (apart from the ones called in the main) according to your logic. The bot should travers...
def handle_req_post(self, post): try: regex = self.REQ_POST_REGEX match = re.match(regex, str(post.title)) if match: amt = float(match.group(1)) currency = match.group(2).upper() if currency not in currencies_supported: ...
The main task of the code is to process a new post by checking its title's prefix and routing it to specific handler methods based on predefined tags like [REQ], [PAID], [UNPAID], [OFFER], or defaulting to an error handler if none match.
def handle_new_post(self, post): print(f"New post: {post.title}") if str(post.title).startswith("[REQ]"): self.handle_req_post(post) elif str(post.title).startswith("[PAID]"): self.handle_paid_post(post) elif str(post.title).startswith("[UNPAID]"): sel...
def get_root(): home = os.path.expanduser('~') return os.path.join(home, '.mps/mpsc20190813') def create_root(): if not os.path.exists(get_root()): os.makedirs(get_root()) return True return False def get_data_path(name): return os.path.join(get_root(), name) def download_gz(url, nam...
This function downloads and preprocesses the Caltech101 image dataset, resizing images to specified dimensions, normalizing color channels, and returning them as NumPy arrays along with corresponding labels and category names.
def caltech101(width=150, height=150): if not os.path.exists(get_root()): create_root() if not os.path.exists(get_data_path('caltech101')): url = 'http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz' download_gz(url, 'caltech101') path = os.path.join(g...
def read_data(f = './Data_Output/Pablo_out/3param_out.csv', M1 = 0, M_min = 0, alpha = 0): data = np.loadtxt(f) if M1 == 1: logM1 = data[:, 6:10] return 10.**logM1 if M_min == 1: logMmin = data[:, 2:6] return 10.**logMmin if alpha == 1: alpha_va = data[:, 10:14] ...
This function calculates the chi-squared statistic by comparing theoretical models (based on input parameters theta) to observed data (from Pablo or Xiu datasets). It loads magnitude and mass data, applies parameter-specific models, computes residuals, and sums squared residuals normalized by variance to assess goodnes...
def chi2(theta): if Pablo_fit == 1: ms_raw = read_data(f = './Data_Output/Pablo_out/3param_out.csv', M1 = M1_fit, M_min = M_min_fit, alpha = alpha_fit) mag_raw = np.loadtxt('./Data_Output/Pablo_out/3param_out.csv')[:-1, 0] ms_data = ms_raw[:-1, 2] ms_var = ms_raw[:-1, 3] - ms_raw[:-1...
def get_det(m): if len(m) == 2: return m[0][0] * m[1][1] - m[0][1] * m[1][0] det = 0 for col in range(len(m)): sign = (-1) ** col cofactor = [row[: col] + row[col + 1:] for row in (m[: 0] + m[1:])] det += (sign * m[0][col] * get_det(cofactor)) return det def get_cofactor...
This code computes the inverse of a square matrix using the adjugate (classical adjoint) method. It calculates the determinant, constructs the cofactor matrix, transposes it to form the adjugate, then divides each element by the determinant to obtain the matrix inverse. The function handles 2x2 matrices with a direct f...
def inv(m): d = get_det(m) if len(m) == 2: return [[m[1][1] / d, -1 * m[0][1] / d], [-1 * m[1][0] / d, m[0][0] / d]] # Get matrix of cofactors cofactors = get_cofactors(m) # Get adjugate cofactors = transpose(cofactors) # Get adj / det for r in range(len(cofac...
def normalise_matrix(m): trans = [] absorbing = [] for row in m: denom = sum(row) if denom == 0: absorbing.append(row) for i in range(len(row)): row[i] = frac(0) else: trans.append(row) # Two identical for loops to pre...
Your return The code calculates the absorption probabilities in a Markov chain with absorbing states, returning them as integers with their least common multiple (LCM). It normalizes the input matrix, extracts transient and absorbing states, computes the fundamental matrix $ F $, multiplies it by the absorption probabi...
def solution(m): # Edge cases assert len(m) == len(m[0]) assert len(m) >= 1 # Get variables for calculation m, trans, absorbing = normalise_matrix(m) # Another edge case if len(absorbing) == 1: return [1, 1] Q, R, I = get_q_r_i(m) # Perform calculations I_minus_Q = s...
def run_orchestrator( self, test_dummy_commands: list[str], duration_sec: int = 3, max_cpus: int = 1, multicorpus: bool = False, extra_args: list[str] = None, ) -> (list[str], int): corpus_files = [self._FAKE_CORPUS[0]] if multicorpus: corpus_files.append(self._FAKE_C...
This test verifies that the orchestrator detects multiple issues when a snapshot fails. It checks the return code, ensures over 50 issues are logged, and confirms specific error messages appear in the logs, validating failure detection and logging functionality within a 3-second timeframe.
def test_snap_failure(self): (err_log, returncode) = self.run_orchestrator( ['snap_fail'], extra_args=['--enable_v1_compat_logging'] ) self.assertEqual(returncode, 1) latest_entry = self._parse_v1_log(err_log) self.assertGreater( int(latest_entry['issues_detected']), 50, # a...
def run_orchestrator( self, test_dummy_commands: list[str], duration_sec: int = 3, max_cpus: int = 1, multicorpus: bool = False, extra_args: list[str] = None, ) -> (list[str], int): corpus_files = [self._FAKE_CORPUS[0]] if multicorpus: corpus_files.append(self._FAKE_C...
This test verifies that the orchestrator writes a binary log entry containing a session summary when 'snap_fail' exits with status 1. It checks log content, ensures the log isn't truncated, and confirms exactly one session_summary field is present in the parsed binary log entries.
def test_binary_logging(self): (read_fd, write_fd) = os.pipe() (err_log, returncode) = self.run_orchestrator( ['snap_fail'], extra_args=[ '--sequential_mode', '--log_session_summary_probability=1', '--binary_log_fd', str(write_fd), ], )...
def extract_samples_from_string(input_str): content = remove_comments(input_str) input_matches = re.findall(r'(?i)##\s*sample\s*input\s+(.*?)\s*---', content, re.DOTALL) output_matches = re.findall(r'(?i)##\s*expected\s*output\s+(.*?)\s*---', content, re.DOTALL) if not (input_matches and output_matche...
The main task of the code is to process markdown (.md) files from the "Questions" directory, extract input/output parameters, generate corresponding Python solution and test files, and organize them into structured folders. It handles both explicit file paths and automatic discovery of unprocessed .md files, creating n...
def main(md_filepath=None): if md_filepath and not os.path.exists(md_filepath): print(f"Error: File '{md_filepath}' not found ") return if not md_filepath: md_filepath = None for root, _, files in os.walk("Questions"): for file in files: if ".md" in f...
def generate_start_line(files): method = random.choice(methods) resource = "/"+random.choice(files) #print(resource) parameters = generate_params() http_string = "HTTP/1.1" end = "\x0d\x0a" return method+" "+str(resource)+str(parameters)+" "+str(http_string)+"\x0d\x0a" def generate_body(json=False, xml=F...
The code generates HTTP requests by dynamically creating start lines, headers, and bodies. It enforces banned headers (e.g., "Transfer-Encoding" for GET) and adjusts content types (XML/JSON) to regenerate bodies. The function combines these elements into a complete request string with CRLFs, ensuring compliance with sp...
def generate_request(modify_chance, filething, banned_headers=[], mandatory_headers=[]): ''' Transfer-Encoding: compress is banned when the request is a GET request. ''' get_banned_headers = ["Transfer-Encoding"] put_banned_headers = ["Transfer-Encoding"] start_string = generate_start_line(filething) ...
def selectParents(pop): parents = [] popLength = len(pop) for iterator in range(MAX_CROSS_ITERATIONS): parentsCandidates = [] for index in range(CANDIDATE_AMMOUNT): random.seed() randIndex = random.randrange(popLength); parentsCandidates.append(pop[ran...
This function evolves a population by selecting parent pairs, generating offspring, mutating a subset of them randomly, and appending the new children to the original population to form the next generation in a genetic algorithm.
def procreatePopulation(pop): parentsPairs = selectParents(pop) children = generateChildren(parentsPairs) childrenAmmount = len(children) for index in range(0,childrenAmmount): random.seed() roll = random.randrange(0,10) if roll < 4: children[index] = mutate(chi...
def initPopulation(pop_size): popList = [] for x in range(0,pop_size): ind = makeIndividual() popList.append({ 'genotype': ind, 'fitness': 0 }) return popList def calculatePopulationFitness(pop): for ind_index in range(0,len(pop)): pop[ind_index]...
The main task of the code is to evolve a population over a specified number of iterations by repeatedly procreating (reproducing) and filtering individuals, returning the final population and iteration count. It initializes a population, iteratively applies reproduction and selection, and terminates after reaching the ...
def runByIterations(iterationMax): population = initPopulation(POPULATION_SIZE) population = calculatePopulationFitness(population) iterations = 0 while(iterations <= iterationMax): population = procreatePopulation(population) population = filterPopulation(population) iteratio...
def initPopulation(pop_size): popList = [] for x in range(0,pop_size): ind = makeIndividual() popList.append({ 'genotype': ind, 'fitness': 0 }) return popList def calculatePopulationFitness(pop): for ind_index in range(0,len(pop)): pop[ind_index]...
The function `runByFitness` evolves a population of 100 individuals through iterative selection, reproduction, and filtering until a valid solution is found or 10,000 iterations are reached, returning the final population and iteration count.
def runByFitness(): population = initPopulation(100) population = calculatePopulationFitness(population) iterator = 0 while(validatePopulation(population) < 1 and iterator < 10000): population = procreatePopulation(population) population = filterPopulation(population) iterator...
def initial_individual(self): for i in range(0, self.individual_count): self.individuals.append(chromosome(self.min, self.max, self.individual_length)) return def getFitness(self, chromosome): if(self.func=="rosenbrock"): sum = self.rosenbrock(chromosome) elif...
The code implements an evolutionary algorithm to optimize a population of individuals over a set number of iterations. It initializes individuals, evaluates their fitness, selects parents, generates offspring via recombination, selects survivors, and tracks the best fitness value at each iteration. The result is a list...
def run(self): result=[] self.initial_individual() iteration=0 time1=time.time() time2=time1 tmp = False while(iteration < self.iterations): iteration+=1 # setFitness for i in range(0, self.individual_count): ...
def make_directory_for_run(): """ Make a directory for this training run. """ print(f'Preparing training run {UNIQUE_RUN_ID}') if not os.path.exists('./runs'): os.mkdir('./runs') os.mkdir(f'./runs/{UNIQUE_RUN_ID}') def initialize_models(device = get_device()): """ Initialize Generator and Discriminator mo...
The code trains a DCGAN (Deep Convolutional Generative Adversarial Network) by initializing generator and discriminator models, preparing datasets with BERT and enCodec models, setting up loss functions and optimizers, and iterating over epochs to perform adversarial training. It ensures reproducibility via a fixed see...
def train_dcgan(): # set_start_method('spawn') # handling pyorch multiprocess cuda error """ Train the DCGAN. """ # Make directory for unique run make_directory_for_run() # Set fixed random number seed torch.manual_seed(42) # Initialize models generator, discriminator , tokenizer, bert_model, enC...
def make_directory_for_run(): """ Make a directory for this training run. """ printf(f'Preparing training run {UNIQUE_RUN_ID}') if not os.path.exists('./runs'): os.mkdir('./runs') os.mkdir(f'./runs/{UNIQUE_RUN_ID}') def initialize_models(device = get_device()): """ Initialize Generator and Discriminator m...
The code trains a Deep Convolutional GAN (DCGAN) to generate music using a MIDI dataset. It initializes models, sets up training parameters, and iteratively trains the generator and discriminator while logging losses via W&B. The script handles pretrained model resumption, saves checkpoints periodically, and generates ...
def train_dcgan(): # INIT WANDB wandb.init(project='GrooveGenie_crnnGan', entity='consolebot') global g_lossi_g, d_lossi_g # set_start_method('spawn') # handling pyorch multiprocess cuda error """ Train the DCGAN. """ # Make directory for unique run make_directory_for_run() # Set fixed random...
def retrieve_source_set(source_dir, file_type, c_lib=c_stand, ignore_empty=False): """ Generates a set of FileNode objects for each file of a specified type in a source directory and its subdirectories. This function scans a given directory and its subdirectories for files with a specified extension. It cr...
The function amalgamates C/C++ source files by reading all .c, .h, and optionally .cpp files from a directory, parsing dependencies, performing topological sorting to determine file order, and combining them into a single amalgamated file. It handles standard libraries, header dependencies, and saves the result as a .c...
def amalgamate( dir, c_lib, file_name, isCpp=False, save_directory=None, split_header_files=True ): """ Amalgmates C source code similar to SQLite https://sqlite.org/amalgamation.html Does this by reading in all .c and .h files in a directory, creates a FileNode object for each file which reads and sav...
def pixels_fill(color): for i in range(len(ar)): pixels_set(i, color) def pixel_group_set(pg, color): for i in range(len(pg)): pixels_set(pg[i], color) def pixels_show(): dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)]) for i,c in enumerate(ar): r = int(((c >> 8) & 0xFF...
The code simulates brake light behavior by blinking red lights three times, holding the red signal for 5 seconds, then turning them off with a 2-second delay, followed by a "brakes released" confirmation. It controls pixel groups to visually represent brake activation and deactivation with timed intervals.
def brakes(): pixels_fill(BLACK) for blink in range(0,3): pixel_group_set(BRAKES, RED) pixels_show() utime.sleep(.1) pixels_fill(BLACK) pixels_show() utime.sleep(.1) pixel_group_set(BRAKES, RED) pixels_show() utime.sleep(5) pixels_fill(BLACK) p...
def leftTurn(): pixels_fill(BLACK) for blink in range(0,2): for i in range(0,len(LR)): pixels_set(LR[i], YELLOW) pixels_set(LF[i], YELLOW) pixels_show() utime.sleep(.02) pixel_group_set(LR, BLACK) pixel_group_set(LF, BLACK) pixels_s...
The main task of the code is to run an animation thread that continuously executes predefined animations (e.g., left/right turns, hazards, headlights, brakes) based on the global `ANIMATION` variable. If no new command is received for over 30 seconds, it resets the animation. The thread checks the `LASTREQUEST` timesta...
def animThread(): global ANIMATION global LASTREQUEST print('Starting main animation thread') while True: if ANIMATION == "left": leftTurn() elif ANIMATION == "right": rightTurn() elif ANIMATION == "hazards": hazardLights() elif ANIMATI...
def setup_logging(file_name: str = 'server-log.txt'): global LOGGER LOGGER = CustomLogger(CURRENT_SCRIPT.parent / file_name) def log_info(error: str): print(f'{LOG_PREFIX}: {error}') if LOGGER is not None: LOGGER.info(f'{LOG_PREFIX}: {error}') def log_error(error: str): print(f'{LOG_PREFIX}:...
The code starts a server on a specified port, ensuring single-instance execution via a mutex. It initializes logging, creates a TCP socket, binds to the port, and enters a loop to handle incoming connections. The server gracefully handles exceptions, keyboard interrupts, and specific errors, releasing the mutex and clo...
def server(port: int): setup_logging() mutex = GlobalMutex(GLOBAL_MUTEX_NAME) # We need to check again if the server is running since one could have been started since the # check performed in `main` (which is done before starting the daemon to avoid doing that if not required). already_running...
def send_message(msg: bytes, port: int, timeout: float = 0.1) -> bool: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) try: sock.connect(('localhost', port)) sock.send(msg) return True except: return False def enable_adb_port_reversal(por...
This script manages a socket server's lifecycle, handling command-line arguments for port specification, daemon mode, and server termination. It checks for existing instances using a mutex, avoids duplicates, and starts the server either in the foreground or as a daemon process, with OS-specific handling for Windows an...
def main(): parser = argparse.ArgumentParser() # In order to allow VS to call this script with an empty string for port, we need to make it a string argument and set to the default port if empty parser.add_argument('--port', default=DEFAULT_PORT, help=f'Port used for the socket server (default: {DEFAULT_POR...
def welcome(to_print=True): message = '''Congratulations, you have been elected the ruler of ancient Babylon. Your duties are to dispense food, direct farming, and buy and sell land as needed to support your people. Watch out for rat infestations and the plague! Grain is the general currency, measured in bushels. ...
The code simulates a ruler's 10-year governance, managing land transactions, food distribution, and agriculture while handling population changes, harvests, and random events. It evaluates the ruler's success based on starvation rates and land wealth, printing summaries and judgment messages. If the ruler fails (e.g., ...
def main(king_name = None, term=None): random.seed() welcome() king = Ruler(king_name, term) # Start a 10 year rule: while (king.in_office and king.years_ruled<king.term): king.print_summary() # Ask 4 questions # Starting with land purchase and sales:...
def get_first_word(tiles, curr_word, valid_words, curr_node): """ return the best word based on a set of tiles tiles: list of tile objects dawg: points to the root node of our DAWG """ if len(tiles) == 0: return get_highest_scoring(valid_words) for l in curr_node.children: f...
The main task of the code is to play a game by placing valid words from a DAWG dictionary until all tiles are used, returning True if all tiles are exhausted within a specified maximum number of attempts (max_iter), and False otherwise. It starts with an initial word placement, then iteratively finds and places subsequ...
def play_until_peel(game, dawg, max_iter=10): """"" Plays from beginning of the game until able to peel. Return True if all tiles can be used in fewer than max_iter tries, and return False otherwise. game: Game object dawg: dawg of valid words max_iter: number of tries to put down a word ...
def countPlacedTiles(self): placed = 0 notPlaced = 0 for ii in range(self.COLS): for jj in range(self.ROWS): if self.array[ii][jj].getIsPlaced(): placed += 1 else: notPlaced += 1 return (placed, notPlaced...
The code processes user actions in a game loop, updating game state and calculating rewards based on actions (e.g., playing tiles, peeling letters, reshuffling). It checks for quit events, evaluates board validity, adjusts scores, and returns reward values alongside game status variables like completion state and shuff...
def playAction(self, action): for myevent in event.get(): # User did something if myevent.type == QUIT: # If user clicked close self.done = True # Flag that we are done so we exit this loop reward = 0 (placed, notPlaced) = self.countPlacedTiles() # parse ac...
def drawconsole(self): ROWS = self.ROWS COLS = self.COLS SIZE = self.SIZE framehor = self.framehor framever = self.framever self.screen.fill([200, 200, 100]) draw.rect(self.screen, [60, 60, 60], (self.framehor-3, self.framever - ...
This code handles user interactions in a tile-based game, managing mouse and keyboard inputs to move, place, and manipulate tiles on a grid. It updates the game state, processes events like tile pickup/drop, checks for valid moves, and renders the game board. The function also manages timing, resets, and game completio...
def play(self): framehor = self.framehor framever = self.framever SIZE = self.SIZE ROWS = self.ROWS COLS = self.COLS if self.gametime == 0: self.clock.tick() self.gametime += 0.001 else: if not self.complete: se...
def get_storage(self): return self._storage def display_menu(first_time=False): """ This method displays all the options available to the user in the console :param first_time: :return: """ # if this is the first time the program has run if first_time: ...
This method runs a menu-driven loop for a movie database application, allowing users to list, add, delete, update, search, sort, and generate reports for movies. It processes user inputs via validation, executes corresponding operations, and continues until the user selects the exit option.
def console(self, valid_choices, main_menu_prompt): """ This method runs the program in a listener loop. :return: """ # Initialize local variables storage = self.get_storage() filename = storage.get_file_path() # The data in this ^^^^^^^^^ file should be a...
def train(self, X_train, y_train): self.get_model().fit(X_train, y_train) def test(self, X_test, y_test): pred = self.predict(X_test) metrics = evaluation_metrics(y_test, pred) return metrics def get_model(self): return self.regressor def eval_sku(self, test_lags, scaler, thresho...
This function trains a machine learning model using provided training data, evaluates it on test data, logs hyperparameters and evaluation metrics (MAE, MSE, RMSE, MAPE) to MLflow, and stores the model. It also conditionally logs additional metrics for SKU evaluation, clustering, and multistep forecasts if parameters a...
def mlflow_pipeline(self, X_train, y_train, X_test, y_test, scaler=None, threshold=None, cluster_model_id=None, sku_eval=None, multistep_eval=None, run_name="XGBoost Model Training", model_name="xg_model"): # Useful for multiple runs (only doing one run in this sample notebook) with mlflow.start_run(run...
def train(self, X_train, y_train): self.get_model().fit(X_train, y_train) def test(self, X_test, y_test): pred = self.predict(X_test) metrics = evaluation_metrics(y_test, pred) return metrics def get_model(self): return self.regressor def eval_sku(self, test_lags, scaler, thresho...
This function trains a machine learning model using provided training data, evaluates it on test data, logs hyperparameters and performance metrics (MAE, MSE, RMSE, MAPE) to MLflow, and saves the model. It optionally logs additional metrics for SKU evaluation, threshold settings, and multistep forecasts, then returns t...
def mlflow_pipeline(self, X_train, y_train, X_test, y_test, scaler=None, threshold=None, cluster_model_id=None, sku_eval=None, multistep_eval=None, run_name="Random Forest Model Training", model_name="rf_model"): # Useful for multiple runs (only doing one run in this sample notebook) with mlflow.start_r...
def train(self, X_train, y_train): self.get_model().fit(X_train, y_train) def test(self, X_test, y_test): pred = self.predict(X_test) metrics = evaluation_metrics(y_test, pred) return metrics def get_model(self): return self.regressor def eval_sku(self, test_lags, scaler, thresho...
This function trains a machine learning model (e.g., SVR) using provided data, evaluates its performance, logs key metrics (MAE, RMSE, MAPE) and parameters to MLflow, and saves the model. It conditionally logs additional metrics for SKU evaluation, clustering, and multistep forecasts, enabling experiment tracking and m...
def mlflow_pipeline(self, X_train, y_train, X_test, y_test, scaler=None, threshold=None, cluster_model_id=None, sku_eval=None, multistep_eval=None, run_name="SVR Model Training", model_name="sv_model"): # Useful for multiple runs (only doing one run in this sample notebook) with mlflow.start_run(run_nam...
def _calc_cumulative_ret(self): return self.summary.tot_asset / self.start_cash - 1 def calc_comp_ann_ret(self): cumu_ret = self._calc_cumulative_ret()[-1] n = len(self.dates) return (cumu_ret + 1)**(252/n) - 1 def calc_sharpe(self, rf=0): daily_ret = self._calc_daily_ret() - ((r...
The main task of the code is to print key financial performance metrics of a portfolio, including start/end dates, day count, initial cash, cumulative return, annualized return, Sharpe ratio, Sortino ratio, Calmar ratio, max drawdown, and Information Ratio (if a benchmark is provided). It aggregates and displays these ...
def show_info(self, rf=0, benchmark=None): print(f"start date: \t\t{str(self.start_date)}") print(f"end date: \t\t{str(self.end_date)}") print(f"day count: \t\t{len(self.dates)}") print(f"start cash: \t\t{self.start_cash}") print(f"cumulative return: \t{self._calc_cumulative_ret(...
def first_valid_table(dataframe): """ get first valid information for the given data :param dataframe: pd.DataFrame; :return: """ first_valid = pd.DataFrame(columns=['first_valid_date', 'total_N/A', 'N/A_since_first_valid']) # first obs date first_valid['first_valid_date'] = dataframe.ap...
The main task of the code is to analyze time-series data by loading and preprocessing a CSV file, handling missing values via forward filling, conducting ADF tests to assess stationarity, determining optimal fractional differencing parameters, applying differencing, re-evaluating stationarity post-differencing, and com...
def main(): df = pd.read_csv(r".\data\newData_Feb11.csv").set_index('Date') # since we only care about trading until the end of 2021, we drop all data after that df = df.loc[: '2022-01-01'] # check nan info fst_valid = first_valid_table(df) # forward filling df = df.fillna(method='ffill')...
def solveSudoku(self): self.SQUARE_LEN = self.info['SQUARE_LEN'] cells = [] [[cells.append(str(i) + str(j)) for j in range(self.GRID_LEN)] for i in range(self.GRID_LEN)] domains = {} for var in cells: # var = '00' domains[var] = [str(k + 1) for k in rang...
The code's main task is to determine the type of game from `self.info['game']` and delegate solving to the corresponding method: `solveSudoku()`, `solveStars()`, or `solveSkyscrapers()`, returning their results. If the game type is unrecognized, it returns `None`. The method initializes game data and iteration count be...
def solveGame(self, game_data): self.data = game_data self.iterations = 0 if self.info['game'] == 'sudoku': return self.solveSudoku() elif self.info['game'] == 'stars': return self.solveStars() elif self.info['game'] == 'skyscrapers': return se...
def remove_client(client_socket): """Remove the client by removing client_socket from sockets and clients""" send_msg(server, sockets, clients[client_socket] + " left the server") logging.info("Closed connection from " + clients[client_socket]) sockets.remove(client_socket) del clients[client_socket...
This function processes incoming chat messages by parsing commands (e.g., --leave, --help, --list) to manage client actions, send help texts, list connected users, or rename clients. It routes messages to private recipients if prefixed with @, or broadcasts group messages otherwise, while logging actions and handling i...
def handle_msg(message, sender): """Handle incoming messages by parsing parsing it according to the protocol detailed in the documentation""" if message is False: remove_client(sender) elif message == "--leave": logging.info(clients[sender] + " asked to leave the chat") remove_client...