dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def read_lines_zst(file_name): with open(file_name, 'rb') as file_handle: buffer = '' reader = zstandard.ZstdDecompressor(max_window_size=2**31).stream_reader(file_handle) while True: chunk = read_and_decode(reader, 2**27, (2**29) * 2) if not chunk: break lines = (buffer + chunk).split("\n") fo...
The code processes a JSON file, filtering lines by date range and specified field values, then writes the results to an output file in zst, txt, or csv format. It logs progress, handles errors, and applies exact or substring matches for field filtering.
def process_file(input_file, output_file, output_format, field, values, from_date, to_date, single_field, exact_match): output_path = f"{output_file}.{output_format}" is_submission = "submission" in input_file log.info(f"Input: {input_file} : Output: {output_path} : Is submission {is_submission}") writer = None if...
def debug_logger(self, method_call, method_name): self.debug_log.append((method_call, method_name,(time.time() - self.debug_time))) self.debug_last_time = time.time() def update_sand(self, sand_location): debug_temp_index = self.debug_index self.debug_index += 1 self.debug_logger...
This function updates particles in a grid by iterating from bottom to top and left to right. It processes each cell's particle type, calling specific update methods for sand and water, while ignoring stationary particles (stone, wood, air). It logs debug information and recursively schedules itself to repeat every 1ms ...
def update_particle(self): debug_temp_index = self.debug_index self.debug_index += 1 self.debug_logger(debug_temp_index, "started update_particle()") # parse through the entire grid for row in range(self.rows - 1, -1, -1): # parse from down to up for column in range(s...
def clear_terminal(): os.system('cls' if os.name == 'nt' else 'clear') return def listen_to(song, username): # add a listening event or increase listen cnt is event already exists session_exists = db.check_sessions(username) if session_exists: db.listen_to_song(song, username) else: ...
The function `get_song_action` presents a menu for user interaction with a song, offering options to listen, view details, add to a playlist, or return to the menu. It validates input, executes corresponding actions by calling other functions, and exits on 'EXIT' input.
def get_song_action(song, username): # SONG ACTIONS choice = '' clear_terminal() print(song[0],song[1],song[2]) print('1. Listen to this song.') print('2. More information.') print('3. Add to playlist.') print('4. Menu') while choice not in ['1','2','3','4']: choice = input('...
def clear_terminal(): os.system('cls' if os.name == 'nt' else 'clear') return def draw_songs_and_playlists(songs_and_playlists, page_num): # draws the requested page of songs and playlists # if no page exists nothing is drawn counter = page_num * 5 identifier_string = '' # prints 5 items ...
The code allows a user to search for songs or playlists using keywords, displays results in paginated format, and lets the user select an item to perform actions (like playing or managing) based on whether it's a song, playlist, or both. It handles navigation, error checking, and interacts with a database to retrieve a...
def search_for_song_playlist(username): clear_terminal() index = [] page_num = 0 choice = '' user_in = '' search_res = '' while user_in == '' or user_in.isspace(): user_in = input("Enter keywords\n") clear_terminal() if user_in.upper() != 'EXIT' and user_in !...
def clear_terminal(): os.system('cls' if os.name == 'nt' else 'clear') return def draw_artist_list(artists, page_num): # draws the requested page of artists # if no page exists nothing is drawn counter = page_num * 5 # prints 5 items for item in [1,2,3,4,5]: if counter == page_num*5...
The code searches for artists using user keywords, displays paginated results, and allows navigation between pages or selection of an artist to view their details. It handles input validation, pagination logic, and interacts with a database to retrieve and present artist information.
def search_for_artist(username): exit_str = 'exit' page_num = 0 clear_terminal() print('Searching For Artists:') user_input = '' while user_input == '' or user_input.isspace(): clear_terminal() print('Searching For Artists:') user_input = input('Enter Keywords to Search:\...
def clear_terminal(): os.system('cls' if os.name == 'nt' else 'clear') return def start_session(username): # check if session already started session_exist = db.check_sessions(username) user_input = '' if session_exist: print('Session Already Started.\n Would you like to end current and ...
The code displays a user menu with options to start a session, search for songs/artists, end sessions, logout, or exit. It repeatedly prompts the user, executes corresponding actions based on input, and ensures sessions are properly ended and database connections closed upon exiting.
def draw_user_screen(username): user_choice = '' # print the options and act upon a valid choice being input while (user_choice not in ['5','6']): clear_terminal() print('Select an option: ') print('1. Start a session.') print('2. Search for songs and playlists.') pri...
def generate_population_two_groups_different_periods(): """ This function generates two groups each one differing in the domain of the periods. """ population = [] id = 0 flag = False for x in range(3, 6): for y in range(5, 11): if flag: population.app...
The main task of the code is to select and return the appropriate population generation function based on the 'SCENARIO' parameter. It checks the scenario value and dispatches to specific functions like two-group periods, bridge scenarios, random grids, probability-based methods, or four-group variations. If no valid s...
def generate_population(): if params['SCENARIO'].upper() == 'TWO_GROUPS_DIFF_PERIODS': return generate_population_two_groups_different_periods() elif params['SCENARIO'].upper() == 'TWO_GROUPS_WITH_BRIDGE': return generate_population_two_groups_with_bridge() elif params['SCENARIO'].upper...
def get_all_orders(): cursor.execute("SELECT * FROM orders") all_orders = cursor.fetchall() return all_orders def get_order_items(order_id): cursor.execute("SELECT item_name, quantity, price FROM order_items WHERE order_id = %s", (order_id,)) order_items = cursor.fetchall() return order_items de...
The code displays all unpaid orders by retrieving order data, checking for associated unpaid bills, listing order items with prices, calculating totals, and providing a 'Print Bill' button for each order.
def display_all_orders(): for widget in frm.winfo_children(): widget.destroy() all_orders = get_all_orders() if not all_orders: label = tk.Label(frm, text="No orders found.") label.pack() else: for order in all_orders: order_id, _, table_number, _, _ = order...
def preprocess_image(im): assert (750, 1845, 3) == im.shape # padding image to (768, 1856, 3) old_image_height, old_image_width, channels = im.shape # create new image of desired size and color (blue) for padding new_image_width = 1856 new_image_height = 768 color = (0, 0, 0) result = n...
The code trains a model (likely a Variational Autoencoder) using training images by iterating through epochs, preprocessing hazy and clean images, and performing training steps with an optimizer. It validates the model on a validation set, computes the ELBO (Evidence Lower Bound) as the evaluation metric, and saves mod...
def train(model, train_images, val_images, epochs=10, optimizer=tf.keras.optimizers.Adagrad(learning_rate=1e-2)): for epoch in range(epochs): print('Epoch {} begins'.format(epoch)) start_time = time.time() for train_im_path in train_images: hazy_image, clean_image = get_hazy_clea...
def parse_verb(self, word_list): skip(word_list, 'stop') skip(word_list, 'error') skip(word_list, 'stop') skip(word_list, 'error') if peek(word_list) == 'verb': return match(word_list, 'verb') else: raise ParserError("Expected a verb next.") def p...
This function parses a sentence by extracting the verb, number (if present), and object from a word list, then constructs a Sentence object combining the subject with these components. It returns a Sentence with subj, verb, num, and obj if num exists, otherwise omitting num.
def parse_subject(self, word_list, subj): verb = self.parse_verb(word_list) num = self.parse_num(word_list) # should be placed before object obj = self.parse_object(word_list) if num is not None: return Sentence(subj, verb, num, obj) else: return Sentence(...
def skip(word_list, word_type): while peek(word_list) == word_type: # remove words that belongs to word_type from word_list match(word_list, word_type) def peek(word_list): if word_list: word = word_list[0] return word[0] else: return None def match(word_list, ex...
This function parses a sentence from a list of words by skipping 'stop' and 'error' tokens, then identifies the subject: if the next token is a 'noun', it uses that as the subject; if a 'verb', it defaults to the player as the subject. It returns the parsed subject or raises an error if the input doesn't start with a v...
def parse_sentence(self, word_list): skip(word_list, 'stop') skip(word_list, 'error') skip(word_list, 'stop') skip(word_list, 'error') start = peek(word_list) if start == 'noun': subj = match(word_list, 'noun') return self.parse_subject(word_list...
def gen_cnf_file(string, grid_width, k, embedding_conditions, contact_conditions, outfile): n = len(string) grid_size = pow(grid_width, 2) positions_of_ones = get_positions_of_ones(string) num_adjacent_ones = get_num_adjacent_ones(positions_of_ones) r = 2 * grid_size - (num_adjacent_ones + k) co...
The function `maximize_contacts` attempts to determine the maximum feasible value of `k` by iteratively solving a constraint satisfaction problem using a SAT solver (`glucose-syrup`). It generates CNF files for each `k`, runs the solver, and adjusts `k` based on the solver's return code: doubling `k` if successful (ret...
def maximize_contacts(string, grid_width, k, embedding_conditions, contact_conditions, outfile, time_elapsed, k_vals_tried=dict()): if k == 0: return 0 print("Generating file with k =", k) gen_cnf_file(string, grid_width, k, embedding_conditions, contact_conditions, outfile) print("Calling gluc...
def read_data(file): with open(file) as f: data = f.readlines() return data[0].strip() def is_binary_string(string): for x in string: if x != "1" and x != "0": return False return True def gen_embedding_conditions(n, grid_width): embedding_conditions = list(...
The code processes input binary strings to determine the maximum number of contacts achievable by arranging them in a grid, using a SAT solver (lingeling) with generated constraints. It reads input files, validates binary strings, computes grid dimensions, creates embedding and contact conditions, runs the solver, and ...
def main(argv): if len(argv) <= 2: print("ERROR: wrong number of arguments given\n\tUsage: main.py {list of input files} -o {output directory}") return else: outdir_index = argv.index("-o") + 1 outdir = argv[outdir_index] files = argv[1:outdir_index - 1] for file_na...
def process_udp(self, sock): """ Processes UDP connections. """ request, addr = sock.recvfrom(exf.SOCK_BUFFER_SIZE) if request: print_with_time("UDP", f"Received {len(request)} bytes from {addr}") response = self.dns_resolve(request, False) ...
The code runs a server that uses I/O multiplexing with `select` to handle both UDP and TCP sockets. It processes incoming data, accepts new TCP connections, and manages socket exceptions. The server runs in a loop until interrupted, ensuring proper cleanup by closing all sockets on exit.
def run(self): print(f"[Info] Server is running!") while True: try: # Single-threaded virgin implementation =/ readable, writable, exceptional = select.select(self.sockets, [], [], self.timeout) now = time.time() for sock in rea...
def get_key(n :int): key = [] for _ in range(n): key.append(random.randint(0, 64)) return key def get_input(n :int): print(f"Give me {n} numbers, space separated:") numbers = str(input()).strip().split() if len(numbers) != n: print(f'\nExpected {n} numbers, recieved...
The code reads a flag, converts it to ASCII values, generates a key, and validates user input. It processes input numbers by calculating their base-10 logarithm floor (digit count -1). If processed input matches the key, it XORs the key with the secret (ASCII values) and then XORs the result with the input to reveal a ...
def main(): with open('flag.txt', 'r') as f: flag = f.read().strip() secret = [] for c in flag: secret.append(ord(c)) n = len(secret) key = get_key(n) print("Key is:") for i in key: print(i, end=' ') print('\n') userinput = get_input(n) if u...
def check_incantation(self) -> bool: """Check if incantation is possible with the new object and the shared inventory Args: object (str): The name of the new objet we got Returns: bool: Incantation is possible or not """ required_ressources = LVLS[self.l...
This algorithm manages a client's state transitions in a game environment, handling communication, resource gathering, and incantation coordination. It sends commands like "Connect_nbr," "Fork," or "Look," processes inventory, broadcasts status updates, and executes incantation sequences based on conditions such as cli...
def algorithm(self): if self.step == -2: self.data_to_write = "Connect_nbr\n" self.step += 1 elif self.step == -1: if self.client_num < 6 and self.useless_slot == 0: self.data_to_write = "Fork\n" self.fork = 1 else: ...
def get_subjects_data(config, subjects, dir_out): print('Gathering subjects data...') subjects_filenames_data = dict() subjects_dfs_train = dict() for subj in subjects: print(f" --> {subj}") dir_input = os.path.join(config['dirs']['input'], subj) dir_output = os.path.join(dir_ou...
(The code processes multiple subjects' data by collecting input directories, creating output directories, loading subject data, training models, and evaluating performance in either 'post-hoc' or 'real-time' mode. It returns a performance score based on the evaluation mode, calculating either a post-hoc score or the me...
def run_wl(config, dir_in, dir_out): # Collect subjects subjects = [f for f in os.listdir(dir_in) if os.path.isdir(os.path.join(dir_in, f))] print(f" Subjects Found = {len(subjects)}") # Make subjects' output dirs for subj in subjects: make_dirs_subj(os.path.join(dir_out, subj)) # Ge...
def run_wl(config, dir_in, dir_out): # Collect subjects subjects = [f for f in os.listdir(dir_in) if os.path.isdir(os.path.join(dir_in, f))] print(f" Subjects Found = {len(subjects)}") # Make subjects' output dirs for subj in subjects: make_dirs_subj(os.path.join(dir_out, subj)) # Ge...
This function performs a grid search over multiple parameters (HZ, SP, PERMDEC, PADDING) by iterating through all combinations, modifying a configuration, running a model (run_wl), and collecting performance scores. It then sorts, visualizes, and saves results as CSV and plots, enabling systematic evaluation of model s...
def gridsearch_htm(config, dir_out, HZS, SPS, PERMDECS, PADDINGS): # Get scores modtypes_scores = {} for hz in HZS: print(f"\nHZ = {hz}") for sp in SPS: print(f" SP = {sp}") for permdec in PERMDECS: print(f" PERMDEC = {permdec}") fo...
def upsert(self, obj, table, date=(), to_del=[], cols=[]): """ performs an insert if data is not in table or an update if it is present :param obj: object with values to update in database :param table: table name :param date: (Optional) date as string :param to_del: (Opt...
This method inserts QuestionSummary objects into a database, along with associated tags and articles. It processes each entry by upserting the QuestionSummary, inserting linked articles, and creating associations between the summary, its tags (via AssociatedTag), and articles (via AssociatedArticle). It retrieves exist...
def insert_question_summaries(self, data): """ inserts QuestionSummary objects into QuestionSummary table :param data: list of QuestionSummary objects """ date = str(datetime.datetime.now()) for row in data: tags = row.tags articles = row.articles...
def print_room(room): """Prints a robot's room. You should not change this function.""" for row in room: for element in row: if element == "empty": print(" ", end="") elif element == "robot": print("R", end="") elif element == "obst...
The function makes a robot perform a random walk in a warehouse, moving in random directions while carrying and delivering packages. It tracks steps taken and continues until all packages are delivered, returning the total step count.
def walk_around_warehouse(warehouse): """Has robot conduct random walk until all packages are delivered.""" # Print the original warehouse. Do not remove. print_room(warehouse) # Track number of steps and packages held steps = 0 packages_held = [] while not all_delivered(warehouse, steps)...
def progUpt(self, value): self.prog += value self.prog_out.emit(self.prog) def verifyExistDir(self, inDir): # Return the absolute path of inDir absPath = None if path.isdir(inDir): # Given path exists if path.isabs(inDir): absPath = inDir ...
The main task of the code is to preprocess test data by converting MATLAB (.mat) and Smart Terminal DAT files into CSV format, merging MATLAB data, aligning time-aligned data, and managing output directories. It checks for required directories, creates CSV folders if missing, converts files using `mat2csv` and `dat2csv...
def preProcessData(self): headDir = self.__headDir testDir = self.__testDir self.progUpt(0) # Verify the existence of Test Data Directory testDir = self.verifyExistDir(testDir) # Test name testName = testDir.split('\\')[-1] datDir = testDir + '\\' + 'd...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
The main task of the code is to retrieve a public list by its ID after validating the user's session. It checks session authenticity, queries the database for the specified public list, returns an error if the list is not found, or returns the serialized list data on success.
def get_list_by_id(list_id): success, user = check_session() if not success: return user public_list = user.public_lists.filter_by(public_list_id=list_id).first() if public_list is None: return failure_response("list not found!") return success_response(public_list.public_list.serial...
def failure_response(message, code=404): return json.dumps({"success": False, "error": message}), code def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: re...
This function creates a public list with a specified name and access setting, associates it with the authenticated user, and saves it to the database. It validates input parameters, checks user authentication, and returns a success response with the new list's data or an error if validation fails.
def create_list(): body = json.loads(request.data.decode()) list_name = body.get('list_name') is_public = body.get('is_public') if is_public is None or list_name is None: return failure_response("Please provide access information/name of list") success, user = check_session() if not succ...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function allows a user to edit a public list's details (name and public status) by ID after validating their session. It updates the list in the database and returns the modified list data or error messages if the list isn't found or session validation fails.
def edit_list_by_id(list_id): success, user = check_session() if not success: return user public_list = user.public_lists.filter_by(public_list_id=list_id).first() if public_list is None: return failure_response("list not found!") body = json.loads(request.data.decode()) public_l...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function deletes a public list associated with the authenticated user by its ID. It checks user session validity, verifies list existence, removes the list and its user association from the database, and returns success/failure responses accordingly.
def delete_list_by_id(list_id): success, user = check_session() if not success: return user delete_list = User_PublicList_Association.query.filter_by(user_id=user.id, public_list_id = list_id).first() if delete_list is None: return failure_response("list not found!") public_list = de...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
The function retrieves all events from a specified public list by validating the user session, checking if the list exists, and returning serialized event data in a success response or appropriate error messages if validation fails.
def get_all_events(list_id): success, user = check_session() if not success: return user public_list = PublicList.query.filter_by(id=list_id).first() if public_list is None: return failure_response('list not found!') return success_response({"events": [c.serialize() for c in public_l...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
The main task of the code is to retrieve an event from a specific public list by its ID, ensuring the user is authenticated. It checks the session validity, verifies the existence of the public list and event, and returns the event data if found, or appropriate error messages if any step fails.
def get_event_by_id(list_id, event_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_list eve...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function creates a new event for a public list after validating the session, checking if the list exists, and ensuring required fields (main_title, sub_title, in_progress) are provided. It associates the event with the list, saves it to the database, and returns a success response with the event details or appropr...
def create_event(list_id): success, user = check_session() if not success: return user public_list = PublicList.query.filter_by(id=list_id).first() if public_list is None: return failure_response('list not found!') body = json.loads(request.data.decode()) main_title = body.get('m...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function edits an event's details by updating its main title, subtitle, and progress status based on JSON data from a request. It verifies user authentication, checks if the specified list and event exist, applies updates using provided or existing values, commits changes to the database, and returns a success res...
def edit_event_by_id(list_id, event_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_list ev...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
The function deletes an event from a public list by verifying the session, checking the existence of the list and event, removing the event from the list and database, then returning a success response with the event's data.
def delete_event_by_id(list_id, event_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_list ...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
The main task of the code is to handle a friend addition request by validating user session, checking if the target user exists, ensuring the user isn't adding themselves, verifying no existing friendship or pending request, and committing the new pending friend request to the database if all conditions are met.
def add_friend(): success, user = check_session() if not success: return user body = json.loads(request.data.decode()) search_id = body.get('id') if search_id is None: return failure_response("no id entered") if id == search_id: return failure_response("cannot send a requ...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function accepts a friend request by verifying the session, checking if the friend exists and has a pending request, then adding them to the user's friends list and removing the pending request.
def accept_friend_request(friend_id): success, user = check_session() if not success: return user friend = User.query.filter_by(id=friend_id).first() if friend is None: return failure_response("friend user not found!") friend = user.applying_friends.filter_by(id=friend_id).first() ...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function rejects a pending friend request by removing the specified friend from the current user's applying friends list, validates the session and friend existence, and returns a success or failure response accordingly.
def reject_friend_request(friend_id): success, user = check_session() if not success: return user friend = User.query.filter_by(id=friend_id).first() if friend is None: return failure_response("friend user not found!") friend = user.applying_friends.filter_by(id=friend_id).first() ...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
The main task of the code is to retrieve all items from a specific event in a public list. It verifies user authentication, checks if the list and event exist, and returns serialized item data on success or appropriate error messages if any step fails.
def get_all_items(list_id, event_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_list event...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function retrieves an item by validating a user session, checking the existence of a public list, event, and item using provided IDs, and returns the item's serialized data on success or failure responses if any step fails.
def get_item_by_id(list_id, event_id, item_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_list...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
The main task of the code is to create a new list item within a specific event, validating user session, list/event existence, and required fields (completed, date, title) before saving the item to the database and returning a success response with the created item's data.
def create_item(list_id, event_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_list event =...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function edits an item in a public list by updating its title, date, or completion status based on incoming JSON data. It verifies the user's session, checks the existence of the specified list, event, and item, applies the updates if valid, and returns the modified item data or appropriate error messages if any r...
def edit_item_by_id(list_id, event_id, item_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_lis...
def check_session(): success, session_token = extract_token(request) if not success: return False, session_token user = get_user_by_session_token(session_token) if user is None: return False, failure_response("user not found!") if not user.verify_session(session_token): retu...
This function deletes an item from an event within a public list by verifying the session, checking the existence of the list, event, and item, then removing and committing the deletion. It returns success/failure responses based on validation steps.
def delete_item_by_id(list_id, event_id, item_id): success, user = check_session() if not success: return user event_list = user.public_lists.filter_by(public_list_id = list_id).first() if event_list is None: return failure_response("list not found!") event_list = event_list.public_l...
def get_all_results(self, link, data=True): """Gets all of the results by continuing to make API calls through the pagination information provided by Bitbucket Args: link (str): URL for desired API call data (bool, optional): Determines if the desired information to be returned is t...
The code retrieves all repositories for a given organization, then processes each repository to update aggregated data such as programming languages, repository counts, watcher counts, and follower counts, likely for analytics or categorization purposes.
def process_repos(self): """Obtain all repository data and then update the aggregated categories either on a per repo or per organization basis """ url = f'{self.url}/repositories/{self.org}?pagelen=100' repos = self.get_all_results(url, data=True) for repo in repos: self.update_languages...
def insert_title_and_description(parent, title, year): # Add title info title_info_node = etree.SubElement(parent, '{' + CMDP_NS_RECORD + '}TitleInfo', nsmap=CMD_NAMESPACES) title_node = etree.SubElement(title_info_node, '{' + CMDP_NS_RECORD + '}title', nsmap=CMD_NAMESPACES) title_node.text = f"{title} ...
The function `insert_component_content` populates metadata elements within a `components_root` structure using provided data. It inserts title, description, keywords, publisher, language, temporal coverage, countries, licenses, subresources, and metadata information by calling specialized helper functions. The inputs i...
def insert_component_content(components_root, title, year, edm_records): # Title and description insert_title_and_description(components_root, title, year) # Resource type insert_keywords(components_root, edm_records) # Publisher insert_publisher(components_root, edm_records) # Language info...
def set_metadata_headers(doc, collection_id, record_file_name): creator_header = xpath(doc, '/cmd:CMD/cmd:Header/cmd:MdCreator') if creator_header: creator_header[0].text = os.path.basename(__file__) creation_date_header = xpath(doc, '/cmd:CMD/cmd:Header/cmd:MdCreationDate') if creation_date_he...
This function generates a CMDI metadata file for a digital collection by populating a template with collection-specific metadata, resource proxies, and component records. It copies the template, inserts metadata headers, processes resource proxies from year files, loads EDM records from input maps, and populates compon...
def make_collection_record(file_name, template, collection_id, title, year_files, input_record_map, metadata_dir): cmdi_file = deepcopy(template) # Metadata headers set_metadata_headers(cmdi_file, collection_id, file_name) # Resource proxies resource_proxies_list = xpath(cmdi_file, '/cmd:CMD/cmd:R...
def load_emd_records(records_map, metadata_dir): edm_records = [] for identifier in records_map: file_name = records_map[identifier].get('file', None) if file_name is None: logger.error(f"No file name in records map for {identifier}") else: file_path = f"{metadata...
The function generates a CMDI record by populating an XML template with metadata and resource proxies from EDM records. It loads EDM metadata, sets headers, inserts resource proxies into the template's ResourceProxyList, and populates the Components section with title/year data and EDM records. Validation checks ensure...
def make_cmdi_record(record_file_name, template, collection_id, title, year, records_map, metadata_dir): cmdi_file = deepcopy(template) # load EDM metadata records edm_records = load_emd_records(records_map, metadata_dir) # Metadata headers set_metadata_headers(cmdi_file, collection_id, record_fil...
def parse_args(): current_platform = platform.system().lower() if "linux" in current_platform: package_os_selection = "linux" elif "darwin" in current_platform: package_os_selection = "mac" elif "windows" in current_platform: package_os_selection = "windows" else: pac...
The main task of the code is to perform artifact search or download operations in an Artifactory repository. It parses command-line arguments, authenticates via ArtifactoryHelper, and executes either a search (retrieving metadata) or download (fetching artifacts) based on the specified action. Parameters include produc...
def main(): args = parse_args() api = ArtifactoryHelper(args.username, args.password, verbose=args.verbose) if args.action == "search": meta = do_search( api=api, product=args.product, release=args.release, guid=args.guid, properties=args.p...
def parse_args(): ###################################################################################################### # Define a parser that contains the common options for different actions ###################################################################################################### common_...
This code defines a main function that interacts with an Artifactory repository via command-line arguments. It performs three operations: "drop" (deleting components), "search" (querying metadata), or "download" (retrieving artifacts). The function parses input arguments, initializes an Artifactory API helper, and exec...
def main(): args = parse_args() api = ArtifactoryHelper(args.username, args.password, verbose=args.verbose) if args.action == "drop": do_drop( api=api, product=args.product, release=args.release, component=args.component, component_dir=args...
def capturing_moves(self): return [cell for cell in self.__same_diagonal() if self.__pieces_on_way(*cell) == (0, 1) and is_empty(*cell)] def __same_diagonal(self): """Returns the list of cells that share the same diagonal with the piece. """ cells = [] for x, y in [(-...
The function determines available moves for a game piece by first checking for capturable moves (if any) and returning them. If none exist, it generates a list of valid diagonal moves where the path is unobstructed and the target cell is empty, based on the piece's position and board state.
def available_moves(self): for row in board: for cell in row: if (cell is not None and cell.color == self.color and cell.capturing_moves()): return self.capturing_moves() return [cell for cell in self.__same_diagonal() ...
def deselect(): if piece_to_continue is not None: return global selected_cell global selected_moves selected_cell = None selected_moves = [] redraw() def move(row_from, col_from, row_to, col_to): captured_piece, change_turn = logic.board[row_from][col_from].move_to(row_to, col_to) ...
This function handles cell clicks in a board game. It checks if a cell is selectable based on its position, processes moves by selecting/deselecting pieces, and triggers game-over logic if a winning move is made. It ensures valid moves, updates the game state, and manages turn-based interactions.
def click_cell(event): row, col = event.widget.row, event.widget.col if (row + col) % 2 == 0: deselect() return if logic.board[row][col] is None: if (row, col) in selected_moves: x, y = selected_cell color = logic.board[x][y].color move(x, y, ...
def intensity_counter(probes, nulls): """determines the intensity of probed vs unprobed images""" I_probed = np.zeros(len(probes)) I_nulls = np.zeros(len(nulls)) for ix in range(len(probes)): I_probed[ix] = np.sum(probes[ix]) for ix in range(len(nulls)): I_nulls[ix] = np.sum(nulls[ix...
The function `cdi_postprocess` processes time-series intensity images from a simulation to correct speckle patterns and create a dark hole in the image. It calculates speckle amplitude and phase using DM voltage maps, performs phase propagation simulations, and applies the CDI algorithm to subtract speckles. The CDI al...
def cdi_postprocess(fp_seq, cdi_zip, map_dir=None, plot=False, debug=False): """ this is the function that accepts the timeseries of intensity images from the simulation and returns the processed single image. This function calculates the speckle amplitude phase, and then corrects for it to create the dark ...
def record_layer_to_handshake_layer(stream): result = b'' while len(stream) > 0: assert 0x14 <= stream[0] <= 0x17 assert stream[1:3] == b'\x03\x03' assert 1 <= B2I(stream[3:5]) <= 2**14 assert len(stream) - 5 >= B2I(stream[3:5]) if stream[0] == 0x16: fragmlen ...
The code parses a TLS server response by extracting handshake messages, including the server hello, certificate, Diffie-Hellman parameters, and RSA signature. It converts these components into hexadecimal format for output, validates message completeness, and prints debug information for each extracted field, such as s...
def dissect_server_response(server_response): handshake_msgs = record_layer_to_handshake_layer(server_response) server_hello, handshake_msgs = extract_hsbody(0x02, handshake_msgs) certificate, handshake_msgs = extract_hsbody(0x0b, handshake_msgs) server_key_exchange, handshake_msgs = extract_hsbody(0x0c...
def send_last_two_messages(self, client: socket.socket, group_name: str): """Sends the last two messages in the group to the client. Args: client (socket.socket): The client socket. """ with self.lock: last_messages = self.groups[group_name].get_last_two_messages...
This function handles client connections by logging new connections, sending initial messages, managing group memberships, processing commands (e.g., joining/leaving groups, sending/retrieving messages), and maintaining active sessions. It broadcasts join/leave notifications, handles message routing between groups, and...
def handle_client(self, client: socket.socket, address): """Will handle a client connection. This function will run in a separate thread. Args: client (socket.socket): The client socket. address (str): The address of the client. """ self._logger.info( ...
def load_state(self, filename=None): assert self.loadfile is not None or filename is not None if filename is None: filename = self.loadfile d = read_file_to_dict(filename) self.on = bool(d['on']) self.mode = yl.PowerMode(int(d['mode'])) self.h = int...
The code initializes a group of bulbs by discovering them, filtering by specified names, and setting up initial states. It loads saved configurations if a file is provided, otherwise sets default brightness, color, and mode, then turns the bulbs on.
def __init__(self, group_name, names, loadfile = None): self.group_name = group_name self.names = names # store in case you want to reconnect or something idk self.loadfile = loadfile self.bulbs = [] bulb_dicts = yl.discover_bulbs() for bulb_dict in bulb_dicts: ...
def on_session_started(session_started_request, session): """ Called when the session starts """ print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId']) def on_launch(launch_request, session): """ Called when the user launches the skil...
This Lambda function handles Alexa skill requests by routing events (LaunchRequest, IntentRequest, SessionEndedRequest) to appropriate handlers, managing session start/ended states, and verifying the application ID to ensure requests originate from the correct skill.
def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ print("event.session.application.applicationId=" + event['session']['application']['applicationId']) "...
def check_keydown_events(event, settings, screen, ship, bullets): """as name indicated""" if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: # when space hit, create a new bullet and add it to the group fire_bul...
This function monitors user input events in a Pygame game, handling keyboard presses/releases, mouse clicks, and quit commands. It delegates key events to `check_keydown_events`/`check_keyup_events` and processes mouse clicks by checking if they hit the play button, triggering game logic like starting the game or updat...
def check_events(settings, screen, stats, sb, button, ship, aliens, bullets): # keeps monitoring keyboard and mouse input for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event, settings, screen, ship, bullets) elif event.typ...
def check_fleet_edges(settings, aliens): """check for the whole fleet to see if there is any alien out of edge""" for alien in aliens.sprites(): # makes it a list so that we can go through each element if alien.check_edges(): change_fleet_direction(settings, aliens) break def ship_hit(settings, stats, screen,...
This function updates alien movement and collision logic. It checks if aliens hit the screen edges, updates their positions, detects collisions between aliens and the ship (triggering a ship hit response), and checks if aliens have reached the bottom of the screen to handle game-over conditions.
def update_aliens(settings, stats, screen, sb, ship, aliens, bullets): """update this group of aliens""" check_fleet_edges(settings, aliens) aliens.update() # check if alien hit ship if pygame.sprite.spritecollideany(ship, aliens): ship_hit(settings, stats, screen, sb, ship, aliens, bullets) check_aliens_bott...
def _get_features_and_masks(self, folder, featurefiles=None, maskfiles=None): """ Returns for sample in folder all feature and mask files Parameters ---------- folder : str location of sample featurefiles : list of str, optional featurefiles to ret...
The main task of the code is to randomly sample a specified number of data samples (batch_size) from a dataset, optionally applying data augmentation. It handles edge cases like invalid data loading, ensures label inclusion when required, and extracts features/masks with specified parameters. The function returns a tup...
def random_sample(self, batch_size=1, dtype=None, tp=None, **kw): """ Randomly samples batch_size times from the data, using data augmentation if specified when creating the class Parameters ---------- batch_size : number of samples to draw dtype : datatype to return ...
def get_cluster_stats(cluster_list, flag_list): """ Compute frequency (p), entropy, and purity for each cluster. cluster_list: a list of cluster assignments (e.g., one column from the dataframe returned by 'get_cluster_assignments'). flag_list: a list or Series of binary labels (e.g., one column from t...
The function evaluates clustering performance by assessing how well cluster assignments predict binary labels. It calculates metrics like AUC (via ROC curves), mean entropy, and purity across clusters. It compares cluster-based predictions against a reference AUC, checks entropy improvements, and returns these metrics ...
def get_performance_for_clustering(cluster_list, flag_list): """ For the given cluster/flag pair, describe how well clusters predict binary labels (flags) using frequency of positive labels in clusters * compute an ROC curve (and AUC) using cluster label frequency as a score to predict the label ...
def mean_H(pattern, df): return h(counts(True, pattern, df), (counts(True, pattern, df) + counts(False, pattern, df))) def avg_clusters_H(pattern, df): cluster_h_sum = [] total_sum = [] for cluster in clusters(pattern, df): dfc = df.loc[(df.index == cluster)] trues = counts(True, pattern...
The function calculates entropy-related metrics for each unique pattern in the input DataFrame, including mean entropy, average cluster entropy, and cluster improvement entropy, then returns these metrics as a structured pandas DataFrame.
def pattern_delta_entropy(df): pattern_Hs = [] for pattern in np.unique(df.pattern): pattern_Hs.append({'pattern': pattern, 'mean_H':mean_H(pattern, df), 'avg_clusters_H': avg_clusters_H(pattern, df), 'cluster_improvement_H':clust...
def clear_empty_lines(lines): """ :param lines: :return: """ return_lines = [] for line in lines: if line.rstrip("\n") != "": return_lines.append(line.rstrip("\n")) return return_lines def search_line(lines_lower, keywords, name): office_hours_return = [] for k...
The code extracts specific events (office hours, mentor sessions, class times) from a text file by searching for keywords, processes the text to remove empty lines, and exports the identified information into a CSV file named 'export.csv'
def parse_text(text_file, class_name = "", export_file = "export.csv"): """ searches for keywords, key times/dates, key locations :param text_file: (txt file) :return: csv file """ in_text = open(text_file, "r", encoding="utf8") text_list = list(in_text) text_list_edit = clear_empty_lin...
def calculate_j_l_zeros(l, n): if l == 1: return np.array() zeros_init = np.array([[j * np.pi * (i == 0) for j in range(1, n+1+l)] for i in range(l+1)]) for i in range(1, l+1): for j in range(l+n-i): a = zeros_init[i-1][j] b = zeros_init[i-1][j+1] zeros_in...
This function calculates a modified spherical Bessel function coefficient $ a_{\text{tilde}}^{\text{sbf}} $ by combining a prefactor derived from Bessel function zeros, a scaled spherical Bessel function term, and a spherical harmonic component. It uses parameters $ l $, $ n $, $ d $, $ \alpha $, and $ c $ to compute t...
def a_sbf(l, n, d, alpha, c): z_l = calculate_j_l_zeros(l, n) z_ln = z_l[n-1] prefactor = np.sqrt(2 / (c**3 * j_l(l+1)(z_ln)**2)) a_tilde_sbf = prefactor * j_l(l)(z_ln / c * d) * Y_l_0(l)(alpha) return a_tilde_sbf
def deal_cards(self, player1, player2): player1.add_card(self.deck.deal()) player2.add_card(self.deck.deal()) player1.add_card(self.deck.deal()) player2.add_card(self.deck.deal()) def play_round(self, cur_game_player1, cur_game_player2, play_type, round_no): bet_raised = self.rai...
This code simulates a Texas Hold'em poker game by initializing a deck, dealing cards to two players, managing community cards in four rounds, handling betting with blinds, and checking for game completion after each round. The game proceeds through rounds 1-4, with a final showdown determining the winner if the game is...
def play(self,play_type): self.total_pot = 0 self.deck = StandardDeck() self.deck.shuffle_cards() no_rounds_completed = 0 # total_pot = 0 # if self.no_of_games % 2 == 0: # cur_game_player1 = self.list_of_players[0]; # cur_game_player2 = self.list_...
def drop_and_recreate_database(): db_engine = create_engine(database_utils.connection_string()) database_utils.BASE.metadata.drop_all(db_engine) database_utils.BASE.metadata.create_all(db_engine) session = sessionmaker(db_engine) return session() def parse_beneficiaries(): beneficiary_csv_list =...
The main task of the code is to load beneficiary and ESRD dialysis data into a database by dropping/recreating the database, parsing raw data, bulk-saving records, committing transactions, and printing the count of inserted beneficiaries and ESRD rows.
def load_data(event, context): # pylint: disable=unused-argument database_session = drop_and_recreate_database() beneficiaries = parse_beneficiaries() esrd_data = parse_esrd_dialysis_data() database_session.bulk_save_objects(beneficiaries) database_session.bulk_save_objects(esrd_data) databas...
def resizeImg(img): width = img.shape[1] height = img.shape[0] if width > 700: ratio = 500 / width resized = cv2.resize(img, None, fx = ratio, fy = ratio, interpolation = cv2.INTER_LINEAR) newWidth = 500 newHeight = int(height * ratio) return resized, ratio, newWidth...
The code processes an image to crop a receipt by detecting edges, identifying contours, extracting the longest contour, using Hough lines to find boundaries, calculating corners, and applying perspective transformation to isolate the receipt. It handles errors by returning the original image if issues arise during proc...
def receipt_crop(image, showProgress = False): try: originalImg = image.copy() image, ratio, newWidth, newHeight = resizeImg(image) height, width = image.shape[0], image.shape[1] # Convert to grayscale for further processing gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ...
def hanning2d(M, N): """ A 2D hanning window, as per IDL's hanning function. See numpy.hanning for the 1d description """ if N <= 1: return np.hanning(M) elif M <= 1: return np.hanning(N) # scalar unity; don't window if dims are too small else: return np.outer(np.hannin...
The function `PSD2` computes the **two-dimensional Power Spectral Density (PSD)** of an input image, optionally handling NaNs, applying windowing, and returning either the full 2D PSD, a radial profile (1D average power vs. spatial frequency), or azimuthal averages. It supports cross-spectral analysis with a second ima...
def PSD2(image, image2=None, oned=False, fft_pad=False, real=False, imag=False, binsize=1.0, radbins=1, azbins=1, radial=False, hanning=False, wavnum_scale=False, twopi_scale=False, **kwargs): """ Two-dimensional Power Spectral Density. NAN values are treated as zero. image2 -...
def test_merge_single_child_clades(tree_filename): tree1 = Phylo.read(tree_filename, 'newick') tree2 = Phylo.read(tree_filename, 'newick') # Add branch lengths for n in tree1.find_clades(): n.branch_length = 1. # Add branch lengths for n in tree2.find_clades(): n.branch_length ...
The main task of the code is to test tree manipulation algorithms by running three specific operations—merging single-child clades, splitting polytomies, and pruning leaves—on a given tree file. The random seed ensures reproducible test results.
def test_tree_algs(tree_filename): random.seed(1) test_merge_single_child_clades(tree_filename) test_split_polytomies(tree_filename) test_prune_leaves(tree_filename)
def get_data_from(request_body: bytes) -> dict: """Deserializes request body. JSONDecodeError is raised if this method cannot deserialize the argument. """ data = loads(request_body) return data def __get_resource_obj(self, resource_type, resource_id): Model = self.__get_enabled_resource_mod...
This code handles a POST request by parsing incoming data to retrieve a resource, creating or activating an existing generic object, and returning a JSON response with the serialized data if successful, or a bad request error if parsing fails.
def post(self, request): try: data = get_data_from(request.body) resource_type = data.get('resourceType') resource_id = data.get('resourceId') resource_obj = self.__get_resource_obj(resource_type, resource_id) except (JSONDecodeError, ValueError, Attribute...
def proper_pkt(self, pkt): if CPUMetadata in pkt: return True if IP in pkt: port = self.pwospf.port_for_ip(pkt[IP].dst) if port != None and pkt[IP].dst == str(self.pwospf[port]['ipaddr']): return True print("%s: received improper packet %s"...
This function processes incoming packets by validating their structure and metadata. It filters out invalid or CPU-originated packets, then routes valid packets to specific handlers based on their metadata reason field (e.g., ARP requests/replies, OSPF packets, or error cases). It ensures only expected packet types are...
def handlePkt(self, pkt): if not self.proper_pkt(pkt): pkt.show2() print('Should only receive packets from switch with special header') assert False if CPUMetadata not in pkt: print("received packet for the router's IP %s" % pkt[IP].dst) retur...
def compute_output_delta(self, out, activation): # if activation == "sigmoid": # delta_output = (self.y - out) * (self.__sigmoid_derivative(out)) # if activation == "tanh": # delta_output = (self.y - out) * (self.__tanh_derivative(out)) # else: # delta_output ...
This code performs a backward pass in a neural network by computing error deltas for each layer, starting from the output layer and propagating backward through hidden layers (layer 2 and layer 1), using the provided activation function to calculate gradients for weight updates during training.
def backward_pass(self, out, activation): # pass our inputs through our neural network self.compute_output_delta(out, activation) self.compute_hidden_layer2_delta(activation) self.compute_hidden_layer1_delta(activation)
def create_bucket(self) -> str: name = self.get_random_bucket_name() self.s3c.create_bucket(Bucket=name) self.assert_bucket_exists(name) assert name not in self.buckets self.buckets.append(name) return name def get_random_object_name(self) -> str: return self.get_...
This test case verifies that attempting to upload a part to a non-existent multipart upload raises a 'NoSuchUpload' error. It creates a bucket, generates random object/upload IDs, initiates a multipart upload, and tries to upload a part. The test expects the operation to fail with the specified exception, confirming pr...
def test_dne_upload_multipart(self): bucket_name = self.create_bucket() objname = self.get_random_object_name() upload_id = self.get_random_upload_id() upload = self.s3.MultipartUpload(bucket_name, objname, upload_id) part = upload.Part(1) # type: ignore has_error = Fals...
def create_bucket(self) -> str: name = self.get_random_bucket_name() self.s3c.create_bucket(Bucket=name) self.assert_bucket_exists(name) assert name not in self.buckets self.buckets.append(name) return name def get_random_object_name(self) -> str: return self.get_...
This test case verifies multipart upload and download functionality by uploading a 100MB file to an S3 bucket using a TransferConfig with 10MB chunk sizes, then downloading it and comparing MD5 hashes to ensure data integrity.
def test_multipart_upload_download(self): bucket_name = self.create_bucket() objname = self.get_random_object_name() objsize = 100 * 1024**2 # 100 MB objpath, md5 = self.gen_random_file(objname, objsize) cfg = boto3.s3.transfer.TransferConfig( multipart_threshold=10...
def create_bucket(self) -> str: name = self.get_random_bucket_name() self.s3c.create_bucket(Bucket=name) self.assert_bucket_exists(name) assert name not in self.buckets self.buckets.append(name) return name def get_random_object_name(self) -> str: return self.get_...
This test case verifies the correctness of multipart upload and download processes. It creates a bucket, generates a 100MB object split into 10MB parts, initiates a multipart upload, uploads each part with ETag verification, completes the upload, downloads the object using transfer config, and validates data integrity ...
def test_upload_multipart_manual(self): bucket_name = self.create_bucket() objname = self.get_random_object_name() objsize = 100 * 1024**2 # 100 MB partsize = 10 * 1024**2 # 10 MB mp = self.gen_multipart(objname, objsize, partsize) print( f"generated multipa...
def create_bucket(self) -> str: name = self.get_random_bucket_name() self.s3c.create_bucket(Bucket=name) self.assert_bucket_exists(name) assert name not in self.buckets self.buckets.append(name) return name def get_random_object_name(self) -> str: return self.get_...
This test verifies the functionality of listing parts in an ongoing multipart upload. It creates a bucket, initiates a multipart upload, uploads a single part, and checks if the part is correctly listed with attributes like ETag, size, and part number. The test ensures the API returns the expected part details and conf...
def test_list_ongoing_parts(self): bucket_name = self.create_bucket() objname = self.get_random_object_name() objsize = 100 * 1024**2 # 100 MB partsize = 10 * 1024**2 # 10 MB mp = self.gen_multipart(objname, objsize, partsize) print( f"generated multipart up...
def refillClass(self, class_i): self.available_pixels[class_i] = self.pixels_per_class[class_i][:] random.shuffle(self.available_pixels[class_i]) def addVariant(self, variant): if variant in list(self.variant_views.keys()): return self.variant_views[variant] = HSICubeImageViews(self.img, variant, self.win_si...
This code initializes a hyperspectral image processor by mapping each pixel to its class label and coordinates, organizing labeled pixels into class-specific lists, and setting up data structures for transformation and sampling. It pads the input image, creates pixel objects with spatial information, tracks class distr...
def __init__(self, hsi_image, ground_truth, window_size, saved_transforms_path): self.img = paddingImage(hsi_image.reshape((*hsi_image.shape, 1))) self.gt = ground_truth self.pixels = [] self.labeled_pixels = [] self.pixels_map = [] self.linear_map = [] class_labels, counts = np.unique(self.gt, return_cou...
def broadcast(messageToClient, sender=None): if type(messageToClient) != bytes: # If the message is not bytes PRINTER.debugPrint("Message to client is not bytes, encoding to bytes for transfer.") messageToClient = messageToClient.encode(FORMAT) # Encodes the message to bytes checkClientsAlive(...
The code manages a multi-round chatroom where each round involves broadcasting a randomly selected word or user-defined topic to connected clients, collecting and broadcasting their responses, and proceeding to subsequent rounds until a maximum number of rounds is reached. It handles both interactive (user-defined topi...
def chatRoom(client, roundNumber, maxRounds=MAXROUNDS, chatAcceptingConnections=chatAcceptingConnections): try: # Tries to send a message to the client PRINTER.debugPrint("No longer accepting connections for the current round") chatAcceptingConnections.set_not_accepting() # Sets the chatAcceptingCo...
def checkBotname(client, chatAcceptingConnections=chatAcceptingConnections): if checkClientAlive(client): # Checks if the client is alive PRINTER.debugPrint("Sent command !RetrieveBotname to client " + str(client)) client.send("!RetrieveBotname".encode(FORMAT)) # Sends the RetrieveBotname command ...
The code sets up a server to await a specified number of bots (STARTWITH) to connect. It handles incoming connections, validates botnames, and manages exceptions like timeouts. Once all bots are connected, it initiates a chatroom, spawns threads for continuous listening and chatting, and maintains operations until inte...
def main(): while True: try: print(PRINTER.centerPrint(f"The server is waiting for {STARTWITH} bots to connect...")) while len(clients) < STARTWITH: # While the has less than the STARTWITH number of bots try: PRINTER.debugPrint("Listening for new...
def print_field(self): l = [] for i in range(int(field_side/field_division)+1): l+=[[0, field_division*i, field_side, field_division*i]] for i in range(int(field_side/field_division)+1): l+=[[field_division*i, 0, field_division*i, field_side]] self.print_lines(...
The code updates a graphical interface by clearing the canvas and redrawing elements like the field, map, found map, and robot position, then refreshing the display with `self.root.update()`.)
def update(self, pos, m): self.canvas.delete("all") # delete the old polygon self.print_field() self.print_map() self.print_found_map(m) self.print_bot(pos) self.root.update()
def print_field(self): l = [] for i in range(int(field_side/field_division)+1): l+=[[0, field_division*i, field_side, field_division*i]] for i in range(int(field_side/field_division)+1): l+=[[field_division*i, 0, field_division*i, field_side]] self.print_lines(...
This code updates a graphical interface by clearing the canvas, redrawing the field and map, printing measurement lines, and positioning one or two bots based on input parameters, then refreshing the display.
def update(self, pos, lines, pos2, lines2): self.canvas.delete("all") # delete the old polygon self.print_field() self.print_map() self.print_measures(lines) self.print_bot(pos) if (pos2): self.print_bot_2(pos2) if (lines2): self.print_mea...
def apply_no_full_cube_rotation_optimization(moves): rots = {'X', 'Y', 'Z', 'Xi', 'Yi', 'Zi'} for i in range(len(moves) - 1, 0, -1): if moves[i] not in rots: continue rot = moves[i] moves[i:] = _unrotate(rot, moves[i + 1:]) def apply_repeat_three_optimization(moves): cha...
The code optimizes a sequence of Rubik's cube moves by normalizing notation (uppercase, replacing apostrophes with 'i', handling '2' suffixes), applying multiple optimization algorithms to simplify the sequence, and restoring original notation. It aims to standardize and reduce move complexity for efficiency.
def optimize_moves(moves): moves = list(moves) result = [] for move in moves: move = move.upper() move = move.replace("'", 'i') if '2' in move: move = move.replace('2', '') result.append(move) result.append(move) apply_no_full_cube_rotation_op...
def _shift_inout_buf(self, bytes_out): """ Send out a buffer of bytes on cmd_pin, while reading in a same-sized buffer on dat_pin """ inbuf = [0] * len(bytes_out) for i, bout in enumerate(bytes_out): inbuf[i] = self._shift_inout_byte(bout) _delay_m...
This function sends a command buffer to a controller, reads a variable-length response, and returns the exact response buffer or an invalid 3-byte buffer. It first shifts out the initial 3 bytes, checks if the response is valid, and if so, processes remaining command bytes and calculates needed padding to complete the ...
def _autoshift(self, cmd_out): """ Send out a command buffer to the controller, while also reading in a variable-length response buffer Returns the exact size buffer returned by the controller, or the invalid '0xff' 3-byte initial read buffer """ cmdlen = len(cmd_...
def _attention(self): """Select joystick for reading/writing""" self.att_pin.value = False # active low CS pin _delay_micros(_ATTN_DELAY_MICROS) def _autoshift(self, cmd_out): """ Send out a command buffer to the controller, while also reading in a variable-length respon...
This function attempts to switch a device to configuration mode by repeatedly sending commands (via _autoshift) and checking for valid/config replies. It returns True if a valid config response is received within a timeout, otherwise False after timing out.
def _change_config_mode(self, outbuf): start_t = time.monotonic() while (time.monotonic() - start_t) < _COMMAND_TIMEOUT_SECS: self._attention() inbuf = self._autoshift(outbuf) self._no_attention() if _is_valid_reply(inbuf) and _is_config_reply(inbuf): ...
def _attention(self): """Select joystick for reading/writing""" self.att_pin.value = False # active low CS pin _delay_micros(_ATTN_DELAY_MICROS) def _autoshift(self, cmd_out): """ Send out a command buffer to the controller, while also reading in a variable-length respon...
This function attempts to enable a controller mode by repeatedly sending commands and verifying responses. It returns True if three consecutive valid replies are received within a timeout, indicating successful mode activation. If no valid replies are received within the timeout, it returns False. The function does not...
def _try_enable_mode(self, outbuf): """ Attempt to enable a controller mode. Returns True if no timeout. If controller does not support mode, this function does NOT verify it """ good_reply_count = 0 start_t = time.monotonic() while (time.monotonic() - start_t) < ...
def _attention(self): """Select joystick for reading/writing""" self.att_pin.value = False # active low CS pin _delay_micros(_ATTN_DELAY_MICROS) def _autoshift(self, cmd_out): """ Send out a command buffer to the controller, while also reading in a variable-length respon...
The code reads input from a controller, processes it with rumble support if enabled, validates the response, and exits configuration mode if needed, returning the processed buffer.
def read(self): """Read from the controller. Must be called frequently. Called by update().""" self._attention() if self.enable_rumble: pollr = list(_poll_rumble) pollr[3] = self.motor1_level pollr[4] = self.motor2_level inbuf = self._autoshift(pol...
def MoveGen(state): neighbors=[] for i in range(len(state)): for j in range(len(state)): if i!=j: if move_possible(state[i],state[j]): a,b=colours_moveable(state[i]) if a==0 and b==4: continue ...
The function `kids(state)` calculates a value based on the number of neighbors generated from a given state and their associated evaluations. It initializes a value as twice the number of neighbors, then iteratively adds results from `pairs(neighbor)` and `f_h(neighbor)` for each neighbor. The main task is to compute a...
def kids(state): neighbors=MoveGen(state) val=2*len(neighbors) for neighbor in neighbors: val+=pairs(neighbor)+f_h(neighbor) return val
def f_h(state): if goal_test(state): return 100 else: return 0 def pairs(state): val=0 for arr in state: for i in range(len(arr)-1): if arr[i]==arr[i+1]: val+=2 else: val-=1 return val def kids(state): neighbors=Move...
The code defines a heuristic function that returns the negative sum of three components—f_h, pairs, and kids—evaluated on a given state, likely used in optimization or search algorithms to prioritize states with higher combined values of these components.
def heuristic(state): return -(f_h(state)+pairs(state)+kids(state))
def goal_test(state): for arr in state: k=arr[0] for i in range(1,len(arr)): if arr[i]!=k: return False return True def MoveGen(state): neighbors=[] for i in range(len(state)): for j in range(len(state)): if i!=j: if move_po...
The code implements best-first search to find the shortest path from an initial state to a goal state. It uses a priority queue sorted by heuristic values, tracks visited states, and reconstructs the path by backtracking through parent pointers stored in a dictionary.
def best_first_search(initial_state): start_tuple = tuple(tuple(x) for x in initial_state) priority_queue = deque([{start_tuple: [None,0]}]) visited = {} path=[] while priority_queue: current_state = priority_queue[0] del priority_queue[0] for state, arr in current_state.item...
def load_sites(): # function opens txt or csv and writes contents to dictionary. print("loading site information... ") f = open("sites.txt", "r") print(f.read()) sites = f.read() def new_site(): # function updates the 'sites' dictionary from user input new = {} new_name = input("Please enter t...
The code defines a main loop for a command-line interface, continuously prompting the user for actions like "new", "set", "dhcp", or "?". It executes corresponding functions to manage sites, with no exit condition. The loop loads initial site data, processes user input, and handles available commands for site configura...
def main(): # main loop for the program, currently no exit condition. load_sites() print("Starting...") while True: action = input("Hello, what would you like to do?") if action == "?": print("available commands are: new, set, query, dhcp ") elif action == "new": ...
def clr(color): out(color) def out(line): stdout.write(str(line)) def reset(): clr(RESET)
The function `outclr` prints a given `line` with a specified `color` and then resets the color formatting. It uses `clr(color)` to set the color, `out(line)` to display the text, and `reset()` to revert to default color settings.
def outclr(line, color): clr(color) out(line) reset()
def outred(line): outclr(line, RED) def outgreen(line): outclr(line, GREEN) def out(line): stdout.write(str(line))
This function processes a diff text, coloring lines starting with '-' in red, '+' in green, and conditionally displaying lines starting with 'i' or ' ' based on the show_equal_ignored flag, while defaulting to outputting other lines unchanged.
def outdiff(difftxt, show_equal_ignored = False): for line in difftxt.splitlines(True): if line[0] == '-': outred(line) elif line[0] == '+': outgreen(line) elif line[0] in ['i', ' ']: if show_equal_ignored: out(line) else: ...
def to_log_entry(self, key: bytes, value: Value) -> str: return f'{key.hex()}, {self.serialize_value(value)}\n' def memtable_wal(self) -> AppendLog: return AppendLog.instance(self.memtable_wal_path()) def serialize_value(self, value: Value) -> str: j_value = deepcopy(value) j_value['valu...
This method inserts a key-value pair into a database by updating the memtable or flushing it to disk if the size threshold is exceeded, while logging changes to a WAL. It checks if the key exists in the memtable, updates it if present, or adds it otherwise. When the memtable exceeds its capacity, it flushes data to dis...
def db_set(self, key: bytes, value: Value) -> None: log = self.to_log_entry(key, value) node = self.memtable.find_node(key) if node: self.memtable_wal().write(log) node.value = value return additional_size = len(key) + len(self.serialize_value...
def chron_app_dates(date_index): go_next = True selected = False # for date in app_dates: -> we don't need the for loop anymore because we are using conditional statments and function calls for the program if select_date(selected, go_next) == True: chosen_app_date = app_dates[date_index] ...
The function prompts the user to select a date list (app, personal, or all), validates the input, and returns the corresponding chronological date list function. If input is invalid, it recursively reprompts until a valid choice is made.
def select_list(): date_index = 0 choose_list = input("Which list of dates would you list to search? ").lower().strip() if choose_list == app_dates_list: return chron_app_dates(date_index) elif choose_list == my_dates_list: return chron_my_dates(date_index) elif choose_list...
def disconnect_clients(): global clients_address clients_address = [] add_log("All clients were disconnected.") def rewind_video(): global video_finished, frame_queue if video_finished: start_read_video() video_capture.set(cv2.CAP_PROP_POS_FRAMES, 0) video_finished = False def send_p...
The main task of the code is to stream video frames to connected clients by encoding each frame into base64, splitting it into data chunks, and sending them sequentially with packet metadata. It handles frame retrieval, chunking, packet sequencing, and client communication, while managing video rewinding and client dis...
def handle_clients(): global video_fps frame_number = 0 while len(clients_address) > 0: if video_finished and frame_queue.empty(): disconnect_clients() rewind_video() break # Get a frame from the queue, converts to jpeg and then encode to base64 ...
def handle_args(): global delay, media_path, port parser = argparse.ArgumentParser( prog='Server', description='Server that sends media to clients' ) parser.add_argument('-d', '--delay', type=float, help='Defines a time interval, in milliseconds, for sending pac...
The main task of the code is to set up a UDP server for streaming media. It handles signals, binds to a specified port, checks media file existence, initiates video reading, spawns a thread to send media to clients, and listens for incoming client connections. The server socket is closed in the finally block to ensure ...
def main(): global server try: signal.signal(signal.SIGINT, signal_handler) handle_args() server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind((SERVER, port)) check_file_existence(media_path) start_read_video() thread = threading.Thre...
def add_log(message: str): print(f"[{get_timestamp()}]: {message}") def unpack_packet(packet): global video_fps, total_frames header = packet[:HEADER_SIZE] frame_number, sequence_number, fps, payload_size, frames_count = struct.unpack( HEADER_FORMAT, header) frame_data = packet[HEADER_SIZE:]...
This function listens for video data packets from a server, unpacks each received packet to extract frame details (number, sequence, FPS, payload), logs the information, and appends the frame data to a structure. It runs continuously until the video transmission completes.
def listen_from_server(): global video_fps add_log("Listening to server...") while not video_finished: packet, address = client.recvfrom(MAX_PACKAGE_SIZE) add_log(f"Received a package from {address}") frame_number, sequence_number, video_fps, payload_size, frame_data = unpack_pack...
def handle_args(): global server_ip, server_port parser = argparse.ArgumentParser( prog='Client', description='Client that receives media from server' ) parser.add_argument('-ip', '--server-ip', type=str, help='Defines the server ip.') parser.add_argument('...
The code sets up a UDP socket for client-server communication, subscribes to data streams, initiates media playback, listens for incoming server data, generates reports, and ensures proper socket closure. It handles keyboard interrupts and maintains resource cleanup via a finally block.
def main(): global client try: signal.signal(signal.SIGINT, signal_handler) handle_args() client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) subscribe() start_player() listen_from_server() show_report() finally: close_socket()
def pdf_to_df(fpath, source_id): from PyPDF2 import PdfReader with open(fpath, "rb") as f: reader = PdfReader(f) texts = [] for i, page in enumerate(reader.pages): texts.append((i+1, page.extract_text())) df = pd.DataFrame(texts, columns=['page_number', 'text']) df['text'...
This function converts a PDF file into embeddings by reading the file, storing its binary data in a database, processing the content into a structured DataFrame, generating embeddings, and inserting the processed data along with metadata into an embeddings table. It returns the total token count or an error status.
def pdf_to_embeddings(fname, user_id, source_id): fname = os.path.splitext(os.path.basename(fname))[0] raw_path = f'users/{user_id}/files/{fname}.{DTYPE_PDF}' n_tokens = 0 try: with open(raw_path, 'rb') as f: data = f.read() add_blob_q = '''INSERT INTO blobs (source_id,...
def getData(): thetaFile = "theta.csv" muFile = "mu.csv" sigmaFile = "sigma.csv" rdat = np.genfromtxt("ndat.csv", delimiter = ',') #rdat = rdat[0:100] MU = np.genfromtxt(muFile, delimiter = ',') SIGMA = np.genfromtxt(sigmaFile, delimiter = ',') THETA = np.genfromtxt(thetaFile, delimiter...
The main task of the code is to compare two datasets (FDAT and RDAT) using ecological analysis metrics. It calculates Shannon diversity, species distribution, MAD (Mean Absolute Deviation), closest neighbor distances, and distance distributions to evaluate differences between the datasets. The code retrieves data via `...
def main(): #Returns ndat.csv as matrix as well as fake data with FDAT, RDAT = getData() compareShannon(RDAT, FDAT) calcSpeciesDist(FDAT, RDAT) compareMAD(RDAT, FDAT) compareClosestNeighbor(RDAT, FDAT) compareDistanceDist(RDAT, FDAT) return 0
def _load_genome_informations(self) -> Dict: """Return a dictionary with genome informations if available. Raises ------ RuntimeWarning: If genome informations are not available locally. """ try: compress_json.load(self._genome_informa...
(The code initializes a `Genome` object by downloading and caching genomic data from the UCSC Browser based on an assembly ID. It filters chromosomes by excluding specified substrings, checks for available genomes, and raises errors if no valid chromosomes remain. It also sets up nucleotide mappings and triggers data d...
def __init__( self, assembly: str, chromosomes: Tuple[str] = None, filters: Tuple[str] = ("chru", "chrmt", "scaffold", "contig", "super", "chrbin", "random", "hap", "alt", "fix"), verbose: bool = True, cache_directory: str = "genomes" ): """Instantiate a new G...
def get_new_results_folder(): #data_output_path = cf.resultsFolderPath + "/" + get_current_simulation_name() + "-avd" + str(cf.av_density) + "-ed" + str(cf.ehmi_density) + "-" + time.strftime("%Y%m%d-%H%M%S") #data_output_path = os.path.join(cf.resultsFolderPath,"{}-avd{}-ed{}-{}".format(get_current_simulation_...
The function initializes SUMO simulations by configuring binaries, scenario paths, multithreading options, and vehicle parameters. It sets up result folders, handles verbosity levels, and runs simulations either once or in nested loops to test varying vehicle densities and defiance levels, iterating through scenarios t...
def init_sim(): if not cf.sumo_GuiOn or options.nogui: sumo_binary = checkBinary('sumo') else: sumo_binary = checkBinary('sumo-gui') global scenario if options.scenario: cf.sumocfgPath = cf.scenario_dict[options.scenario] scenario = options.scenario else: s...
def __create_gui() -> PySimpleGUI.Window: """ Creates GUI to run during the simulation. Do not call this function outside of this file. """ global women_crossed global women_ncrossed global men_crossed global men_ncrossed global other_crossed global other_ncrossed global healthy...
The main task of the code is to run and manage a GUI during a simulation, updating real-time data (e.g., timestep, pedestrian/vehicle counts, crossing information) and handling user interactions like stopping, pausing, or quitting the application. It creates the GUI if not already initialized, updates visual elements b...
def run_gui(): """ Runs GUI during simulation. """ global gui global current_traci_step if gui is not None: gui.Element('-timestep-').update( "Timestep: " + str(current_traci_step) + " (Update delay: " + str(cf.update_delay) + " steps)") if gui is None: gui = __c...
def __create_cgui() -> PySimpleGUI.Window: """ Creates config GUI to run prior to the simulation. """ choose_scenario_table = list() for elem in cf.scenarios: choose_scenario_table.append(elem[0]) cguiScenTable = PySimpleGUI.Table(values=choose_scenario_table, headings=[""], ...
The main task of the code is to run a configuration GUI for a simulation, allowing users to add multiple configurations to a loop, adjust parameters, and trigger simulation starts. It handles GUI events, updates configuration settings, validates numeric inputs, and returns control flow indicators like 'sim_start' or 'c...
def run_cgui() -> str: """ Runs config GUI that is displayed prior to the simulation. """ global in_loop global current_sim global numeric_error_msg global num_of_loops global cgui if cgui is None: cgui = __create_cgui() while True: event, values = cgui.read(time...
def utility_function(board, player_on_move): len_board = len(board) val = 0.0 cnt1 = 0 cnt2 = 0 for i in range(len_board): for j in range(len_board): if (board[i][j]==1): # pawn player 1 val += find_distance((i,j), (len_board-1,len_board-1)) if ...
This code implements the Minimax algorithm with Alpha-Beta pruning for a board game, evaluating optimal moves for a player. It recursively explores possible moves, applies heuristic checks for win conditions, and prunes non-critical branches to enhance efficiency. The function returns the best move and its associated v...
def minimax(depth, alpha, beta, is_max, player_on_move, board, using_local_search=True): cnt[depth]+=1 # basis if (depth==3): return utility_function(board, player_on_move), None best_val = float("-inf") if is_max else float("inf") best_move = None len_board = len(board) # iter...
def hide_possible_moves(self): for i in range(self.board_size): for j in range(self.board_size): if self.halma.board[i][j].kind == 0: self.tile_labels[i][j].config(fg=self.get_tile_color(i, j)) def show_possible_moves(self): x, y = self.selected_tile ...
This function handles tile selection and movement in a Halma game. It allows a human player to select/deselect tiles, validate moves, update the UI, and trigger the bot's turn if the move is valid. It checks for existing selections, ensures moves follow game rules, and updates the board state accordingly.
def on_click_tile(self, e, x, y): if self.winner: return if self.selected_tile == (x, y): # deselect tile self.hide_possible_moves() self.tiles[x][y].config(bg=DARK_GRAY) self.selected_tile = (-1, -1) elif self.selected_tile == (-1, -1): # select...