dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def create_first_generation(self, n_workers=None, parallel_type="processing"): self.create_initial_generation() self.calculate_population_fitness(n_workers=n_workers, parallel_type=parallel_type) self.rank_population() def create_next_generation(self, n_workers=None, parallel_type="processing"):...
This code implements a genetic algorithm (GA) to optimize a problem by iteratively generating and evaluating generations of candidate solutions. It initializes the first generation, tracks fitness metrics (average, standard deviation), adjusts mutation factors adaptively, and stops early if convergence is detected. Eac...
def run(self, n_workers=None, parallel_type="processing"): """solve the GA""" self.create_first_generation(n_workers=n_workers, parallel_type=parallel_type) # for visualisation fits = [ind.fitness for ind in self._cur_generation] avg = np.mean(fits) std = np.std(fits) ...
def __load_dictionaries(self): """ Load the data annotations """ train_dataset_dicts = load_json(file_path=os.path.join(self.dictionaries_path, self.dictionaries_names[0])) val_dataset_dicts = load_json(file_path=os.path.join(self.dictionaries_path, self.dictionaries_names[1])) ...
The `train` method loads or creates dictionaries, logs dataset sizes, registers datasets, configures training settings, initializes a trainer (with data augmentation or default), adds validation hooks, adjusts hook order, resumes training, and executes the training process, returning the result. It handles both standar...
def train(self): """ Method to load and retrain the pre-trained model """ if check_files(self.dictionaries_names, self.dictionaries_path) and self.load_pre_existing_dicts: self.__load_dictionaries() else: self.__save_dictionaries() ...
def get_providers(self, record: LogRecord) -> list[AbstractProvider]: # noqa ARG002 return self.providers def get_provider_attributes(self, index: int, provider: AbstractProvider, record: LogRecord) -> Optional[dict]: try: provider_data = provider.get_attributes(record) except Excep...
The main task of the code is to aggregate and format attributes from a log record into a structured dictionary. It collects provider-specific data, standard fields like timestamp, status, message, and location, and optionally includes error details, stack traces, and formatter errors. The result is a consolidated dicti...
def get_attributes(self, record: LogRecord) -> dict: result = {} for index, provider in enumerate(self.get_providers(record)): provider_data = self.get_provider_attributes(index, provider, record) if provider_data is not None: result.update(provider_data) ...
def selectBank(): reset() item = pyautogui.locateCenterOnScreen("bank.png") pyautogui.click(item.x,item.y + 20) time.sleep(3) def bankItems(): move("right",3) moveMouse([654, 262]) pyautogui.click() time.sleep(1) moveMouse([519, 57]) pyautogui.click() def reset(): moveMo...
The main task of the code is to automate a mining and banking cycle. It repeatedly selects a bank, retrieves items, resets the process, transports resources from the mine to the bank, digs rocks, returns to the bank, and reselects the bank to manage items, creating a loop for continuous resource extraction and storage.
def main(): selectBank() bankItems() while True: reset() bankToMine() digRocks() mineToBank() selectBank() bankItems()
def calc_transform(dh_params): """Calculate base to end effector transform.""" joint_count = 0 while f'joint_{joint_count + 1}' in dh_params.keys(): joint_count += 1 trans_matrix = np.identity(4) tool_length = 0 if 'tool_length' in dh_params.keys(): tool_length = dh_params['tool...
The function `servo_calcs` computes the required joint angles to achieve a target Cartesian position and orientation using iterative servoing. It adjusts joint states via Jacobian-based inverse kinematics, minimizing the difference between the current and goal positions/orientations within specified tolerances. The alg...
def servo_calcs(dh_params, goal_pos, joint_states, max_iter=500, pos_tol=1e-5, rot_tol=1e-3, set_last=0, joint_limits=0): """ Calculate the joint states for a given cartesian position with servoing in cartesian space. - param goal_pos: target cartesian position with roll-pitch-yaw orien...
def servo_calcs(dh_params, goal_pos, joint_states, max_iter=500, pos_tol=1e-5, rot_tol=1e-3, set_last=0, joint_limits=0): """ Calculate the joint states for a given cartesian position with servoing in cartesian space. - param goal_pos: target cartesian position with roll-pitch-yaw orien...
The main task of the code is to compute valid joint configurations to reach a goal position using multiple servoing methods, prioritizing solutions that avoid joint limits. It first attempts a standard calculation, then iteratively re-runs with alternative joint limit handling strategies (reducing DOF, goal vector prio...
def servo_all_methods(dh_params, goal_pos, joint_states, set_last=0): """Run servo_calcs with 3 different methods (if necessary) to avoid joint limits.""" j_s = joint_states.copy() servo_joints = servo_calcs(dh_params, goal_pos, j_s, set_last=set_last)[0] process_result(servo_joints) # Check joint ...
def player(board): """ Returns player who has the next turn on a board. """ if (board == initial_state()): return 'X' count = {'X': 0, 'O': 0} for row in board: if row.count(None) < len(row): count['O'] += row.count('O') count['X'] += row.count('X') re...
The code implements the minimax algorithm to determine the optimal action for the current player on a tic-tac-toe board. It recursively evaluates all possible moves, prioritizing immediate wins, then selects the move maximizing/minimizing utility based on the player's turn, ensuring optimal strategy against an ideal op...
def minimax(board, p=None): """ Returns the optimal action for the current player on the board. """ p = p or player(board) if (terminal(board)): return None else: possibilities = actions(board) outcome = {} for places in possibilities: next_move = resu...
def _legalize_move_um(self, channel, move_um, relative): if self.verbose: print('%s(ch%s): requested move_um = %0.2f (relative=%s)' % ( self.name, channel, move_um, relative)) if relative: move_um += self.position_um[channel] limit_um = self._position_limi...
This function moves a specified channel to a target position in micrometers. It validates the move, converts the position to encoder counts, executes the movement, waits for completion if required, and returns the legalized position.
def move_um(self, channel, move_um, relative=True, block=True): legal_move_um = self._legalize_move_um(channel, move_um, relative) if self.verbose: print('%s(ch%s): moving to position_um = %0.2f' % ( self.name, channel, legal_move_um)) encoder_counts = self._um_to_enc...
def check_active_nodes(self): actual_time = time.time() active_nodes = self.receiver.get_active_nodes() if active_nodes is None: return for address, node in active_nodes.items(): if actual_time - node.time > MAX_OUTAGE_TIME: logging.info("Removin...
The code manages node roles and color assignments in a distributed system. It continuously checks active nodes, promotes itself as leader if applicable, coordinates color assignments when all nodes are colored, and handles non-leader states by seeking a leader or requesting colors. The loop ensures node status monitori...
def run(self): while self.runningFlag: # check last pings for possible node removal self.check_active_nodes() if self.actual_node.promotedAsLeader: # logging.debug("Im boss!") active_nodes = self.receiver.get_active_nodes() if...
def fill(self, value, **kwargs): self.led.brightness = kwargs.get("brightness", 1) delay = kwargs.get("delay", 0) self.led.fill[0] = value self.led.write() sleep(delay) def off(self): self.fill(BLACK) def warning(self): for _ in range(10)...
The code's main task is to blink a display by repeatedly turning it on with a specified color and delay, then turning it off, repeating this sequence a number of times defined by the 'value' parameter, while handling exceptions by triggering a warning and exiting if an error occurs.
def blink(self, color, value): for _ in range(value): try: self.fill(color, delay=.2) self.off() self.fill(color, delay = 3) self.off() sleep(3) except: se...
def display_board(): print(board[0]+" | "+board[1]+" | " +board[2]) print(board[3]+" | "+board[4]+" | "+board[5]) print(board[6]+" | "+board[7]+" | "+board[8]) def handle_turn(player): position=int(input("enter position from 1 to 9:")) position=position-1 board[position]="x" di...
The code defines a function to manage a turn-based game. It starts by displaying the game board, then enters a loop where it handles the current player's turn, checks if the game has ended (e.g., win/draw), and switches to the next player. The loop continues until the game concludes, ensuring alternating player actions...
def play_game(): display_board() while game_still_going: handle_turn(current_player) check_if_game_over() flip_player()
def connect(): client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_socket.connect((SERVER_IP, SERVER_PORT)) return client_socket def login(conn): username = input("Please enter username: ") password = input("Please enter password: ") uname_and_pwd = username + "#" + passwor...
This code implements a trivia game client that connects to a server, allows user login, and provides options to play trivia questions, check personal score, view high scores, list logged users, or quit. The main task is to handle user interactions and relay requests to the server through a menu-driven interface.
def main(): client_connection = connect() login(client_connection) while True: print("p Play a trivia question") print("s Get my score") print("h Get high score") print("l Get logged users") print("q Quit") choice = input("Pl...
def load_user_database(): """ Loads users list from file ## FILE SUPPORT TO BE ADDED LATER Recieves: - Returns: user dictionary """ users = {} new_file = open("/Users/luzonimrod/Documents/Python/Users.txt",'r') for line in new_file: key, value = line.split() li = value.split(",") for i in range(len(li)):...
The code implements a trivia server that manages multiple client connections using non-blocking I/O. It initializes user data, accepts new clients, processes commands (like LOGOUT), handles client messages, and broadcasts responses. The server uses `select.select` to monitor socket activity, appending new clients to a ...
def main(): # Initializes global users and questions dicionaries using load functions, will be used later global users, client_socket global questions users = load_user_database() client_sockets = [] print("Welcome to Trivia Server!") server_socket = setup_socket() #client_host, client_address = client_server.a...
def _token(self, token:str, estado_actual:str, estado_sig:str): if self.lineas[self.pos] != " ": text = self._juntar(self.pos, len(token)) # Junta los caracteres if self._analizar(token, text): # analiza el token la entrada self.pos += len(token)...
This code processes input lines using a state machine to parse configuration parameters for a graph, extracting text, node color, text color, and node shape. It handles tokens like '{', '}', commas, and strings, with error recovery. Upon completion, it assigns colors/forms, generates a report, and outputs the parsed da...
def _compile(self): global Valor2An, Palabras global OperacionT, Color_Nodo, Color_Letra,Forma_Nodo estado_actual = 'S0' estado_anterior ='S0' while self.lineas[self.pos] != "": if self.lineas[self.pos] == '\n': self.fila +=1 ...
def create_book_to_similarity_barplot( self, book_to_similarity: Dict[BookName, SimRatio] ) -> bq.Figure: x_ord = bq.OrdinalScale(reverse=True) y_sc = bq.LinearScale() bar = bq.Bars( x=list(book_to_similarity.keys()), y=list(book_to_similarity.values()), ...
The code performs a Bible search by validating input text length, generating book and chapter similarity data, creating visualizations, and updating the UI with search results or error messages if the query is invalid.
def search_phrase(self, *_): """Run the search""" self.search_text.loading = True self.bible_loading.active = True query_text = self.search_text.v_model if count_words(query_text) > BibleApp.MAX_QUERY_WORDS: err_msg = f"Max words Limit to {BibleApp.MAX_QUERY_WORDS}" ...
def __random_district_label(self, graph): """ UTIL method for getting a random district from a graph of nodes """ return random.sample(graph, 1)[0] def __get_district_subgraph(self, g, district_label): """ Given a nx.graph and a district_label Return a...
The function `recombination_of_districts` applies a recombination algorithm to a graph representing districts. It randomly selects two adjacent districts, merges them, and generates a minimum spanning tree (MST) of the combined subgraph. It iteratively tests edges in the MST to find a valid split that maintains distric...
def recombination_of_districts(self, i): """ Given a graph Perform the recombination algorithm described in https://mggg.org/va-report.pdf ("Comparison of Districting Plans for the Virginia House of Delfates"; Metric Geometry and Gerrymandering Group; Section 2.3.2) ...
def __pop_score_diff(self, graph): scores = [] # 0: total 1: vap 2: cvap total_district_mapping = {} vap_district_mapping = {} cvap_district_mapping = {} for district_label in self.all_districts: total_district_mapping[district_label] = 0 vap_district_map...
The main task of the code is to compute and store key statistical metrics of a districting plan (represented as a graph) into the object's data structure. These metrics include the efficiency gap, population scores, objective function score, number of opportunity districts, and counts of Republican/Democrat-voting dist...
def __record_key_stats(self, graph, is_original_plan=False): """ Given a potential districting plan (graph) and an optional flag for saying this is the original plan, Update our local data record to include stats for this plan data object: eg : efficiency gap mea...
def recombination_of_districts(self, i): """ Given a graph Perform the recombination algorithm described in https://mggg.org/va-report.pdf ("Comparison of Districting Plans for the Virginia House of Delfates"; Metric Geometry and Gerrymandering Group; Section 2.3.2) ...
This code generates alternative district plans through iterative recombination, saving each plan's graph structure and statistics to JSON files. It first randomizes an initial plan via cooling rounds, then runs specified rounds of recombination to explore plan variations. Valid plans meeting strict criteria (e.g., low ...
def generate_alternative_plans(self, rounds, processNumber, outputPath): # Run `cooling`-many rounds to randomize the plan a bit # self.__drawGraph(self.g, "output/original") for i in range(0, self.cooling_period): print("Randomizing the seed plan", i) if i % 25 == 0 and self.verbose...
def valid_robot_move(self, move, env): x = self.i + dx[move] y = self.j + dy[move] if not env.valid_position(x,y): return False piece = env.board[x][y] if piece == Corral and not self.charge_child: return False piece = env.get_piece(x,...
The code determines valid robot movements, prioritizes Corral moves if charging a child, otherwise applies a strategy to select the next action from available options, returning 'Stay' if no valid moves exist.
def action(self, board): actions = [ Up, Down, Left, Right ] results = [] for act in actions: if self.valid_robot_move(act, board): results.append(act) if self.charge_child: for res in results: if board.board[self.i + dx[res]][sel...
def possible_child_move(self, x, y , move): x_n = x + dx[move] y_n = y + dy[move] if self.valid_position(x_n,y_n) and self.board[x_n][y_n] == Obstacle: return self.possible_child_move(x_n, y_n, move) if not self.is_empty(x_n, y_n): return False ...
The code moves a child on a board by updating their position based on the given move direction. If the new position contains an obstacle, it swaps the obstacle with the last empty cell along the movement path, updating the board state. The function also triggers a `child_mess` method with the original coordinates.
def make_child_move(self, i , move): x, y = self.childs[i].i, self.childs[i].j if self.possible_child_move(x, y, move): x_n = x + dx[move] y_n = y + dy[move] self.childs[i].i = x_n self.childs[i].j = y_n if self.board[x_n][y_n] == Obstacle: ...
def corrales(self): large = max(self.rows, self.columns) for i in range(self.n_childs): if large == self.rows: self.board[i][0] = Corral else: self.board[0][i] = Corral def get_empty_pos(self): board = self.board actioners = self.g...
The code resets a game environment by initializing or repositioning game elements like the robot, children, and obstacles on a grid. It sets initial states for game variables (e.g., win/loss conditions) and generates the board layout, ensuring empty spaces are filled with entities. If no existing child or robot objects...
def reset(self, dirty, obstacles, childs = None, robot = None, complete=False): if complete: self.moment = 0 self.tie = False self.lost = False self.win = False self.ended = False self.dirty = 0 self.board = [ [Empty] * self.column...
def reset(self, dirty, obstacles, childs = None, robot = None, complete=False): if complete: self.moment = 0 self.tie = False self.lost = False self.win = False self.ended = False self.dirty = 0 self.board = [ [Empty] * self.column...
This code simulates a cleaning task where a robot and children agents navigate a grid to clean dirt while avoiding obstacles. The simulation tracks dirt levels, checks for win/loss conditions (winning by fully cleaning, losing by exceeding dirt threshold), handles agent movements, and periodically resets the environmen...
def simulate(self): self.reset(self.init_dirty, self.init_obst, complete=True) while (self.moment < 100*self.t): dirty = self.object_percent(Dirty) self.dirty += dirty if dirty >= 0.6: self.lost = True break ...
def gd_download(url, directory): if 'folder' in url: output = get_title(url)[:-15] output_path = directory + output print("---> Downloading to: " + output_path) download_folder(url, output_path) elif 'file' in url: temp_output = get_title(url)[:-15] output = temp_...
The main task of the code is to identify the file-sharing service (Google Drive, Dropbox, MediaFire, WeTransfer) from the input URL and trigger the corresponding download function to save the file to the specified output path.
def grab(url, output_path): if gdrive_url in url: gd_download(url, output_path) if dropbox_url in url: db_download(url, output_path) if mediafire_url in url: mf_download(url, output_path) if wetransfer_url in url: wt_download(url, output_path)
def selectFiles(self): self.filePaths = fd.askopenfilenames(filetypes=[("CSC files", "*.csv")]) filenames = [] for filePath in self.filePaths: path, filename = os.path.split(filePath) filenames.append(filename) self.filenamesLabel.config(text="\n".join(filenames)...
The code creates a GUI application for processing CSV data using a low-pass filter. It allows users to select files, input filter parameters (order, sampling frequency, cutoff frequency, and x-axis offset), plot the filtered data, and save the results. The interface initializes default values for parameters and organiz...
def __init__(self): super().__init__() self.geometry("500x400") self.title("Low Pass Filter csv data") self.plotData = {} self.filePaths = [] tk.Button(self, text="Select Files", command=lambda: self.selectFiles()).pack() self.filenamesLabel = tk.Label(self, ...
def return_max_cursor_pos(self): """ Returns the max_cursor_pos based on the amount of rows of the display. """ return self.lcd.lcd.rows def return_max_index(self): """ Returns the max_index based on the amount of slots. """ return len(self.current_menu.sl...
The main task of the code is to reset the menu system by clearing the LCD, updating menu slots if necessary, recalculating cursor and index limits, stopping any ongoing scrolling, resetting cursor position, and reinitializing navigation parameters. It also optionally resets the wait state based on the `reset_wait` para...
def reset_menu(self, reset_wait=True): """ Resets the Menu and the wait bool if wanted. Parameters ---------- reset_wait : bool If True wait is set to false. """ self.lcd.clear() time.sleep(0.01) if isinstance(self.current_menu...
def __set_wait(self): self.wait = True def __callback(self, callback_type: str, value=None): self.current_menu.value_callback(callback_type, value, self) def __reset_wait(self): self.wait = False def __stop_scrolling(self, row, index): self.end_scrolling = True while self.scrolli...
This method handles directional input to update the menu's cursor and shift values, triggers callbacks for custom cursors, manages scrolling behavior, and adjusts the UI state based on navigation direction, ensuring proper index bounds and overflow handling.
def __value_changed(self, value, direction): if not self.wait: self.__set_wait() self.timeout_reset = True if self.current_menu.custom_cursor: self.__callback("direction", value=direction) self.__reset_wait() else: p...
def __callback(self, callback_type: str, value=None): self.current_menu.value_callback(callback_type, value, self) def reset_menu(self, reset_wait=True): """ Resets the Menu and the wait bool if wanted. Parameters ---------- reset_wait : bool If True ...
This function handles user input in a file menu system by checking the current menu type, index position, and path validity. It triggers callbacks for pressing items, navigating directories, or returning to parent menus, while managing file/directory actions based on custom behaviors and resetting the menu state accord...
def pressed(): if isinstance(self.current_menu, MenuFile): if self.index <= self.current_menu.pr_slots_last_index: self.__callback("press", value=self.index) elif self.current_menu.file_menu_depth >= 1 and self.index == self.current_menu.pr_slots_last_inde...
def get_input(text, defValue): resValue = input(text + ' [def: ' + defValue + ', . to cancel]: ') if resValue == '.': return False, defValue if resValue == '': resValue = defValue if resValue == ' ': resValue = '' return True, resValue.strip() def get_rentry_input(title, lang, labels, keywords): r, tit...
The function `cmd_add_bookmark` adds a bookmark by collecting a URL, title, language, labels, and keywords from user input. It validates inputs and checks if the URL already exists in the database. If valid and not duplicate, it stores the bookmark data via `repo.add_bookmark_db` and confirms the addition. Errors halt ...
def cmd_add_bookmark(inp_values): r, url = get_input('url', '') if not r: return r, inp_values[Cmd.ITITLE], inp_values[Cmd.ILANG], inp_values[Cmd.ILABELS], inp_values[Cmd.IKEYWORDS] = get_rentry_input('', inp_values[Cmd.ILANG], inp_values[Cmd.ILABELS], inp_values[Cmd.IKEYWORDS]) if not r: return if repo.add_...
def argparser(): parser = argparse.ArgumentParser(description="Issues a batch of requests.") parser.add_argument( "-o", "--hostname", type=str, default="localhost", metavar="localhost", help="Hostname to connect to." ) parser.add_argument( "-p", "--port", type=int, metava...
The main task of the code is to process a sequence of events defined in a TOML configuration file, executing network operations (e.g., creating connections, sending/receiving data) and system actions (e.g., sleeping, loading/unloading files) via event-driven logic. It uses epoll for I/O multiplexing, manages request st...
def main(): requests = {} receivers = {} args = argparser() poller = select.epoll() basename = f"{args.hostname}:{args.port}" outdir = "" if len(args.dir) > 0: outdir = args.dir try: os.mkdir(outdir) except: pass for event in toml.load(ar...
def ticker_bid_ask(session, ticker): payload = {'ticker': ticker} resp = session.get('http://localhost:9999/v1/securities/book', params=payload) if resp.ok: book = resp.json() return (book['bids'][0]['price'], book['asks'][0]['price']) raise ApiException('Authorization error. Please c...
The function `clear_USD` liquidates an open USD position by repeatedly executing market sell orders (if long) or buy orders (if short) in increments defined by `config.USD_PER_TRADE`, until the position is fully closed. It retrieves real-time USD bid/ask prices and adjusts the position iteratively, ensuring minimal mar...
def clear_USD(session): USDbid, USDask = ticker_bid_ask(session, "USD") position = get_position(session, "USD") while position > 0: amount = min(position, config.USD_PER_TRADE) make_order("USD", "MARKET", amount, "SELL") time.sleep(0.1) position = get_position(session, "USD")...
def get_settings(project: Project): return project.pyproject.settings["plugin"]["torch"] def check_lockfile(project: Project, lock_name: str) -> str | None: """Check if the lock file exists and is up to date. Return the update strategy.""" lockfile_file = project.root / lock_name if not lockfile_file.ex...
The code checks if a project's lockfile is up-to-date based on configuration settings. If the `check` option is enabled, it validates the lockfile's status, exiting with an error if outdated. Otherwise, it generates or updates the lockfile by processing dependencies for each API variant, resolving requirements with spe...
def handle(self, project: Project, options: dict): plugin_config = Configuration.from_toml(get_settings(project)) if options.check: is_updated = check_lockfile(project, plugin_config.lockfile) if not is_updated: project.core.ui.echo( "Lockfile...
def get_ps(self, epoch,): if epoch >= len(self.ps): return self.ps[-1] else: return self.ps[epoch] def mask_sample(self, sample): seq_length = len(sample) # duplicate sample sequence # TODO: check the reshaping is correct sample = sample.tile( ...
The code trains a neural network model over multiple epochs using a training dataset, computes loss via masked sample predictions, performs backpropagation, and periodically evaluates model performance on a development dataset. It logs training and validation losses, along with perplexity metrics, into JSON files for t...
def train_loop(self, data_train, data_dev, encode_text, prefix="", epochs=50): logdata = [] for epoch in range(epochs): self.train(True) print("Using", self.get_ps(epoch), "with", self.training) losses_train = [] for sample_i, (sample_num, sent_embd) in e...
def get_username_password(options): """ Parse the username/password from the command line or environment. """ if '--auth' in options: username, password = options['--auth'].split(':') else: username = os.environ.get('VODAFONE_USERNAME') password = os.environ.get('VODAFONE_PAS...
The main task of the code is to retrieve and display usage information from a service (likely Vodafone) by authenticating with a username and password. It parses command-line options, configures logging based on verbosity, retrieves credentials from arguments or environment variables, fetches usage data, and displays i...
def main(): options = docopt(__doc__, version='1.0.1') if options['--verbose']: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) username, password = get_username_password(options) if not username or not password: print("No username/pas...
def get_login_info(): """ Get info from customer. TODO: Validate inputs, ask again if given invalid input. """ acct_num = input("Please enter your account number: ") pin = input("Please enter your four digit PIN: ") return acct_num, pin def login_to_server(sock, acct_num, pin): """ Attempt to login ...
The main task of the code is to manage an ATM session by authenticating a user's account number and PIN via a server connection, processing transactions if authenticated, and terminating the session. It returns `True` on successful validation and transaction processing, or `False` if authentication fails, ensuring prop...
def run_atm_core_loop(sock): """ Given an active network connection to the bank server, run the core business loop. """ acct_num, pin = get_login_info() validated = login_to_server(sock, acct_num, pin) if validated: print("Thank you, your credentials have been validated.") else: prin...
def get_next_quarter_date() -> (int, int): """ :return: the next quarter start month and year """ month = datetime.date.today().month year = datetime.date.today().year next_quarter = find_next_quarter(month) if next_quarter == 1: year += 1 return next_quarter, year def fetch_even...
The main task of the code is to retrieve and filter Jewish holidays occurring in the next quarter, returning them as a list of dictionaries with Hebrew names and dates. It calculates the next quarter's date, fetches relevant events, and filters them using a custom check before formatting the results.
def get_next_quarter_holidays() -> List[Dict[Text, Text]]: """ :return: all jewish holidays in the next quarter """ next_quarter, year = get_next_quarter_date() events = fetch_events(year) return [{EventsConsts.HEBREW_KEY: event[EventsConsts.HEBREW_KEY], EventsConsts.DATE_KEY: event...
def _update_display(self): """ update every cell and data according to current game board """ self._display_cells(False) self.__score_label[TEXT] = SCORE + str(self.__game_board.get_score()) self.__best_score_label[TEXT] = BEST_SCORE + str( self.__game_board.g...
This auxiliary function updates the game display, checks for game over/winning conditions, triggers corresponding outcomes (lose/win), updates the undo button's appearance, and plays a move sound. It handles post-move logic by evaluating the game state, ensuring UI elements reflect the current status, and managing visu...
def _any_move_event(self): """ auxiliary function for the directions functions """ self._update_display() if self.__game_board.game_over(): return self._lose() if self.__game_board.winner() and not self.__win: return self.win() self.__undo_...
def send_and_receive_TAC(sender_object, receivers_named_tuples, message_func, message_type_of_sender, message_type_of_receiver, index_of_iteration, addings=None): send_TAC(sender_object, receivers_named_tuples, message_func, message_type_of_sender, message_type_of_receiver, ind...
This function performs iterative message passing between an agent and its neighbors to compute a final position. It runs mini_iterations of sending variable-to-function messages, aggregates results into next_pos, then broadcasts this position to robot neighbors. The final position is determined using a specified functi...
def max_sum_TAC_variable_node(agent, for_alg): mini_iterations = for_alg['mini_iterations'] for index_of_iteration in range(mini_iterations): # print('agent %s is in %s loop' % (agent.get_name(), i)) # var-robots to func-targets send_and_receive_TAC(sender_object=agent, receivers_named_...
def print_primes(a): print(f"{a}: {prime_factors(a)}") def print_lcm(a, b): res = lcm(a, b) print(f"lcm({a}, {b}) = {res}") print_primes(a) print_primes(b) print_primes(res) print("") def print_hcf(a, b): res = hcf(a, b) print(f"hcf({a}, {b}) = {res}") print_primes(a) print_primes(b) print_prime...
This function acts as a dispatcher, executing different mathematical operations based on the 'funcArg' parameter. It calls corresponding functions like print_primes, print_lcm, or r_lcm, handling parameters a, b, and c as needed for tasks like prime generation, LCM/HCF calculations, and their reversed variants. The 'ma...
def func(funcArg, a, b=None, c=None): match funcArg: case("usage"): print(usage) case("primes"): print_primes(a) case("lcm"): print_lcm(a, b) case("hcf"): print_hcf(a, b) case("r_primes"): r_primes(a) case("r_lcm"): r_lcm(a) case("r_lcm_nomult"): r...
def boot_vm_manualy(): cmd, arch = general_boot_setup() # aarch64 if arch == "aarch64": cmd = qemu_arm_tools.aarch64_specific(cmd) # arm (32bit) elif arch == "arm": cmd = qemu_arm_tools.arm_specific(cmd) # amd64 elif arch == "x86_64": cmd = qemu_x86_tools.amd64_sp...
The main task of the code is to create a command-line interface loop that repeatedly displays a menu of options for managing virtual machines and system tasks. It allows users to manually boot a VM, check disk utilization, load a VM from a file, print host information, or quit. The loop continues until the user selects...
def main_loop(): # TODO: rewirte this function (main_loop) run = True while run: print("choose action:\n1: boot vm manualy\n2: disk util\n3: Load VM from file\n4: Quit") rep = tools_kit.choose_number("choose action: ") if rep == 1: boot_vm_manualy() if rep == 2: ...
def _expand_array(self, array_name): """ Expand variables and return a set of keywords. Warning is issued when exceptions occur.""" ret = self._arrays[array_name] if array_name in self._arrays else [] try: ret = self._do_expand_array(array_name) except Exception as e...
The main task of the code is to convert a custom pattern syntax into a compiled regular expression for trigger matching. It processes placeholders (*, #, _) into regex equivalents, handles optional patterns, replaces arrays, bot/user variables, and input/reply tags with actual values, then compiles the final regex with...
def _reply_regexp(self, user, regexp): """Prepares a trigger for the regular expression engine.""" if regexp in self._regexc["trigger"]: # Already compiled this one! return self._regexc["trigger"][regexp] # If the trigger is simply '*' then the * there needs to become (...
def _say(self, message): if self._debug: print("[RS] {}".format(message)) if self._log: # Log it to the file. fh = open(self._log, 'a') fh.write("[RS] " + message + "\n") fh.close() def _topic_triggers(self, topic, triglvl, depth=0, inheritance...
This method sorts triggers (or 'that's') by analyzing topics and their inherited triggers, ensuring proper prioritization. It initializes a cache, processes each topic's triggers (including inherited ones), sorts them, and stores the results. For non-'that's' cases, it recursively sorts previous replies and substitutio...
def sort_replies(self, thats=False): """Sort the loaded triggers.""" # This method can sort both triggers and that's. triglvl = None sortlvl = None if thats: triglvl = self._thats sortlvl = 'thats' else: triglvl = self._topics ...
def _say(self, message): if self._debug: print("[RS] {}".format(message)) if self._log: # Log it to the file. fh = open(self._log, 'a') fh.write("[RS] " + message + "\n") fh.close() def _warn(self, message, fname='', lineno=0): header =...
The code parses RiveScript code into a structured in-memory format for execution. It processes commands like `!` (variable definitions), `>` (topic/object labels), `<` (end labels), `+` (triggers), `-` (replies), and others, organizing them into topics, objects, and syntax trees. It handles multi-line comments, tracks ...
def _parse(self, fname, code): """Parse RiveScript code into memory.""" self._say("Parsing code") # Track temporary variables. topic = 'random' # Default topic=random lineno = 0 # Line numbers for syntax tracking comment = False # In a multi-line comment ...
def reorganize_social_groups(self): for row in self.grid.cells: for cell in row: if len(cell.herds) > 1: merged_herd = [] for herd in cell.herds: if herd is not None and hasattr(herd, "__iter__"): ...
The main task of the code is to simulate social group interactions within a grid. It iterates through each cell, reorganizes social groups, and triggers conflicts between prides or hunting behavior by prides against herds. If multiple prides exist, they fight; if one pride and one herd exist, the pride hunts the strong...
def struggle(self): for row in self.grid.cells: for cell in row: self.reorganize_social_groups() if len(cell.prides) > 1: self.fight_between_prides(cell.prides[0], cell.prides[1]) elif (len(cell.prides) == 1) and (len(cell.herds) =...
def giveSomeCellsWater(self): for row in self.grid.cells: for cell in row: if cell.type == "ground" and random.random() < WATER_CHANCE: cell.type = "water" def populateMapWithErbastAndCarviz(self, erbast_prob, carviz_prob): for row in self.grid.cells: ...
The code simulates an ecosystem over multiple days, modeling growth, movement, grazing, and reproduction of organisms. It tracks grid states daily, generates heatmaps visualizing vegetation, carviz, and erbast densities, and produces plots to analyze terrain, population trends, and species distribution dynamics over ti...
def start(self): self.giveSomeCellsWater() self.populateMapWithErbastAndCarviz(0.1, 0.9) self.gridStatuses = [self.grid] changes = [] for day in range(NUMDAYS): self.growing() self.move() self.grazing() self.struggle() s...
def settings(key: str): """ Get a setting from the app state. Lazily evaluates app state defined as functions and cache the results Args: key (str): setting key Returns: setting value """ if datetime.utcnow() - app_state["login_time"] > timedelta(hours=1): login(ref...
The function `azcli` executes an Azure CLI command with retry logic. It runs a specified command, retries on failure up to `max_attempts` times with exponential backoff, logs errors, and returns the JSON response. It ensures the user is logged in, handles exceptions, and uses recursive calls to retry failed invocations...
def azcli(basecmd: list, attempt: int = 1, max_attempts: int = 5): """ Run a general azure cli cmd with retries Args: basecmd (list): base command to run attempt (int, optional): attempt number. Defaults to 0. max_attempts (int, optional): max attempts. Defaults to 5. Returns: ...
def list_workspaces(fmt: OutputFormat = OutputFormat.LIST, agency="ALL"): "Get sentinel workspaces from {datalake}/notebooks/lists/SentinelWorkspaces.csv" # return workspaces dataframe from the datalake dataframe = ( pandas.read_csv((settings("datalake_path") / "notebooks/lists/SentinelWorkspaces.cs...
The function executes a set of KQL queries in parallel using threading, collects results into JSON files, and packages them into a zip archive. It handles agency-specific or global ("ALL") data retrieval, including RunZero asset queries, and combines results with agency metadata. The output includes JSON data, KQL quer...
def report_zipjson(query_config: dict, agency: str, timespan: str): """ Run a set of queries and return the results as a collection of json in a zip. Args: query_config (dict): Dictionary of queries to run. agencies (pandas.DataFrame): Dataframe of agencies to query. timespan (str):...
def clean_path(path: str) -> str: """ Remove any disallowed characters from a path Args: path (str): path to sanitize Returns: str: sanitized path """ return sanitize_filepath(path.replace("..", ""), platform="auto") def settings(key: str): """ Get a setting from the ap...
The function `get_blob_path` generates a path to access an Azure blob storage URL. If no subscription is provided, it returns a test `Path` object. Otherwise, it extracts the storage account and container from the URL, generates a SAS token (using preset or dynamic methods), and returns a `UPath` object for authenticat...
def get_blob_path(url: str, subscription: str = ""): """ Mounts a blob url using azure cli If called with no subscription, just returns a pathlib.Path pointing to url (for testing) """ if subscription == "": return Path(clean_path(url)) account, container = url.split("/")[2:] account...
def _clearLastError(self): """ any errors are cached till the next AT command :return: nothing """ self.LastErrorType = None self.LastErrorNum = None def _setCmd(self, cmd: str,rxTimeout:int=2) -> bool: """ called by all set commands which...
This function initiates or stops the LoRaWAN join process for a device, authenticating with a network server using OTAA keys. It sends configuration parameters (start, autojoin, interval, retries) to the module, waits for authentication responses (+CJOIN:OK/FAIL), and returns True/False based on success. It handles par...
def join(self,start:int=1,autojoin:int=0,interval:int=8,retries:int=8)->bool: """ Start or stop the join process. Set the OTAA keys and other parameters first. :param start: int: 0: stop join,1: start join :param autojoin: int: 0: disable auto join, 1:enable auto join (factory) ...
def _setCmd(self, cmd: str,rxTimeout:int=2) -> bool: """ called by all set commands which either return OK or raise an exception if a CME ERROR occurs :param cmd: str: the full command with parameters (if any) :return: True/False or raise an Exception ...
The main task of the code is to send a payload via a communication interface, handling confirmed/unconfirmed messages with retry counts, encoding data to hex, sending commands, waiting for responses (e.g., confirmation, errors), and invoking a downlink callback for received data. It returns True on success or False on ...
def sendPayload(self,payload:str=None,confirm:int=0,nbtrials:int=8) -> bool: """ possible responses OK+SEND:TX_LEN # confirm length OK+SENT:TX_CNT # nbtrials OK+RECV:TYPE,PORT,LEN,DATA # received data or ERR+SEND:ERR...
def getManufId(self) -> str: """ get the manufacturer ID which should always be ASR for this device :return: str:<manufacturer> e.g. 'ASR' """ return self._inquire("CGMI") def setLogLevel(self,level:int) -> bool: """ set current log level. This library t...
(The main task of the code is to initialize the ASR6501 class by configuring logging, verifying serial communication with an ASR modem via the `getManufId()` check, and setting initial parameters like join mode and error tracking. It ensures the device is ASR-compatible, raises exceptions on failures, and prepares the ...
def __init__(self,serial,logging_level:int=DEFAULT_LOG_LEVEL): """ initialises the ASR6501 class :param serial: serial stream object :param logging_level: such as logging.INFO, logging.DEBUG etc :param debug: """ self.serial=serial # logging should be s...
def print_log(self, st): if self.local_rank == 0: print(st) def prepare_dataset(self, max_skip = 5): cfg = self.cfg self.print_log('Process dataset...') train_datasets = [] for dataset in cfg.DATASETS: if dataset.name == 'synthetic': curr...
The code executes a training loop for a neural network, managing epochs, dynamic data sampling adjustments (skip fractions), and progress tracking. It iterates over batches, updates model parameters, logs losses, and adjusts skip values periodically to modify data sampling strategies. The loop continues until the total...
def training(self): # torch.autograd.set_detect_anomaly(True) cfg = self.cfg self.network.module.train_() self.report_interval = cfg.LOG.REPORT_INTERVAL self.save_im_interval = cfg.LOG.SAVE_IM_INTERVAL self.save_model_interval = cfg.LOG.SAVE_MODEL_INTERVAL step...
def getStatesSubsequences(direction, states): subsequences = [] sequence = [] # grouping sequential database into sequences by date states_by_date = groupDataFrameByDate(states) for _, group in states_by_date: # _ is a date we group by, group is dataframe of measurements in that group (single se...
The code performs data mining to identify frequent event patterns from sequences. It extracts subsequences from states and events, mines patterns using the BIDE algorithm with specified thresholds and minimum length, and calculates measures like support and confidence. The result is a list of pattern tuples with occurr...
def dataMining(events, states, direction, threshold, minlen, bide): # statesSubsequences [[seq],[seq],[seq]] statesSubsequences = getStatesSubsequences(direction, states) print("States subsequences done\t", datetime.now()) # eventsSubsequences[dataframe of eventsSubsequence] subsequences of events ...
def dataMining(events, states, direction, threshold, minlen, bide): # statesSubsequences [[seq],[seq],[seq]] statesSubsequences = getStatesSubsequences(direction, states) print("States subsequences done\t", datetime.now()) # eventsSubsequences[dataframe of eventsSubsequence] subsequences of events ...
The code's main task is to mine temporal patterns from event-state data (e.g., diabetes, posts, anonymized datasets) using a specified direction and threshold, compare them with opposite-direction patterns, update results accordingly, and export described patterns to a CSV file. It prepares data, extracts patterns, adj...
def main(file, direction, threshold, minlen, user, bide): print("Start\t\t\t\t", datetime.now()) # prepare raw data in expected format # states has date_time, value # events has data_time, code if (file == 'diabetes'): events, states = prepareDataDiabetes(user) elif (file == 'posts'): events, s...
def authenticate(username, password): auth_url = 'http://localhost:5000/authenticate' response = requests.post(auth_url, json={ 'username': username, 'password': password } ) if response.status_code == 200: return True else: return False def fetch_encrypte...
The code handles user login by retrieving entered credentials, authenticating them, and if successful, destroying the login window, fetching an encrypted message, and displaying the main GUI with user details and the encrypted data. If authentication fails, it updates the status to indicate invalid credentials.
def login(): username = username_entry.get() password = password_entry.get() if authenticate(username, password): login_window.destroy() encrypted_message = fetch_encrypted_message(username, password) show_main_gui(username, password, encrypted_message) else: login_status...
def caesar_cipher(text, shift): encrypted_text = "" for char in text: if char.isalpha(): shifted_char = chr((ord(char) - ord('a' if char.islower() else 'A') + shift) % 26 + ord('a' if char.islower() else 'A')) encrypted_text += shifted_char else: encrypted_tex...
The main task of the code is to register a new user by retrieving username/password inputs, encrypting a default message using a Caesar cipher, and invoking a registration function. If successful, it displays a confirmation, closes the login window, and opens the main GUI with the user's credentials. Errors trigger app...
def register_new_user(): username = username_entry.get() password = password_entry.get() if username and password: encrypted_message = caesar_cipher("Default message", 34) if register(username, password, encrypted_message): messagebox.showinfo( "Registration Succe...
def create_content_database(): conn = sqlite3.connect("content.db") cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS content ( txid TEXT UNIQUE, blockheight INTEGER, vout TEXT, time INTEGER, op_return TEXT, ...
The main task of the code is to process blockchain transactions and validate JSON entries by connecting to two databases. It retrieves transactions with content from "novo_blocks.db", processes them, extracts valid JSON entries from another database, and processes those entries. Finally, it closes both database connect...
def main(): novo_blocks_conn = sqlite3.connect("novo_blocks.db") conn = create_content_database() transactions = get_transactions_with_any_content(novo_blocks_conn) process_transactions(conn, transactions) valid_entries = get_valid_json_entries(conn) process_valid_json_entries(conn, valid_entr...
def query_peripheral(self): """ """ chars = self.requester.discover_characteristics() services = self.requester.discover_primary(); self.services = {} self.handle_map = {} self.uuid_map = {} for service in services: uuid16 = CentralLockDevice.g...
The main task of the code is to establish and maintain a Bluetooth Low Energy (BLE) connection to a peripheral device (likely a lock), allowing the user to interact with it via command-line options. These options include disconnecting, writing a secret code, reading status/log values, and displaying BLE data. The loop ...
def maintain_connection(self, address): """ Connects to the peripheral and maintains the connection until the user wishes to disconnect """ OPT_DISCONNECT = 'D' OPT_WRITE_CODE = 'W' OPT_READ_STATUS = 'S' OPT_READ_LOG = 'L' OPT_SHOW_BLE_DATA = 'B' ...
def scan(self): """ Scans for nearby BLE devices and returns their attributes """ service = DiscoveryService() print("Scanning...") dev_dict = service.discover(self.scan_duration) devices = [] for addr, name in dev_dict.items(): devices.append(...
The code connects to a BLE Lock device by allowing the user to select a device from a scanned list via its address or index, then initiates a connection using the selected device's address.
def connect(self, devices): """ Provides the interface to connect to a BLE Lock device """ if devices is None: devices = self.scan() print(devices) self.print_devices(devices) device = input("Please select from one of the devices listed above (enter ad...
def scan(self): """ Scans for nearby BLE devices and returns their attributes """ service = DiscoveryService() print("Scanning...") dev_dict = service.discover(self.scan_duration) devices = [] for addr, name in dev_dict.items(): devices.append(...
This function handles user input to determine the next action in a BLE application. It presents available options (scan/connect), parses user commands via an argument parser, and executes corresponding actions: scanning for BLE devices or connecting to a specified device using parsed arguments.
def handle_next_action(self): """ Handles the next action required by the user """ info = f'{ColourPrinter.BG_BLUE}{ColourPrinter.SILVER}' normal = f'{ColourPrinter.NORMAL}' print(f'{info}Available actions:{normal}') parser = ArgumentParser() parser.add_ar...
def _check_play_button(self, mouse_pos): button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: self.start_game() def _check_keydown_events(self, event): if event.key == pygame.K_RIGHT: self.spaceship.moving_right ...
This function processes Pygame events to handle user input: exiting the game, detecting left mouse button clicks to trigger the play button, and managing keyboard key presses and releases. It delegates specific actions to methods like _check_play_button, _check_keydown_events, and _check_keyup_events for further proces...
def _check_events(self): for event in pygame.event.get(): # Exiting the game if event.type == pygame.QUIT: sys.exit() # Pressing the LMB elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() ...
def _check_fleet_edges(self): for target in self.targets.sprites(): if target.check_edges(): self._change_fleet_direction() break def _spaceship_hit(self): # If there are still lives: if self.stats.spaceship_left > 0: self.stats.spacesh...
This method updates target positions, checks for collisions between the spaceship and targets (triggering a life loss if collided), and handles edge/bottom boundary checks for targets.
def _update_targets(self): self._check_fleet_edges() # Deciding which way to move the fleet self.targets.update() # Updating location # If the spaceship collides with a target, lose a life if pygame.sprite.spritecollideany(self.spaceship, self.targets): self._spaceship_hi...
def _check_events(self): for event in pygame.event.get(): # Exiting the game if event.type == pygame.QUIT: sys.exit() # Pressing the LMB elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() ...
The code runs a game loop that continuously checks for events, updates game elements (spaceship, bullets, targets) when the game is active, and refreshes the screen to render changes in real-time.
def run_game(self): while True: self._check_events() # Updating positions if self.stats.game_active: self.spaceship.update() self._update_bullets() self._update_targets() self._update_screen()
def personDraws(self, dealer=False, player_id=0, side=None, times=1): """Player draws input number of times.""" if dealer: print('Dealer draws', end='') player = self.people['dealer'] else: print(f'Player {player_id + 1} draws', end='') player = se...
The main task of the code is to run a command-line Blackjack game, allowing players to bet, draw cards, and play rounds against a dealer. It handles multiple game sessions, processes player decisions (hit/stand), checks for busts, and determines winners. The dealer draws cards based on rules, and the game resets for su...
def main(self): """Begins the game of command line Blackjack.""" game_count = 1 while not (quit := False): print(f'\n-------- Game {game_count} begin --------\n') # Dealer init self.personDraws(dealer=True) for i in range(...
def displayCardPile(self, cards, centre_pos): """Draws a pile of overlapping cards on the window. Args: cards (list of "Card" namedtuples): List of cards to display. centre_pos (tuple (x,y)): Centre position of the entire card pile (coordin...
This method displays a player's or dealer's cards at a specified position, showing one pile for normal hands or two split piles. It highlights the current pile (left/right) with a red box and adjusts positions based on split status.
def displayCards(self, centre_pos, dealer=False, player_id=0): """Gets cards list of the correct person using arguments. Displays one card pile in the given position, or two piles if player has split. Args: centre_pos ([type]): [description] dealer (bool, ...
def displayButtons(self): """Calls the functions to draw out all game buttons.""" self.displayActionButtons() self.displayBetButtons() def displayDealer(self): """Displays dealers cards, current hand value and whether they've bust.""" # Display cards centre_pos = (self.WI...
The code's main task is to render the current Blackjack game state on the screen, including the green background, title, buttons, dealer/player hands, and round outcome (win/draw/lose) using Pygame, then updating the display.
def display(self): """Displays the current blackjack game state to the window.""" self.win.fill(self.GREEN_BG) # Title at top of screen text = self.TITLE.render('Blackjack', 1, self.BLACK) self.win.blit(text, (int(self.WIDTH/2 - text.get_width()/2), 20)) self.displayBut...
def __extract_unique_question_codes(self) -> None: """ Extracts all the unique question codes for every question. These codes will be used as keys for the questions to avoid duplicates as well as mapping the images to the questions as well. """ selection_div: Tag for sel...
The main task of the code is to extract question codes, questions, answers, and images from HTML elements, then store them in the class instance's results dictionary. It ensures valid input types with assertions, delegates extraction to private methods, and orchestrates data matching to organize results systematically.
def generate_results(self) -> None: """ Wrapperfunction to be called to perform extraction of question codes, questions, answers, images and storing the results into the results dictionary of the respective class instance. """ assert isinstance(self._questio...
def process_genome(GenomeReady, genome_path, Bismap, fasta_path, conversion, out_dir, chr_dir, queue_name, bowtie_path, chrsize_path, write_script, pipe): """Generates necessary fasta files for Umap and Bismap Umap and Bismap require f...
The main task of the code is to process a genome by generating indexes, handling kmer-based sequence analysis, and submitting computational jobs for alignment and unification. It processes genome paths, manages job dependencies, creates kmer directories, runs Bowtie aligners, unifies results, and combines outputs. The ...
def main(): args = ArgHandler() # genome_path, chrom_dir, dir_kmers, chrsize_path, out_dir = args_list[:5] # idx_path, conversion, Bismap, queue_name = args_list[5:9] # kmers, SimultaneousJobs, ExitAfterIndexing = args_list[9:12] # var_id, write_script, source_dir, GenomeReady = args_list[12:16] ...
def lcd_byte( self, bits, mode ): pi.digitalWrite( self.RS, mode ) # High bits pi.digitalWrite( self.D4, 0 ) pi.digitalWrite( self.D5, 0 ) pi.digitalWrite( self.D6, 0 ) pi.digitalWrite( self.D7, 0 ) pi.digitalWrite( self.D4, bits & 0x10 ) pi.digitalWrite( self.D5, bits & 0x20 ) pi.digitalWrite( ...
This code initializes an LCD display by sending configuration commands to set display settings, enable cursor blinking, clear the screen, and reset the cursor position to the home location.
def setup( self ): self.lcd_byte( 0x33, 0 ) self.lcd_byte( 0x32, 0 ) self.lcd_byte( 0x06, 0 ) self.set_cursol( 0 ) self.set_blink( 1 ) self.lcd_byte( 0x28, 0 ) self.clear( ) self.move_home( )
def validateN(n): if( int(math.sqrt(n)) == math.sqrt(n) ): return True return False def createBoard(n): matrix=[] # define empty matrix for i in range(n): # total row is 3 row=[] for j in range(n): # total column is 3 row.append(0) # adding 0 value for each column for...
The code generates a valid Sudoku-like board of size n x n (a perfect square) by either using predefined examples or user-provided initial values. It iteratively creates random boards, checking for row, column, and subgrid validity, until a solution is found within a specified maximum number of attempts. If successful,...
def main(): n = 0 while(True): n = input("Enter the size of the board: n >> ") if( validateN(int(n)) == True ): break print("Invalid n. N must be a perfect square!") matrix = createBoard(int(n)) copy_matrix = createBoard(int(n)) example = "0" choice ...
def compute_mean_mles(train_data, train_labels): ''' Compute the mean estimate for each digit class. You may iterate over the possible digits (0 to 9), but otherwise make sure that your code is vectorized. Arguments train_data: size N x 64 numpy array with the images train_labels: s...
The code performs Gaussian MLE estimation for digit classification, computes train/test log-likelihoods, evaluates classification accuracy, and visualizes leading eigenvectors of class covariance matrices. It loads data, calculates means/covariances, classifies samples, and compares results with ground truth labels.
def main(): train_data, train_labels, test_data, test_labels = data.load_all_data() # #test to remove TODO # digits_subset = data.get_digits_by_label(train_data,train_labels,1) # m=np.mean(digits_subset, axis=0) # print(digits_subset.shape) # print(m.shape) # Fit the model means = comp...
def kfInit(kf1D = True, kf2D=True): std_acc=50; x_std_meas=0.02; y_std_meas=0.024;std_acc_1D=50; x_std_1D=0.24; if kf1D == True: KF1D_head = KalmanFilter1D(1/30, 1, std_acc_1D, x_std_1D) KF1D_midS = KalmanFilter1D(1/30, 1, std_acc_1D, x_std_1D) KF1D_RS = KalmanFilter1D(1/30, 1, std_acc_...
The code processes 3D and 2D skeleton data from multiple paths, comparing predicted and ground-truth points. It calculates errors for limbs using Euclidean distance, applies filters (median, Kalman), and evaluates performance via statistical metrics (outliers, KL divergence, t-tests). It visualizes errors in 2D/3D, ana...
def VisualizeError(paths): eds2D = np.empty([8,1]); eds3D = np.empty([8,1]); missed_count=0;n=0;q = 0;outliers_count3D=0;outliers_count2D=0;tots=0;failed_count_2D=0;failed_count_3D=0 pts_full_pred = np.empty([8,1]); pts_full_gt = np.empty([8,1]);pts_KF = np.empty([8,1]); limbs_2D = {}; limbs_3D = {};limbs_3D_pr...
def get3Dskeleton(path, id = 0, dep = True, gt=True, csvI = False, csvName= None, pts3Dmet = True, dilt = True): pts2D, filename = get2Dskeleton(path=path, id = id, dep = dep, gt=gt, csvI=csvI, csvName= csvName) if dep == True and pts2D: dep = os.path.join(path,'depth') depImg = np.load(dep+'...
The code compares 3D skeleton predictions against ground truth data using Kalman Filters (KF) for smoothing and evaluating accuracy. It processes image sequences, applies KF to predict joint positions, calculates Euclidean errors for 2D/3D limb segments, applies median filters, and analyzes performance via statistical ...
def compareGT(paths): eds2D = np.empty([8,1]); eds3D = np.empty([8,1]); missed_count=0;n=0;q = 0;outliers_count3D=0;outliers_count2D=0;tots=0;failed_count_2D=0;failed_count_3D=0 pts_full_pred = np.empty([8,1]); pts_full_gt = np.empty([8,1]);pts_KF = np.empty([8,1]); limbs_2D = {}; limbs_3D = {};limbs_3D_prev={}...
def __bomb(self, field: list[int], map_player: Client): self.stats[map_player]["bombed"].append(field) self.__sendFieldResp(field, self.players.index(map_player), "HIT" if field in self.stats[map_player]["ships"] else "MISS") def cyclePlayer(self): self.currentPlaye...
This function processes a player's request to bomb a specified field. If the player is valid and the field hasn't been bombed by the opposing player, it triggers the bomb, cycles to the next player, updates the game state, and checks for victory. If invalid, it sends a failure response.
def fieldReq(self, field: list[int], player: Client): if player == self.currentPlayer and player in self.players: field_player = self.players[len(self.players) - 1 - self.players.index(player)] if field not in self.stats[field_player]["bombed"]: self.__bomb(field, field_p...
def get_detail(self, sale_id): "return: diccionario del objeto sale detail con formato serializado de sus relaciones" res = [] for obj in SaleDetail.objects.filter(sale=sale_id): dict_res = SaleDetailSerializer(obj).data if dict_res: dict_res["product"] = ...
The code retrieves a sale object by ID, serializes it into a dictionary, and enriches it with related data: sale details, customer info, and payment method by calling helper methods. It returns a structured dictionary with serialized sale data and its associated relationships.
def get_sale(self, id_item): "return: diccionario del objeto ventas con formato serializado de sus relaciones" obj = Sale.objects.get(pk=id_item) res = SaleSerializer(obj).data if res: res['saledetail'] = self.get_detail(id_item) res['customer'] = self.get_custome...
def gen_instances_df(): # (instance_set, n, instance_name, beta, exec_id) instances = get_instances_execs() return pd.DataFrame(instances, columns=["set", "n", "name", "beta", "exec_id"]) def read_reference_data(): return pd.read_csv("../instances/reference_data.csv", dtype={"beta": str, "opt": "Int64",...
The main task of the code is to read and process execution results from files in a specified folder, merge them with reference data, calculate objective gaps, and clean instance names. It generates a DataFrame containing execution metrics (objective, time), merges with reference values, handles missing data, converts o...
def read_execution_data(results_folder: str, remove_solomon_n: bool = True): df = gen_instances_df() # each row of this dataframe represents one of ten execution of each instance n_instance_beta ref_data = read_reference_data() df = df.merge(ref_data, how="left", on=["set", "name", "beta"], copy=False) ...
def entropy(data): total, positive, negative = len(data), (data[:, -1] == "Y").sum(), (data[:, -1] == "N").sum() entropy = 0 if positive: entropy -= positive / total * log2(positive / total) if negative: entropy -= negative / total * log2(negative / total) return entropy def bestAttr...
The code implements the ID3 algorithm to build a decision tree. It recursively selects the best attribute to split the data, partitions the dataset based on attribute values, and creates child nodes for each partition. The process stops when entropy is zero (pure class) or no features remain, assigning the most common ...
def id3(data, labels): #print("data is ",data) root = Node('Null') if entropy(data) == 0: #all are either pos or neg root.label = data[0, -1] elif len(data[0]) == 1: root.label = Counter(data[:, -1]).most_common()[0][0] else: column = bestAttribute(data) roo...
def add_sand(self,x,y): self.forward(x,y) def saveFile(self, fileName, directory): if not os.path.exists(directory): os.makedirs(directory) savefig(fileName) def plot_sandpile(self): grid = self.grid N = self.N critLevel = self.critLevel iterations = self.iterations initMode = se...
The code simulates a sandpile model by adding sand to a grid in different modes (Random, SpecificCorners, SpecificMiddle), tracking the number of collapses ("breaks") and affected areas across iterations. It visualizes the grid in real-time if enabled, records statistical frequencies of breaks and area sizes, and saves...
def run(self): grid = self.grid N = self.N critLevel = self.critLevel iterations = self.iterations initMode = self.initMode mode = self.mode animated = self.animated save = self.save if mode == 'Random': freq = {} for i in range(iterations): self.numbreaks = 1 #R...
def create_recipe(new_recipe_path: Path) -> None: """Create new recipe directory using template (default behavior is overwrite).""" recipe_template_path = Path("src/uni/converter/recipe_template") shutil.rmtree(new_recipe_path, ignore_errors=True) shutil.copytree(recipe_template_path, new_recipe_path) d...
(The code generates a new recipe from a flow definition by creating directory structure, converting the flow into a DAG file, updating config files with flow parameters, and copying necessary files. It uses helper functions for setup, DAG generation, formatting, and file copying, with notes indicating temporary steps t...
def cli(flow_definition_path: str, new_recipe_path: str, flow_object_name: str) -> None: """FLOW_DEFINITION_PATH: location of .py file containing flow definition.""" # Convert string paths into OS-agnostic Path objects flow_definition_path = Path(flow_definition_path) new_recipe_path = Path(new_recipe_p...
def can_handle(self, directive: str) -> bool: """Flag whether this plugin supports the given *directive*.""" if directive != "windows": self._log.debug( f"The Windows plugin does not support '{directive}' directives." ) return False return Tr...
The code configures Windows using dotbot by validating input data, checking platform compatibility, and applying personalization settings, registry modifications, and font symlink creation. It returns a boolean indicating success.
def handle(self, directive: str, data: dict[str, typing.Any] | typing.Any) -> bool: """ Configure Windows using dotbot. :raises ValueError: ValueError is raised if the `.can_handle()` method returns False. """ if not self.can_handle(directive): raise Val...
def apply_kernel(image: SingleChannelImage, kernel: Kernel) \ -> SingleChannelImage: """apply kernel to a single channel image and return the new image """ img_copy = deepcopy(image) # don't want to change the original for i in range(len(image)): for j in range(len(image[0])): ...
The function converts an input image into a binary edge map by first blurring it, then thresholding each pixel based on a local block's average value. Pixels darker than the threshold are set to black (0), while others become white (255), creating a high-contrast edge detection result.
def get_edges(image: SingleChannelImage, blur_size: int, block_size: int, c: int) -> SingleChannelImage: """gets image,then check if its darker or lighter, if darker than makes the pixel black else white """ img_copy = deepcopy(image) # Copy image data blured_image = apply_kernel(img_cop...
def separate_channels(image: ColoredImage) -> List[List[List[int]]]: """separate a colored image to different channels""" l1 = [] # for channels for i in range(len(image[0][0])): list1 = [] # for ist in channel for j in range(len(image)): list2 = [] # for number in list ...
The function scales down a colored image to fit within a specified maximum size while preserving its aspect ratio. If the image's dimensions are already within the limit, it returns None. Otherwise, it separates the image into color channels, resizes each channel based on the larger dimension (height or width), and rec...
def scale_down_colored_image(image: ColoredImage, max_size: int) \ -> Optional[ColoredImage]: """gets image and max size, if image parameters is lower than max size than do nothing, else scale down the image to the right size""" height = len(image) width = len(image[0]) if height <= max_...
def get_edges(image: SingleChannelImage, blur_size: int, block_size: int, c: int) -> SingleChannelImage: """gets image,then check if its darker or lighter, if darker than makes the pixel black else white """ img_copy = deepcopy(image) # Copy image data blured_image = apply_kernel(img_cop...
The function cartoonifies an image by first extracting edges via grayscale conversion and thresholding, then quantizing the original image into specified color shades. It creates a mask from normalized edge data, applies this mask to each color channel of the quantized image, and combines the masked channels to produce...
def cartoonify(image: ColoredImage, blur_size: int, th_block_size: int, th_c: int, quant_num_shades: int) -> ColoredImage: """gets image and parameters, get the edges and quantize of the image,i created a mask from the edges of the image and then made a new image by the add_mask function, th...
def get_weather(): import requests api_key = "8bcf303b818a150ee52d4628a4602992" city = "toshkent" weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}" response = requests.get(weather_url) weather_data = response.json() return weather_data def translate_to_...
The function converts weather data from JSON format into a formatted Uzbek text. It extracts parameters like weather description, temperature, humidity, wind speed/direction, and cloud cover, translates them into Uzbek, converts temperature to Celsius, replaces numbers with words, and returns a descriptive sentence abo...
def get_weather_json_to_word(): data = get_weather() weather_main = translate_to_uzbek(data.get('weather')[0].get('description')) # tuman temp_date = int(data.get('main').get('temp')) - 273 # int C numlik_date = data.get('main').get('humidity') # namlik % wind_date_speed = data.get('wind').get('s...
def reset_weights(self): """ Resets weights in order to reuse FFNN object for training """ if self.seed is not None: np.random.seed(self.seed) self.weights = list() for i in range(len(self.dimensions) - 1): weight_array = np.random.randn( ...
The function performs cross-validation by splitting data into folds, training the model on each fold, and averaging performance metrics across folds. It scales data, trains using a scheduler, and accumulates scores (e.g., accuracy, confusion matrices for logistic regression) for each fold. Results are averaged, with op...
def cross_val( self, folds: int, X: np.ndarray, t: np.ndarray, scheduler_class, *args, # arguments for the scheduler (sans batchsize) batches: int = 1, epochs: int = 1000, lam: float = 0, use_best_weights=False, ): """Crossvali...
def get_pr_data_loc(data, samples): result = [] for s_point in samples: # get k nearest points visual_angle = 2 * math.tan((CONE_DIAMETER / 2) / (s_point[1] + EPSILON)) * 180 / math.pi num_ideal_points = max(int(visual_angle * POINTS_PER_DEGREE), 1) s_point = toxy(s_point) ...
The main task of the code is to refine the estimated location of a cone (or object) using template matching on lidar data. It generates sample points around a center (LocX, LocY), calculates probability distributions for data and sample points, normalizes their product, and identifies the maximum probability point as t...
def template_matching(LocX, LocY, sigma, lidar_data, label=None, plot=False): # data_points = extract_data_points() data_points = lidar_data data_points_xy = toxy(data_points) sample_range = 3 * sigma sample_gap = 0.05 # how far each sample is from each other center_point_xy = [LocX, LocY] ...
def get_all_product_numbers_for_product_type(product_type_url): product_type = product_type_url.split("/")[-1] print(f"Collecting all product numbers for product type: {product_type}") all_product_numbers = [] product_list_pages = get_product_list_pages(product_type_url) for i, page in enumerate(p...
The main task of the code is to scrape product data for men's jackets from a website, parse each product page into structured data, and insert the information into a database. It retrieves product numbers, generates product links, extracts product details, and handles errors during database insertion, providing progres...
def main(): # Establish database connection db = REIClothingDatabase(REIClothingDatabase.REI_CLOTHING_DATABASE_PATH) # Get all jacket product numbers jacket_product_nums = get_all_product_numbers_for_product_type( urls.MENS_JACKETS) # Get all jacket product pages jacket_product_pages =...
def get_ghost_loc(layout): loc = dict() row = 0 for rows in layout: col = 0 for cols in rows: if (cols == 'W'): loc[0] = [row, col] elif (cols == 'X'): loc[1] = [row, col] elif (cols == 'Y'): loc[2] = [row, c...
This code simulates a Pacman game with multiple ghosts, alternating between Pacman's strategic moves and random ghost movements. It tracks scores, handles collisions, updates the game state, and determines the winner (Pacman or Ghost) based on eating all food or being caught. The solution string logs each step, layout ...
def reflex_play_multiple_ghosts(problem, verbose): #Your p4 code here seeds = problem[0] layout = problem[1] ghost_loc = get_ghost_loc(layout) pacman_loc = get_pacman_loc(layout) foods_loc = get_foods_loc(layout) solution = 'seed: ' + str(seeds) + '\n' solution += '0\n' + convert_m...
def compute_parts_2(base_ids, rebase=True): N = None H,W = base_ids.shape uids = F.unfold(base_ids[None,None].float(), (3,3), padding=1, stride=1).int().view(9,H,W) adjacency = (uids[:] == uids[4,:N]) & (uids[4,N] != 0) mask = adjacency[4] ptr = torch.arange(mask.numel()).view_as(mask) uptr ...
The code computes the recall of instance parts between ground truth (gt) and predictions (pred) by matching instances, counting matched instances and pixel areas. It calculates total and recalled instances/pixels, returning these metrics for evaluation.
def compute_om(gt, pred, scores): parts = compute_parts_2(gt) i_parts = instance_part_area(gt, parts) gt_pred, _, _ = compute_matching_masks(gt, pred) gt_pred = {g:p for g,p in gt_pred} parts_pred = compute_intersection_masks_scores(parts, pred, scores) total_par_instances = 0 recalled_par_...
def masks_to_ids(masks): ids = None for i, rle in enumerate(masks, 1): mask = mask_util.decode(rle) if ids is None: ids = torch.zeros(mask.shape, dtype=torch.int32) ids += mask*i return ids def stack_masks(masks): res = [] for rle in masks: mask = torch.te...
The code computes evaluation metrics (OM, OIR, DPR) by comparing ground truth (gt) and predicted (pred) masks. It processes each result pair, converts masks to IDs, aligns shapes, and calculates intersection/union scores. Metrics are aggregated across all results and returned as a dictionary with formatted print output...
def compute_metrics(self, results: list) -> dict: gri = gti = grp = gtp = 0 for gt, pred in results: gt_ids = masks_to_ids(gt['anns']) if gt_ids is None: gt_ids = torch.zeros((gt['height'],gt['width']),dtype=torch.int32) masks, scores = pred['masks'],...
def _check_random(self, explanation, similarity_metrics): model_copy = utils.clone_keras_model(self.model) original_explanation = explanation.explain(model_copy) self._randomize_all_layer_weights(model_copy) new_explanation = explanation.explain(model_copy) return self._get_resul...
The code evaluates randomization methods (complete, cascading, data) using specified explanations and similarity metrics. It processes input parameters, executes corresponding checks, logs results, generates dataframes, and optionally plots visualizations. The function returns structured dataframes for analysis. Your r...
def evaluate(self, randomization, explanation, similarity_metrics, **kwargs): """ randomization: string name of the randomization to perform explanation: the explanation(s) objects to run similarity metrics: list of similarity functions to compute """ if randomization i...
def rescale_image(image, size=None, percent=50, super_res = False, sr_model = None): if (super_res): return sr_model.upsample(image) if (percent == 100): return image if size == None: width = int(image.shape[1] * percent/ 100) height = int(image.shape[0] * percent/ 100) dim = (width, height) return cv2.r...
The code tracks a specified object in a video using a tracker (default: CSRT) between defined start and end frames. It scales frames, initializes the tracker on the first frame, updates it iteratively, and collects frame indices, original frames, and corresponding bounding boxes for tracking results.
def track_bbox_in_video(params, video_path, tracking_object, tracker_type = 'CSRT'): video = cv2.VideoCapture(video_path) if not video.isOpened(): print("Could not open video at path: " + video_path) sys.exit() original_frames = [] bboxes = [] frame_indices = [] frame_idx = 0 initialization = False scalin...
def build_portfolio(table, date, currency): df = read_db_transactions(table, date, currency) # Adjust for stock splits df['Units'] = df['Units'] * df['SplitRatio'] df['Price'] = df['Price'] / df['SplitRatio'] tickers = df['Ticker'].unique().tolist() portfolio = {ticker: Security(ticker) for t...
The code processes a portfolio of financial assets for multiple currencies, calculating unrealized gains, total value, and money-weighted rate of return (MWRR). It fetches stock prices, computes performance metrics, stores results in MongoDB, and sends notifications via Telegram. The script also logs execution time, me...
def main(): process = psutil.Process(os.getpid()) exec_time = 0 start_time = time.time() timing = eval(config["misc"]["Timing"]) data_table = {'contributions': config["mysql"]["ContributionTable"], 'trades': config["mysql"]["TransactionTable"]} result_table = {'CAD': config["my...
def get_scene(scenes, scene_key): for scene in scenes: if scene['key'] == scene_key: return scene raise Exception(f"Undefined scene for: {scene_key}") def game_ends(scene): if 'end' in scene and scene['end'] > '': return True else: return False def play_scene(scene, hero): display_scene(scen...
The code defines a game loop that starts at a given scene, processes each scene by updating the hero's state, transitions to the next scene based on the current scene's output, and repeats until the game ends, finally displaying the concluding scene.
def game(scenes, hero, start_key): scene = get_scene(scenes,start_key) while not game_ends(scene): next = play_scene(scene, hero) scene = get_scene(scenes,next) display_scene(scene)
def _build_forward(self): config = self.config N, M, JX, JQ, VW, VC, d, W = \ config.batch_size, config.max_num_sents, config.max_sent_size, \ config.max_ques_size, config.word_vocab_size, config.char_vocab_size, config.hidden_size, \ config.max_word_size prin...
This code initializes a TensorFlow model for a question-answering task, defining input placeholders, global step tracking, and building forward computation and loss functions. It sets up variables for word/character embeddings, attention masks, and answer strings, while preparing for training with EMA (exponential movi...
def __init__(self, config, scope, rep=True): self.scope = scope self.config = config self.global_step = tf.get_variable('global_step', shape=[], dtype='int32', initializer=tf.constant_initializer(0), trainable=False) # Define forward inputs her...
def extract_main_content(pdf_path, doc_ref, verbose= True): if verbose: logger.log(f".extract_main_content - opening path: {pdf_path}") doc = fitz.open(pdf_path) full_text = "" chunk_size = 2 # Number of pages to read at a time output_s = analyze_cover(doc.load_page(0).get_text()) if verbose:...
This function processes an article by extracting its content, splitting it into token-limited chunks if necessary, and generating summaries for each chunk. It returns structured output with metadata, summaries, and organized parts, handling large texts by chunking and summarizing while preserving author, title, and jou...
def process_article(file_path, doc_ref, verbose= False): logger.log(f'process_article.verbose: {verbose}') output = extract_main_content(file_path, doc_ref) encoding = tiktoken.encoding_for_model("gpt-3.5-turbo") tokens = encoding.encode(output["text"]) n_tokens = len(tokens) large_threshold =...
def extract_chapters_from_epub(book): chapters = [] encoding = tiktoken.get_encoding("cl100k_base") for item in book.items: if isinstance(item, epub.EpubHtml): content = item.get_body_content() soup = BeautifulSoup(content, 'html.parser') title = extract_text_from...
The function processes an EPUB file into a structured dictionary containing the book's title, author, chapter content, total token count, and coverage percentage of tokens in content. It combines chapter content into items based on token ranges (5000-14000) and logs key metrics for analysis.
def process_epub_to_book_dict(epub_file): book = epub.read_epub(epub_file) encoding = tiktoken.get_encoding("cl100k_base") book_dict = { 'title': book.get_metadata('DC', 'title')[0][0], 'author': book.get_metadata('DC', 'creator')[0][0], 'content': extract_chapters_from_epub(book), ...
def reset_move_state(self): self.user_move = None self.correct_move = False def print_info(self): print(self.keyboard_instruction) if self.message: print(self.message) self.message = None def check_board(self, new_figure=False): current_board = self.board....
The code processes user input in a game loop, validating moves for a game board, updating game state, and handling exceptions like invalid moves or game over conditions. It continuously checks for valid moves, updates the figure's position, and manages transitions to new figures or game termination.
def start(self): while True: while not self.new_figure_needed: self.reset_move_state() while not self.correct_move: self.print_info() self.user_move = get_char() if self.user_move == EXIT: ...
def get_urls(sent): Base_string = "https://www.google.com/search?q=" Google_Search = Base_string + sent res = requests.get(Google_Search) soup = BeautifulSoup(res.text, 'html5lib') links_list = [] links = soup.findAll("a") for link in links: link_href = link.get('href') if...
The function `check_one_sent` extracts URLs from a given sentence, retrieves text from each URL, compares the original words of the sentence against the retrieved website content, and returns a list of comparison results along with the URLs.
def check_one_sent(sent): ans = [] url = get_urls(sent) for x in url: website_words = get_text_from_url(x) original_words = get_original_words(sent) ans.append(check(original_words, website_words)) return ans, url
def print_board(board): for row in board: print(" | ".join(row)) print("---------") def find_best_move(board): best_val = -math.inf best_move = (-1, -1) for i in range(3): for j in range(3): if board[i][j] == " ": board[i][j] = "O" mov...
This code implements a Tic-Tac-Toe game where Player X (human) inputs moves, while Player O (AI) uses a best-move algorithm. The game alternates turns, updates the board, checks for wins/ties after each move, and ends when a player wins or the board fills with no winner.
def play_game(): board = [[" " for _ in range(3)] for _ in range(3)] current_player = "X" while True: print_board(board) if current_player == "X": row = int(input("Enter row (0, 1, or 2): ")) col = int(input("Enter column (0, 1, or 2): ")) if board[row][...
def __check_if_downloaded(context: BrowserContext, url: str, directory: str, last_modified: datetime.datetime) -> bool: info = head(context, url, last_modified) if info is None: return True last_modified = info['last_modified'] filename = info['filename'] print(last_modified, filename) ...
The main task of the code is to download a file from a given URL using browser context cookies, check if it's already downloaded, and save it to a specified directory with the correct filename derived from the Content-Disposition header, handling streaming data in chunks for efficiency.
def __download_file(context: BrowserContext, url: str, directory: str, last_modified: datetime.datetime): # don't download if already downloaded if __check_if_downloaded(context, url, directory, last_modified): return jar = __get_cookie_jar_from_context(context, url) res = requests.get(url, co...